Speedo
Speedo

Reputation: 55

Placing pieces on 2D array gameboard

I'm trying to make a program where there's an 8x8 game board of asterisks. The user has to place eight pieces on the board so that there's one piece in each row but the user can input which column the piece is located in each row. Lastly, I want to print a visual of the board after they decide where in each row to place each piece. For example, if they enter: 4, 1, 7, 0, 6, 4, 3, 2 it would look like ***P**** (P = piece) for the first row of the board with the pieces in the correct column for the other seven rows. In my code right now, I have created the 8x8 game board and I have filled the board with 0s (don't know how to make it asterisks). I am now at the point where I need the user input to put the pieces in the correct column for each row but am struggling to do so. I appreciate everyone who decides to help me!

public void problem3(){
    Scanner in = new Scanner(System.in);
    char[][] board = new char[8][8];//Initializes an 8x8 board

    //This creates the 8x8 board and fills the board with asterisks
    for (char row = 0; row < board.length; row++) {
        for (char column = 0; column < board[0].length; column++) {
            board[row][column] = '*';
        }
    for (row = 0; row < 8; row++) { //creates right amount of cells for 8 rows 
        for (char column=0; column<8; column++) { //creates right amount of cells for the 8 columns
            System.out.print(board[row][column] + " "); //prints # of cells
        }
                System.out.println(); //prints each row on new line
    }
    }       
        for (int row = 0; row < 8; row++) {
            int col = 0;
            System.out.println("In which column would you like to place the queen for column ");
            col = in.nextInt();
            board[row][col] = 'P'; //mark board with "P"
            }
        for (int i=0; i<8; i++) { //loops prints board
              System.out.println(Arrays.toString(board[i]));
            }
    }

Upvotes: 0

Views: 2602

Answers (1)

SMA
SMA

Reputation: 37023

  • Use appropriate data type. Now since you need "*" and "P", character instead of int seems better.
  • Initialize them with '*' instead of 0
  • loop in for each "row" to get input from user 8 (0-7) times
  • When user inputs the int data, you know its a column of row mentioned in above step, so take the data like:

    col = in.nextInt();
    board[row][col] = 'P';//mark it with p. You may need to validate input column added by user is in range of 0-7?
    
  • Print the board like:

      for (int i=0; i<8; i++) {
          System.out.println(Arrays.toString(board[i]));
      }
    

Upvotes: 1

Related Questions