Tic Tac Toe Game | Two Player | 3x3 grid

In summary: Checks to see if player has won the game. if (determineWinner() == 1) return "Player one won"; else if (determineWinner() == 2) return "Player two won"; else if (determineWinner() == 0) return "It's a 'cat
  • #1
iamjon.smith
117
3
Assignment:
TicTacToe and TicTacToeGame.

The TicTacToe class contains a 3x3 two-dimensional array of integers. The constructor should initialize the empty board to all zeros. It should have a method playerMove that accepts two integers as parameters, the first is the player (1 or 2) and the second is the actual move (1-9). If it is a valid move it changes the value of that square to 1 or 2 (depending on whose turn it is and returns the Boolean value true to indicate a valid move has been completed). If it is not a valid move the board does not change and it returns a Boolean value of false to indicate an invalid move. TicTacToe should also have the method displayBoard that will display the current state of the board. The last method should be determineWinner which returns a 1 if player one won, a 2 if player 2 won, a 0 if it’s a ‘cat’s game’, and -1 if there is no winner yet and the game is not over.

Here is my TicTacToeClass
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tictactoetest;

/**
 *
 * @author Jon and Jessica
 */
public class TicTacToe {

    private int player = 1;
    private int gameBoard[][] = new int[3][3];

    public TicTacToe(){
    // Initializes all elements to the array of 0; nested for loop
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    gameBoard[i][j] = 0;
                }

            }
    }

    public TicTacToe( int [][] gameBoard){
        setGameBoard(gameBoard);
    }
    /**
     * @return the player
     */
    public int getPlayer() {
      
      return player;
    }

    /**
     * @param player the player to set
     */
    public void setPlayer(int player) {
        this.player = player;
    }

    /**
     * @return the gameBoard
     */
    public int[][] getGameBoard() {
        return gameBoard;
    }

    /**
     * @param gameBoard the gameBoard to set
     */
    public void setGameBoard(int[][] gameBoard) {
        this.gameBoard = gameBoard;
    }

   public String gamePiece (int player){
      String result = "";
      if (player == 1){
          result = "X";
      }else if (player == 2){
          result = "O";
      }
      return result;
   }
    
    // Accepts row and column from player. If move made is invalid, it will still be current player's turn.
    public boolean playerMove(int row, int col) {

        // Initialize boolean move
        boolean move;

        // Checks to see if board location is occupied and a move can be made
        if (gameBoard[row -1][col -1] == 0)
            {
            gameBoard[row-1][col-1] = player;

            return true;
            }
        else
        {
        // The specified cell is already occupied.
            move = false;
        }
            return move;
        }

        public boolean isGameOver(){

            boolean gameOver = true;

            for (int i = 0; i < 3; i++){
                for (int j = 0; j < 3; j++){
                    if (gameBoard[i][j] == 0){
                        gameOver = false;
                    }
                }
            }
            return gameOver;
        }
        // Method to check rows, columns, and diaganals for winner

        public int gameWinner(){

            int winner = 0;

            // check row 1 for winner
        if (gameBoard[0][0] == gameBoard[0][1] && gameBoard[0][0] == gameBoard[0][2] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check row 2 for winner
        if (gameBoard[1][0] == gameBoard[1][1] && gameBoard[1][0] == gameBoard[1][2] && gameBoard[1][0] != 0 ){

            winner = gameBoard[1][0];
        }
            // check row 3 for winner
        if (gameBoard[2][0] == gameBoard[2][1] && gameBoard[2][0] == gameBoard[2][2] && gameBoard[2][0] != 0 ){

            winner = gameBoard[2][0];
        }
            // check column 1 for winner
        if (gameBoard[0][0] == gameBoard[1][0] && gameBoard[0][0] == gameBoard[2][0] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check column 2 for winner
        if (gameBoard[0][1] == gameBoard[1][1] && gameBoard[0][1] == gameBoard[2][1] && gameBoard[0][1] != 0 ){

            winner = gameBoard[0][1];
        }
            // check column 3 for winner
        if (gameBoard[0][2] == gameBoard[1][2] && gameBoard[0][2] == gameBoard[2][2] && gameBoard[0][2] != 0 ){

            winner = gameBoard[0][2];
        }
            // check first diagonal row for winner;
        if (gameBoard[0][0] == gameBoard[1][1] && gameBoard[0][0] == gameBoard[2][2] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check second diagonal for winner
        if (gameBoard[0][2] == gameBoard[1][1] && gameBoard[0][2] == gameBoard[2][0] && gameBoard[0][2] != 0 ){

            winner = gameBoard[0][2];
        }
            return winner;

        }

        // Display board after each input
        public void showBoard(){

            System.out.println("Tic Tac Toe Game\n" + "-----------");
            for(int i = 0; i < 3; i++){

                for (int j = 0; j < 3; j++){

                    System.out.print(gameBoard[i][j] + " | ");
                }
                System.out.println("\n-----------");

            }

        }

}

Here is the main method:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tictactoetest;
import java.util.Scanner;
/**
 *
 * @author Jon and Jessica
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //Variable declaration
        int row;
        int column;

        TicTacToe ttt = new TicTacToe();
        Scanner input = new Scanner(System.in); // accept user input
            System.out.println("Welcome to Tic Tac Toe!\n Player 1 = X\n Player 2 = O");

        while(ttt.gameWinner() == 0 && !ttt.isGameOver()){

            ttt.showBoard();

            // Get next player move
            System.out.println("Player " + ttt.getPlayer());
            System.out.println("Place your piece!");
            System.out.println("Please enter the row (1-3)");
            row = input.nextInt();

            // Trap for invalid row number
            while(row < 1 || row > 3){
                System.out.println("That is not a valid row!");
                System.out.println("Please re-enter row 1 - 3");
                row = input.nextInt();
            }
            System.out.println("Please Enter Column (1-3)");
            column = input.nextInt();

            // Trap for invalid column
            while(column < 1 || column > 3){
                System.out.println("That is not a valid column!");
                System.out.println("Please re-enter column 1 - 3");
                column = input.nextInt();
            }
            while(!ttt.playerMove(row,column)){
                System.out.println("That is not a valid move... please try again!");
                System.out.println("Please enter the row 1-3");
                row = input.nextInt();

                // Trap for invalid entry
                while(row < 1 || row > 3){
                    System.out.println("That is not a valid row, try again.");
                    System.out.println("Please enter row 1-3");
                    row = input.nextInt();
                }

                System.out.println("Please enter column 1-3");
                column = input.nextInt();

                // Trap for invalid entry
                while (column < 1 || column > 3){
                    System.out.println("That is not a valid column, try again.");
                    System.out.println("Please enter column 1-3");
                    column = input.nextInt();
                }
            }
        }
        // If the loop was exited because there are no moves left, it's a tie, or "Cat's Game"
        if(ttt.gameWinner() == 0){
            System.out.println("Sorry...Cat's Game!");
        }
        else{
               // Since player auto advances, once game is over, winner is previous player
            System.out.println("The winner is Player ");
            if(ttt.getPlayer() == 1){
                System.out.println("2");
            }
            else{
                System.out.println("1");
            }
        }
    }

}

problems I am having:

1. The program accepts user input, determines position, and displays move, but it doesn't switch players. It is always player 1's turn.

2. Instead of displaying a 1 or 2 for the player, I need it to display an X for player one and a O for player 2.

What am I overlooking?
 
Physics news on Phys.org
  • #2


I cleaned up the code in the class a little bit and removed some unnecessary stuff. Here is the cleaned/commented code.

Tic Tac Toe Class
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tictactoetest;

/**
 *
 * @author Jon and Jessica
 */
public class TicTacToe {

    private int player;
    private int gameBoard[][] = new int[3][3];

    public TicTacToe(){
    
        player = 1;

        for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    gameBoard[i][j] = 0;
                }

            }
    }

      /**
     * @return the player
     */
    public int getPlayer() {
     
      return player;
    }

    /**
     * @param player the player to set
     */
    public void setPlayer(int player) {
        this.player = player;
    }

    /**
     * @return the gameBoard
     */
    public int[][] getGameBoard() {
        return gameBoard;
    }

    // Accepts row and column from player. If move made is invalid, it will still be current player's turn.
    public boolean playerMove(int row, int column) {

        // Initialize boolean move
        boolean move;

        // Checks to see if board location is occupied and a move can be made
        if (gameBoard[row -1][column -1] == 0)
            {
            gameBoard[row -1][column -1] = player;

            move = true;
            }
        else
        {
        // The specified cell is already occupied.
            move = false;
        }
            return move;
        }

        public boolean isGameOver(){

            boolean gameOver = true;

            for (int i = 0; i < 3; i++){
                for (int j = 0; j < 3; j++){
                    if (gameBoard[i][j] == 0){
                        gameOver = false;
                    }
                }
            }
            return gameOver;
        }
        // Method to check rows, columns, and diaganals for winner

        public int gameWinner(){

            int winner = 0;

            // check row 1 for winner
        if (gameBoard[0][0] == gameBoard[0][1] && gameBoard[0][0] == gameBoard[0][2] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check row 2 for winner
        if (gameBoard[1][0] == gameBoard[1][1] && gameBoard[1][0] == gameBoard[1][2] && gameBoard[1][0] != 0 ){

            winner = gameBoard[1][0];
        }
            // check row 3 for winner
        if (gameBoard[2][0] == gameBoard[2][1] && gameBoard[2][0] == gameBoard[2][2] && gameBoard[2][0] != 0 ){

            winner = gameBoard[2][0];
        }
            // check column 1 for winner
        if (gameBoard[0][0] == gameBoard[1][0] && gameBoard[0][0] == gameBoard[2][0] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check column 2 for winner
        if (gameBoard[0][1] == gameBoard[1][1] && gameBoard[0][1] == gameBoard[2][1] && gameBoard[0][1] != 0 ){

            winner = gameBoard[0][1];
        }
            // check column 3 for winner
        if (gameBoard[0][2] == gameBoard[1][2] && gameBoard[0][2] == gameBoard[2][2] && gameBoard[0][2] != 0 ){

            winner = gameBoard[0][2];
        }
            // check first diagonal row for winner;
        if (gameBoard[0][0] == gameBoard[1][1] && gameBoard[0][0] == gameBoard[2][2] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check second diagonal for winner
        if (gameBoard[0][2] == gameBoard[1][1] && gameBoard[0][2] == gameBoard[2][0] && gameBoard[0][2] != 0 ){

            winner = gameBoard[0][2];
        }
            return winner;

        }

        // Display board after each input
        public void showBoard(){

            System.out.println("Tic Tac Toe Game\n" + "-----------");
            for(int i = 0; i < 3; i++){

                for (int j = 0; j < 3; j++){

                    System.out.print(gameBoard[i][j] + " | ");
                }
                System.out.println("\n-----------");

            }

        }

}

and here is the main method

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tictactoetest;
import java.util.Scanner;
/**
 *
 * @author Jon and Jessica
 */
public class TicTacToeTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //Variable declaration
        int row;
        int column;

        TicTacToe ttt = new TicTacToe();
        Scanner input = new Scanner(System.in); // accept user input
            

        while(ttt.gameWinner() == 0 && !ttt.isGameOver()){
            System.out.println("Welcome to Tic Tac Toe!\n Player 1 = X\n Player 2 = O");
            ttt.showBoard();

            // Get next player move
            System.out.println("Player " + ttt.getPlayer());
            System.out.println("Place your piece!");
            System.out.println("Please enter the row (1-3)");
            row = input.nextInt();

            // Trap for invalid row number
            while(row < 1 || row > 3){
                System.out.println("That is not a valid row!");
                System.out.println("Please re-enter row 1 - 3");
                row = input.nextInt();
            }
            System.out.println("Please Enter Column (1-3)");
            column = input.nextInt();

            // Trap for invalid column
            while(column < 1 || column > 3){
                System.out.println("That is not a valid column!");
                System.out.println("Please re-enter column 1 - 3");
                column = input.nextInt();
            }
            // When a move is invalid, have player make new move
            while(!ttt.playerMove(row, column)){
                System.out.println("That is not a valid move... please try again!");
                System.out.println("Please enter the row 1-3");
                row = input.nextInt();

                // Trap for invalid entry
                while(row < 1 || row > 3){
                    System.out.println("That is not a valid row, try again.");
                    System.out.println("Please enter row 1-3");
                    row = input.nextInt();
                }

                System.out.println("Please enter column 1-3");
                column = input.nextInt();

                // Trap for invalid entry
                while (column < 1 || column > 3){
                    System.out.println("That is not a valid column, try again.");
                    System.out.println("Please enter column 1-3");
                    column = input.nextInt();
                }
            }
        }
        // If the loop was exited because there are no moves left, it's a tie, or "Cat's Game"
        if(ttt.gameWinner() == 0){
            System.out.println("Sorry...Cat's Game!");
        }
        else{
               // Since player auto advances, once game is over, winner is previous player
            System.out.println("The winner is Player ");
            if(ttt.getPlayer() == 1){
                System.out.println("2");
            }
            else{
                System.out.println("1");
            }
        }
    }

}

I still have the same issue though. The board displays correctly on start up, the first player makes the first move, this also displays correctly. Now is where the first problem occurs;
It doesn't switch to player 2, it just asks player 1 to make the next move. What am I missing?

Also, when the player makes a move, the move is displayed on the board as "1" for player 1, and (I assume since it won't switch to player two) a "2" for moves made by player 2. I would like to make this change to "X" for player 1 and "O" for player 2. Could someone please please point me in the right direction to finish this up. It is due tomorrow night!
 
  • #3


Please, someone, can you look at this java Tic Tac Toe code and help with the issues listed. The assignment is due tonight and I can not, for the life of me, figure out what I am missing. The program doesn't switch players and I need to show X and O for player 1 and 2 respectively. Please, someone, anyone, help me!
 
  • #4
It may help if you try think about what "changing player" means in terms of the field variables used by your TicTacToe class (hint: where is the code that call the setPlayer method?)

Likewise for your print-out. You have a method giving the symbol for the two players, but that won't make much difference unless you call it from an appropriate place.
 
  • #5
That is the issue that I am having. I call the getPlayer method, but I don't know what I need to do to set the player and change from one to the next. The same with the Symbol. Could you give a little more information, example, or something for me to work with. At this point I have just gotten extremely confused and don't know what to do. The project is due tonight and I have spent days trying to fix this program.
 
  • #6
If you or Jessica wrote the code yourself it must be so long ago you have forgotten what you wrote. *cough*. Or forgotten to talk to each other.

But, anyway, as you say, you need to "set player" and that requires two things: a method to set it with (which you have) and a place to set it from (which you need to identify). Perhaps, by looking at how you structured the loops in your code and remembering what the different parts are supposed to do you may be able to identify the point in the game controller code where the player should shift from one to the other. At that point you could then, for instance, set player 1 if it current is 2 else set it to 1. You may even get advanced and make a method, say swapPlayer(), that makes this swap so you only have to call that method at the right place.

For the print-out I'm afraid you once again have to understand what you wrote yourself. Try remember where you placed the code for print out of the board and see if you can modify it to call another method that converts that ugly 1 and 2 into a nice X and O just before you print it (hint: you had such a method in your first post, but threw it out in the second version you showed).
 
  • #7
Ok, I have created a switchPlayer method, and have placed it where I think it should go, but now it is not recognizing the method in the class. I get the error: cannot find symbol.

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tictactoetest;

/**
 *
 * @author Jon and Jessica
 */
public class TicTacToe {    private int player;
    private int gameBoard[][] = new int[3][3];

    public TicTacToe(int currentPlayer){       player = currentPlayer;

        for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    gameBoard[i][j] = 0;
                }

            }
    }

      /**
     * @return the player
     */
    public int getPlayer() {
      
      return player;
    }

    /**
     * @param player the player to set
     */
    public void setPlayer(int player) {
        this.player = player;
    }

    /**
     * @return the gameBoard
     */
    public int[][] getGameBoard() {
        return gameBoard;
    }

    public void switchPlayer(){
        if (player ==1){
            player = 2;
        }
        else {
            player =1;
        }
    }

    // Accepts row and column from player. If move made is invalid, it will still be current player's turn.
    public boolean playerMove(int row, int column) {

        // Initialize boolean move
        boolean move;

        // Checks to see if board location is occupied and a move can be made
        if (gameBoard[row -1][column -1] == 0)
            {
            gameBoard[row -1][column -1] = this.player;

            move = true;
            }
        else
        {
        // The specified cell is already occupied.
            move = false;
        }
            return move;
        }

        public boolean isGameOver(){

            boolean gameOver = true;

            for (int i = 0; i < 3; i++){
                for (int j = 0; j < 3; j++){
                    if (gameBoard[i][j] == 0){
                        gameOver = false;
                    }
                }
            }
            return gameOver;
        }
        // Method to check rows, columns, and diaganals for winner

        public int gameWinner(){

            int winner = 0;

            // check row 1 for winner
        if (gameBoard[0][0] == gameBoard[0][1] && gameBoard[0][0] == gameBoard[0][2] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check row 2 for winner
        if (gameBoard[1][0] == gameBoard[1][1] && gameBoard[1][0] == gameBoard[1][2] && gameBoard[1][0] != 0 ){

            winner = gameBoard[1][0];
        }
            // check row 3 for winner
        if (gameBoard[2][0] == gameBoard[2][1] && gameBoard[2][0] == gameBoard[2][2] && gameBoard[2][0] != 0 ){

            winner = gameBoard[2][0];
        }
            // check column 1 for winner
        if (gameBoard[0][0] == gameBoard[1][0] && gameBoard[0][0] == gameBoard[2][0] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check column 2 for winner
        if (gameBoard[0][1] == gameBoard[1][1] && gameBoard[0][1] == gameBoard[2][1] && gameBoard[0][1] != 0 ){

            winner = gameBoard[0][1];
        }
            // check column 3 for winner
        if (gameBoard[0][2] == gameBoard[1][2] && gameBoard[0][2] == gameBoard[2][2] && gameBoard[0][2] != 0 ){

            winner = gameBoard[0][2];
        }
            // check first diagonal row for winner;
        if (gameBoard[0][0] == gameBoard[1][1] && gameBoard[0][0] == gameBoard[2][2] && gameBoard[0][0] != 0 ){

            winner = gameBoard[0][0];
        }
            // check second diagonal for winner
        if (gameBoard[0][2] == gameBoard[1][1] && gameBoard[0][2] == gameBoard[2][0] && gameBoard[0][2] != 0 ){

            winner = gameBoard[0][2];
        }
            return winner;

        }

        // Display board after each input
        public void showBoard(){

            System.out.println("Tic Tac Toe Game\n" + "-----------");
            for(int i = 0; i < 3; i++){

                for (int j = 0; j < 3; j++){

                    System.out.print(gameBoard[i][j] + " | ");
                }
                System.out.println("\n-----------");

            }

        }

}

and call it after the primary move is made, but this is where the error shows up.

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tictactoetest;
import java.util.Scanner;
/**
 *
 * @author Jon and Jessica
 */
public class TicTacToeTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //Variable declaration
        int row;
        int column;

        
        TicTacToe ttt = new TicTacToe();
        Scanner input = new Scanner(System.in); // accept user input

        while(ttt.gameWinner() == 0 && !ttt.isGameOver()){
            System.out.println("Welcome to Tic Tac Toe!\n Player 1 = X\n Player 2 = O");
            ttt.showBoard();            // Get next player move
            System.out.println("Player " + ttt.getPlayer());
            System.out.println("Place your piece!");
            System.out.println("Please enter the row (1-3)");
            row = input.nextInt();

            // Trap for invalid row number
            while(row < 1 || row > 3){
                System.out.println("That is not a valid row!");
                System.out.println("Please re-enter row 1 - 3");
                row = input.nextInt();
            }
            System.out.println("Please Enter Column (1-3)");
            column = input.nextInt();
            ttt.switchPlayer();

            // Trap for invalid column
            while(column < 1 || column > 3){
                System.out.println("That is not a valid column!");
                System.out.println("Please re-enter column 1 - 3");
                column = input.nextInt();
            }
            // When a move is invalid, have player make new move
            while(!ttt.playerMove(row, column)){
                System.out.println("That is not a valid move... please try again!");
                System.out.println("Please enter the row 1-3");
                row = input.nextInt();

                // Trap for invalid entry
                while(row < 1 || row > 3){
                    System.out.println("That is not a valid row, try again.");
                    System.out.println("Please enter row 1-3");
                    row = input.nextInt();
                }

                System.out.println("Please enter column 1-3");
                column = input.nextInt();

                // Trap for invalid entry
                while (column < 1 || column > 3){
                    System.out.println("That is not a valid column, try again.");
                    System.out.println("Please enter column 1-3");
                    column = input.nextInt();
                }
            }
        }
        // If the loop was exited because there are no moves left, it's a tie, or "Cat's Game"
        if(ttt.gameWinner() == 0){
            System.out.println("Sorry...Cat's Game!");
        }
        else{
               // Since player auto advances, once game is over, winner is previous player
            System.out.println("The winner is Player ");
            if(ttt.getPlayer() == 1){
                System.out.println("2");
            }
            else{
                System.out.println("1");
            }
        }
    }

}

I will work on the output issue after this one is resolved. I think I can get that one figured out. Jessica is my wife and everything is shared, so it shows her name. This code has actually been written over the last 4 days, LOL. Been a rough week with finals going on. Thank you for the help, BTW.
 
  • #8
You should not switch player until you are sure that the current player has made a valid move (hint: there is only a single place in your code as it is now where it would be correct to switch player). If the only change from previous is that you have inserted a call to ttt.switchPlayer() then I can't really see why that shouldn't compile (javac, or whatever compiler you use, should tell you what is wrong and where).

And by the way, when you get to your X/O output problem, you probably also want to extend your number-to-symbol method so it can handle empty cells (hint: make you game-piece method return a space when the cell is neither player 1 or 2 is one way).
 
  • #9
Filip Larsen said:
You should not switch player until you are sure that the current player has made a valid move (hint: there is only a single place in your code as it is now where it would be correct to switch player). If the only change from previous is that you have inserted a call to ttt.switchPlayer() then I can't really see why that shouldn't compile (javac, or whatever compiler you use, should tell you what is wrong and where).

And by the way, when you get to your X/O output problem, you probably also want to extend your number-to-symbol method so it can handle empty cells (hint: make you game-piece method return a space when the cell is neither player 1 or 2 is one way).

Ok, so I should call the switchPlayer method after I have guaranteed correct input, so after:

Code:
 // Trap for invalid entry
                while(row < 1 || row > 3){
                    System.out.println("That is not a valid row, try again.");
                    System.out.println("Please enter row 1-3");
                    row = input.nextInt();
                }

                System.out.println("Please enter column 1-3");
                column = input.nextInt();

                // Trap for invalid entry
                while (column < 1 || column > 3){
                    System.out.println("That is not a valid column, try again.");
                    System.out.println("Please enter column 1-3");
                    column = input.nextInt();
                }
                
            }
        }
        ttt.switchPlayer(); // method to switch players (HERE IS SWITCH)
        
        // If the loop was exited because there are no moves left, it's a tie, or "Cat's Game"
        if(ttt.gameWinner() == 0){
            System.out.println("Sorry...Cat's Game!");
        }
        else{

however, whenever I try to use the method switchPlayer, I get the following error:

cannot find symbol
symbol: method switchPlayer()
location: class tictactoetest.TicTacToe

I have checked and the method should be declared correctly, but I can't figure out why it won't let me call it.
 
  • #10
Ok, Now I have the game switching players correctly, slight issue with the winning move not showing up, and I need to correct the output to show "X" and "O", but it is almost finished. Thank you so much for all the help! I am having an issue with this aspect as well. I have included a new method to convert the 1 and 2 to X and O as follows:

Tic Tac Toe Class with gamePiece() method:

Code:
public String gamePiece(int player){
              String result = "";
              if (player == 1){
                  result = "X";
              }
              else if (player == 2){
                  result = "O";
              }
              else {
                  result = " ";
              }
              return result;
   }

I call the board in the main() method simply by calling ttt.showBoard() at the beginning of the method as follows:

Code:
public static void main(String[] args) {

        //Variable declaration
        int row;
        int column;
        
        
        TicTacToe ttt = new TicTacToe();
        Scanner input = new Scanner(System.in); // accept user input        while(ttt.gameWinner() == 0 && !ttt.isGameOver()){
            System.out.println("Welcome to Tic Tac Toe!\n Player 1 = X\n Player 2 = O");
            ttt.showBoard(); // print board to screen
            
            // Get next player move
...

I attempted to add the method call ttt.gamePiece(); directly after I call the board, but I get an error message. Any advice to point me in the right direction?
 
Last edited:
  • #11
Look at the actual code for printing out the board and find the place where you print each of the 9 numbers. Can you see a good place to change the number printing into piece printing? Note, that the gamePiece method takes a parameter, so you need to call it with the value of a cell; you cannot just call gamePiece() without parameters.
 
  • #12
I ended up using a toString() method to create the string "X" and "O", as well as the board and used a string builder and sb.append("") to draw the board.

I finally got it to work as desired. It now switches players, catches invalid moves, takes new moves, determines winner, determines draw, displays board as blank when game starts, and populates board with X and O for player 1 and player 2 respectively. It continues to ask for moves until game is over, upon which time it can also declare the winner, or draw.

Thank you so much Filip for all of your help, you have shown yourself to be a great asset to this forum/community.
 

Related to Tic Tac Toe Game | Two Player | 3x3 grid

1. How do I win at Java Tic Tac Toe?

In order to win at Java Tic Tac Toe, you must place three of your symbols (either X or O) in a row, either horizontally, vertically, or diagonally. The first player to achieve this wins the game.

2. Can I play Java Tic Tac Toe against the computer?

Yes, many Java Tic Tac Toe games allow you to play against the computer. You can either choose to play against a pre-programmed AI or set the difficulty level to play against a more challenging opponent.

3. What are the common bugs or issues in Java Tic Tac Toe?

Some common bugs or issues in Java Tic Tac Toe may include the computer making an incorrect move, the game not recognizing a winning combination, or the game not resetting properly after a win or tie.

4. How can I improve the performance of my Java Tic Tac Toe game?

To improve the performance of your Java Tic Tac Toe game, you can try optimizing your code, using efficient algorithms, and minimizing the use of memory and resources. You can also consider implementing a graphical user interface (GUI) for a smoother user experience.

5. Is there a limit to the number of players in Java Tic Tac Toe?

No, there is no limit to the number of players in Java Tic Tac Toe. However, the game is typically designed for two players, so adding more players may require adjusting the game rules and board size.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
1
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
Back
Top