Home > Back-end >  Outputting replaced arrays | Penny Pitch Game
Outputting replaced arrays | Penny Pitch Game

Time:11-06

This program tosses up 5 coins on a board of numbers. The board is displayed as:

1 1 1 1 1

1 2 2 2 1

1 2 3 2 1

1 2 2 2 1

1 1 1 1 1

So I'm having trouble of coming up with a way to output a 'P' or any letter really on the cells the "coin" landed on. It should look something like this:

1 P 1 1 1

1 2 2 2 P

P 2 3 P 1

1 P 2 2 1

1 1 1 1 1

A small section of code in this program would then add up the number the coins landed on

 public static void penny(String [] args){
 Scanner reader = new Scanner(System.in);
    Random gen = new Random();
    int total = 0;
    Boolean p = true;
    int [][] array = {{1,1,1,1,1},
                    {1,2,2,2,1},
                    {1,2,3,2,1},
                    {1,2,2,2,1},
                    {1,1,1,1,1}};
    String [][] penny = {{"P","P","P","P","P"},
                    {"P","P","P","P","P"},
                    {"P","P","P","P","P"},
                    {"P","P","P","P","P"},
                    {"P","P","P","P","P"}};
    System.out.println("Press Enter to commence penny operation.");
    String Enter = reader.nextLine();
    for (int row = 0; row < 1; row  ){
      for (int col = 0; col < 5; col  ){
        System.out.print(array[row][col]   " ");
        }
    }
System.out.print("\n");
    for (int row = 1; row < 2; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(array[row][col]   " ");
    }
}
System.out.print("\n");
    for (int row = 2; row < 3; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(array[row][col]   " ");
    }
}
System.out.print("\n");
    for (int row = 3; row < 4; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(array[row][col]   " ");
    }
}
System.out.print("\n");
    for (int row = 4; row < 5; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(array[row][col]   " ");
            
    }
}

int penny1 = array[gen.nextInt(5)][gen.nextInt(5)];
int penny2 = array[gen.nextInt(5)][gen.nextInt(5)];
int penny3 = array[gen.nextInt(5)][gen.nextInt(5)];
int penny4 = array[gen.nextInt(5)][gen.nextInt(5)];
int penny5 = array[gen.nextInt(5)][gen.nextInt(5)];



for (int index = 1; index < 4; index  ){
    if (penny1 == index){
        total = total   index;
        }
    if (penny2 == index){
        total = total   index;
    }
    if (penny3 == index){
        total = total   index;
    }
    if (penny4 == index){
        total = total   index;
    }
    if (penny5 == index){
        total = total   index;
    }
}
System.out.print("\nPress Enter for total");
String Enter2 = reader.nextLine();
System.out.print("\ntotal is: "   total   "\n");
System.out.print("\nPress Enter to display where the pennies landed");
String Enter3 = reader.nextLine();
for (int row = 0; row < 1; row  ){
      for (int col = 0; col < 5; col  ){
        System.out.print(penny[row][col]   " ");
        }
    }
System.out.print("\n");
    for (int row = 1; row < 2; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(penny[row][col]   " ");
    }
}
System.out.print("\n");
    for (int row = 2; row < 3; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(penny[row][col]   " ");
    }
}
System.out.print("\n");
    for (int row = 3; row < 4; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(penny[row][col]   " ");
    }
}
System.out.print("\n");
    for (int row = 4; row < 5; row  ){
        for (int col = 0; col < 5; col  ){
            System.out.print(penny[row][col]   " ");
            
    }
}

}

CodePudding user response:

The penny positions are lost immediately when they are created, e.g. int penny1 = array[gen.nextInt(5)][gen.nextInt(5)]. You need to store the generated values or to apply them instantly.

I suggest that you fill 'String [][] penny' with the values from 'int [][] array' (with ints converted to strings, of course), and when the penny positions are created overwrite the values in 'penny'.

CodePudding user response:

One way you can do this is to utilize two 2D arrays. One to hold the original game board elements for getting scores and another to place the randomly generated penny locations within the matrix.

In order to randomly place the pennies, you would want to iterate through the number of pennies to be thrown and the randomly generate an matrix Row index value and also a random matrix column index value for each penny. Place the penny locations within the matrix accordingly as these random values are generated.

Here is a runnable example:

public class PennyPinchGameDemo {
    
    /* The actual game board. This board will always remain the same
       and is used to create a new play board and to gather scores. */
    private char[][] GAME_BOARD = {{'1', '1', '1', '1', '1'},
                                   {'1', '2', '2', '2', '1'},
                                   {'1', '2', '3', '2', '1'},
                                   {'1', '2', '2', '2', '1'},
                                   {'1', '1', '1', '1', '1'}};
    
    /* The original board to play on. The elements in this particular 
       board will change depending on where the pennies will randomly
       fall.                           */
    private char[][] board_In_Play = {{'1', '1', '1', '1', '1'},
                                      {'1', '2', '2', '2', '1'},
                                      {'1', '2', '3', '2', '1'},
                                      {'1', '2', '2', '2', '1'},
                                      {'1', '1', '1', '1', '1'}};
    
    private final java.util.Random random = new java.util.Random();  // Declare a Random object.
    
    /* Default number of pennies in game. This value can be changed
       using the setNumberOfPennies() Setter method.   */
    private int numberOfPennies = 5;    
    
    private int overallScore;
    
    // Constructor #1:
    public PennyPinchGameDemo() { }
    
    // Constructor #2:
    public PennyPinchGameDemo (int numberOfPennies) {
        setNumberOfPennies(numberOfPennies);
    }
    
    // Constructor #3:
    public PennyPinchGameDemo (char[][] GAME_BOARD, int numberOfPennies) {
        setGAME_BOARD(GAME_BOARD);
        setNumberOfPennies(numberOfPennies);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // App started this way so as to avoid the need for statics.
        new PennyPinchGameDemo().startApplication(args);
    }
    
    private void startApplication(String[] args) {
        displayGameBoard();                       // Display the original Game Board;
        System.out.println("Pennies Toss...\n");  // Indicate a Pennies Toss;
        doPennyToss();                            // Carry out the pennies toss; 
        displayScore();                           // Display the Score.
    }
    
    private void displayGameBoard() {
        for (char[] rows : board_In_Play) {
            /* Display each row of the Game Board row using the
               Arrays.toString() method but remove the open.close
               square brackets, commas, and double space the elemental
               values.         */
            System.out.println(java.util.Arrays.toString(rows)
                               .replaceAll("[\\[\\],]", "").replace(" ", "  "));
        }
        System.out.println();  // Blank line for esthetics.
    }
    
    private void doPennyToss() {
        // Create a new board to play in...
        for(int i=0; i < board_In_Play.length; i  ) {
            System.arraycopy(GAME_BOARD[i], 0, board_In_Play[i], 0, board_In_Play[i].length);
        }
        
        int randomRow;    // Will hold the randomly generated Matrix ROW index value
        int randomColumn; // Will hold the randomly generated Matrix COLUMN index value
        /* Iterate throught the number of pennies to be thrown
           and generate a random Row and Column matrix index 
           values then place each penny in the game board at 
           those index values generated.
        */
        for (int i = 0; i < numberOfPennies; i  ) {
            // Generate random matrix Row index value.
            randomRow = random.nextInt(board_In_Play.length);
            // Generate random matrix Column index value.
            randomColumn = random.nextInt(board_In_Play[0].length);
            /* If there is already a penny located at the above 
               randomly generated row/column index values then
               try again (redo this particular iteration)... */
            if (board_In_Play[randomRow][randomColumn] == 'P') {
                i--;
                continue;
            }
            /* No penny located at this randomly generated
               Row/Column index values so place the penny 
               at that location.              */
            board_In_Play[randomRow][randomColumn] = 'P';
        }
        
        // Now display the game board with the pennies in position.
        displayGameBoard();
    }
    
    private void displayScore() {
        this.overallScore = 0;  // Will hold the overall score.
        /* Iterate through the game board matrix and when a 
           penny is encountered at a specific location then
           get the score value form the Original GAME BOARD
           matrix based on the very same Row/Column index 
           values. Convert that element character value to
           and integer value and add it to the overall Score.  */
        for (int r = 0; r < board_In_Play.length; r  ) {
            for (int c = 0; c < board_In_Play[r].length; c  ) {
                if (board_In_Play[r][c] == 'P') {
                    this.overallScore  = Integer.parseInt(Character.toString(GAME_BOARD[r][c]));
                }
            }
        }
        // Display the Score.
        System.out.println("Score: --> "   this.overallScore);
    }
    
    // Getters & Setters (if you want them)
    /* Some Setter methods are required since they 
       are used in some constructors.    */
    public final char[][] getBoard_In_Play() {
        return board_In_Play;
    }

    public final void setBoard_In_Play(char[][] board_In_Play) {
        this.board_In_Play = board_In_Play;
    }

    public final char[][] getGAME_BOARD() {
        return GAME_BOARD;
    }

    public final void setGAME_BOARD(char[][] GAME_BOARD) {
        this.GAME_BOARD = GAME_BOARD;
    }
    
    public final int getNumberOfPennies() {
        return numberOfPennies;
    }

    public final void setNumberOfPennies(int numberOfPennies) {
        int maxAllowablePenies = board_In_Play.length * board_In_Play[0].length;
        if (numberOfPennies > maxAllowablePenies) {
            this.numberOfPennies = maxAllowablePenies;
        }
        else {
            this.numberOfPennies = numberOfPennies;
        }
    }
    
}
  • Related