简体   繁体   中英

2D Arrays: TicTacToe program

The program I have below is a Tic Tac Toe game. Here are the details of the assignment:

TicTacToe

  • Store the game board in a single 2D array. (3 x 3) X
  • method to add a move.
  • method to display the board.
  • method to tell whose turn it is (X or O).
  • method to find a winner or tie.
  • method to initialize the game to the beginning.
  • Main method that allows two players to enter their turns on the same keyboard.

My problem is that I don't know how to take coordinates entered by the user and turn them into an "X" or "O" value for the user's turn into the array which it then displays onto the board itself for the user after they make each play. There are compiling errors on line; ticTac.showBoard(char[][] displayArray) ;. Any other comments and errors you have on how to simplify things or errors you see are definitely welcome!

public class TicTacToeMain //main class that runs the system.
    {
      public static void main(String[] args)
      {

        System.out.println("             TIC TAC TOE");
        System.out.println();
        System.out.println("Instruction: You will be asked to enter the row number(0-2) and the column number(0-2) of");
        System.out.println("the board you wish to play your piece. You are to decide which player is X's and O's and");
        System.out.println("to move as prompted. X's always start first. To win you need to place 3 pieces in a row ");
        System.out.println("horizontally, vertically, or diagonally. An example of the board layout is below. Enjoy!");
        System.out.println();
        System.out.println("  0   1   2");
        System.out.println();
        System.out.println("0");
        System.out.println();
        System.out.println("1");
        System.out.println();
        System.out.println("2");
        System.out.println();

        TicTacToe ticTac = new TicTacToe();
        ticTac.showBoard(char[][] displayArray); //SYNTAX ERROR ON TOKEN "char" and "displayArray".
        ticTac.readInput();



      }
    }





import java.util.Scanner;

public class TicTacToe //helper methods class.
{
  private int moveCount;
  private char playerTurn;
  private int row, col;
  private char[][] board = new char[3][3];

  public TicTacToe() //constructor method
  { 
    char[][] board = new char[3][3];
    for(char row = 0 ; row < 3; row++)
      for(int col = 0; col < 3; col++)
      board[row][col] = ' ';
   playerTurn = 'X';
    moveCount = 0;



  }
   public void findResult() //constructor to find winner/tie and print to user.
  {
     this.setPlayerTurn();


     if(board[row][0] == board[row][1] && board[row][1] == board[row][2] && (board[row][0] == 'X' || board[row][0] == 'O'))
      System.out.println( + playerTurn + " wins!");

    else if(board[0][col] == board[1][col] && board[1][col] == board[2][col] && (board[0][col] == 'X' || board[0][col] == 'O'))
      System.out.println( + playerTurn + " wins!");

    else if(board[0][0] == board[1][1] && board[1][1] == board[2][2] && (board[0][0] == 'X' || board [0][0] == 'O'))
      System.out.println( + playerTurn + " wins!");

    else if(board[2][0] == board [1][1] && board[1][1] == board[0][2] && (board [2][0] == 'X' || board[2][0] == 'O'))
      System.out.println( + playerTurn + " wins!");

    else if(moveCount == 9)
     System.out.println("Tie game!");

}

 public void readInput() //method to read user input.
  {
    int newRow, newCol;
    this.setPlayerTurn();
    do
    {
    Scanner keyboard = new Scanner(System.in);

      this.setPlayerTurn();
    System.out.println("Turn " + moveCount);
    System.out.println("Player " + playerTurn + " please select the row you wish to place your next move.");
    newRow = keyboard.nextInt();
    if(newRow < 0 || newRow > 2)
       System.out.println("Invalid Entry. Please re-enter.");
    else
    {
      row = newRow;
    System.out.println("Now, enter the column.");
    newCol = keyboard.nextInt();
    if(newCol > 2 || newCol < 0)
    System.out.println("Invalid Entry. Please re-enter.");
    else
      col = newCol;
      moveCount++;
      System.out.println("You entered row " + row + " and column " + col +".");
      System.out.println();
      findResult();
    }
    }while(moveCount <= 8);


  }

  public  void showBoard(char[][]displayArray) //to add inputs to as well as  display board.
  {
    int rowInput, colInput;
    readInput();
    rowInput = row;
    colInput = col;
    for(rowInput = 0; rowInput < displayArray.length; row++)
     {
      for(colInput = 0; colInput < displayArray[row].length; col++)
      System.out.print(" " + displayArray[row][col] + " ");
      System.out.println();
    }
  }

  private char setPlayerTurn() //method to find which players turn it is.
  {
    {
    if (moveCount == 0 || moveCount % 2 == 0)
      playerTurn = 'X'; 
    else
      playerTurn = 'O';
    }
    return playerTurn;



}

}

Change your call to showboard in your main to

ticTac.showBoard(); 

Since you already have the board within a TicTacToe object.

Then showBoard() should look like this:

 public  void showBoard() //to add inputs to and display board.
  {
    int rowInput, colInput;
    readInput();
    rowInput = row;
    colInput = col;
    for(rowInput = 0; rowInput < board.length; row++)
     {
      for(colInput = 0; colInput < board[row].length; col++)
      System.out.print(" " + board[row][col] + " ");
      System.out.println();
    }
  }

The reason for this is because your TicTacToe object already has a board, you do not need to pass it one.

Also, as another tip, you don't need another class to run your TicTacToe. You can simply put the main inside of TicTacToe, like so:

public class TicTacToe {

public TicTacToe(...){
...
}
public static void main(String[] args){
...read inputs and make board here...
}

...other methods...

}

It's a little confusing at first to be creating an instance of your class in the main of your class but you'll get used to it...and you'll have a lot less files :-).

A note of caution when doing this though, you do need to create an object of your class to use its methods within your main because main is a "static" method. static methods are allocated before everything else in the program and main is the first that runs in a java program so, if you don't create the object, main doesn't know how to get access to the methods inside of it. Hopefully that didn't cause more confusion than it was worth.

As another pointer, if you really were trying to create a new 2d char array to pass to that method you could have done it like so

ticTac.showBoard(new char[3][3]);

I don't know how to take the coordinates entered by the user and turn it into an x or o value for the play into the array and then displaying the board itself.

You are most of the way there in readInput . You have the row and col coordinates input from the user. In the same way you look at the value in board[row][col] when displaying the board, and board[row][0] when checking for a win, you want to set the location in board array to the current player. This can be done by saying board[something][something] = value . What should something and value be?

Any other comments and errors you have on how to simplify things or errors you see are definitely welcome!

It looks like almost all of the pieces of the program are there and completed. However, the flow of the program tying everything together has a few problems. There are a couple of principles of programming that may apply here:

  • SRP (Single Responsibility Principle) : Each unit of a program should have only a single purpose
  • SoC (Separation of Concerns) : Each module or unit should have a clear dividing line. Two methods should not partially overlap in what they do.

With these ideas in mind, I will offer a couple of comments on your program flow:

  1. Often you can tell if you have a clean design if the names of the methods are what they actually do. For example, findResult() makes a call to setPlayerTurn() . That is misleading because the current player changes every time you simply want to check the game result. When exactly should you switch turns?
  2. Who's job is it to display the board? You are displaying the board in the main program, but you never see that because readInput() loops 8 times before you ever reach the call to showBoard() . Showing the board should probably be the responsibility of TicTacToe . The main method should just kick off the game.
  3. Does readInput() read input, or play the whole game? It sounds like it should read one set of coordinates input, but it has a loop that processes the whole game. It may make more sense to separate that into two methods - one that handles a single move, and one that loops through 9 times, displaying the board and calling the readInput() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM