Question

In: Computer Science

In a game of Tic Tac Toe, two players take turns making an available cell in...

In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win.

Write a program in Java that emulates a Tic Tac Toe game.

When you are done, a typical session will look like this:

 Welcome to tic-tac-toe.
 Enter coordinates for your move following the X and O prompts.
   1 2 3
A   | | 
   -----
B   | | 
   -----
C   | |

X:A2
   1 2 3
A   |X| 
   -----
B   | | 
   -----
C   | |

O:B3
   1 2 3
A   |X| 
   -----
B   | |O
   -----
C   | |

And so on. Illegal moves will prompt the user again for a new move. A win or a stalemate will be announced, mentioning the winning side if any. The program will terminate whenever a single game is complete.

This file has the general framework of the TicTacToe class. An object of this class will represent a tic-tac-toe "board". The board will be represented internally by a two dimensional array of characters (3 x 3), and by a character indicating who's turn it is ('X' or 'O'). These are stored in the class instance variables as follows.

private char[][] board;
private char player; // 'X' or 'O'

You will need to define the following methods:

1. A constructor:

public TicTacToe()

to create an empty board, with initial value of a space (' ')

2. play method

public play(String position)

if position represents a valid move (e.g., A1, B3), add the current player's symbol to the board and return true. Otherwise, return false.

3. switchTurn method

public void switchTurn()

switches the current player from X to O, or vice versa.

4. won method

public boolean won()

Returns true if the current player has filled three in a row, column or either diagonal. Otherwise, return false.

5. stalemate method

public boolean stalemate()

Returns true if there are no places left to move;

6. printBoard method

 public void printBoard()

prints the current board

7. Use the following test code in your main method to create a TicTacToe object and print it using the printBoard method given, so as to test your code. Your printBoard method should produce the first board in the example above.

public static void main(String[] args) {

       Scanner in = new Scanner(System.in);
       TicTacToe game = new TicTacToe();
       System.out.println("Welcome to Tic-tac-toe");
       System.out.println("Enter coordinates for your move following the X and O prompts");
       
       while(!game.stalemate()) 
       {
              game.printBoard();
              System.out.print(game.getPlayer() + ":");

              //Loop while the method play does not return true when given their move.
              //Body of loop should ask for a different move
              while(!game.play(in.next()))
              {
                    System.out.println("Illegal move. Enter your move.");
                    System.out.print(game.getPlayer() + ":");
               }
              //If the game is won, call break;
              if(game.won())
                  break;

              game.printBoard();
              //Switch the turn
              game.switchTurn();

        }
        game.printBoard();
        if(game.won())
        {
             System.out.println("Player "+game.getPlayer()+" Wins!!!!");
        } 
        else 
        {
             System.out.println("Stalemate");
        }
}

Solutions

Expert Solution

// TicTacToe.java : Java program to allow user to playe Tic Tac Toe Game involving 2 players
import java.util.Scanner;

public class TicTacToe {
  
   private char[][] board;
   private char player; // 'X' or 'O'
  
   // create an empty tic tac board and set starting player to X
   public TicTacToe()
   {
       board = new char[3][3];
       for(int i=0;i<board.length;i++)
           for(int j=0;j<board[i].length;j++)
               board[i][j] = ' ';
       player = 'X';
   }
  
   // If position represents a valid move (e.g., A1, B3), add the current player's symbol
   // to the board and return true. Otherwise, return false.
   public boolean play(String position)
   {
       position = position.trim(); // remove white space if any
       // check length of position is 2
       if(position.length() == 2)
       {
           // get the character for row an column
           char row = position.charAt(0);
           char col = position.charAt(1);
          
           // convert character to integer
           int rowNum = (int)(row-'A');
           int colNum = (int)(col-'1');
          
           // check if valid range and the position is not occupied
           if(rowNum >=0 && rowNum < 3 && colNum >=0 && colNum < 3 && board[rowNum][colNum] == ' ')
           {
               // if valid and free space, set player to that space and return true
               board[rowNum][colNum] = player;
               return true;
           }
          
       }
      
       return false; // invalid
   }
  
   // switches the current player from X to O, or vice versa.
   public void switchTurn()
   {
       if(player == 'X')
           player = 'O';
       else
           player = 'X';
   }
  
   // Returns true if the current player has filled three in a row, column or either diagonal. Otherwise, return false.
   public boolean won()
   {
       // check row-wise and column-wise
       for(int i=0;i<3;i++)
       {
           if((board[i][0] == board[i][1]) && (board[i][0] == board[i][2]))
               if(board[i][0] == player)
                   return true;
          
          
           if((board[0][i] == board[1][i]) && (board[0][i] == board[2][i]))
               if(board[0][i] == player)
                   return true;
       }
      
       // check main diagonal
       if((board[0][0] == board[1][1] ) && (board[1][1] == board[2][2]))
           if(board[0][0] == player)
               return true;
      
       // check other diagonal
       if((board[0][2] == board[1][1]) && (board[1][1] == board[2][0]))
           if(board[1][1] == player)
               return true;
      
       return false;
   }

   //Returns true if there are no places left to move;
   public boolean stalemate()
   {
       for(int i=0;i<board.length;i++)
       {
           for(int j=0;j<board[i].length;j++)
               if(board[i][j] == ' ')
                   return false;
       }
      
       return true;
   }
  
   // prints the current board
   public void printBoard()
   {
       System.out.println();
       System.out.printf("%3s","");
       for(int i=0;i<board.length;i++)
       {
           System.out.printf(" %d ",i+1);
       }
      
       for(int i=0;i<board.length;i++)
       {
           System.out.printf("\n%3c",'A'+i);
           for(int j=0;j<board[i].length;j++)
           {
               if(j < board[i].length-1)
                   System.out.printf(" %c|",board[i][j]);
               else
                   System.out.printf(" %c",board[i][j]);
           }
           if(i < board.length-1)
               System.out.printf("\n%3s---------","");
       }
       System.out.println("\n");
   }
  
   // method to return the current player
   public char getPlayer()
   {
       return player;
   }
  
   public static void main(String[] args) {

       // test the class
       Scanner in = new Scanner(System.in);
   TicTacToe game = new TicTacToe();
   System.out.println("Welcome to Tic-tac-toe");
   System.out.println("Enter coordinates for your move following the X and O prompts");
     
   while(!game.stalemate())
   {
   game.printBoard();
   System.out.print(game.getPlayer() + ":");

   //Loop while the method play does not return true when given their move.
   //Body of loop should ask for a different move
   while(!game.play(in.next()))
   {
   System.out.println("Illegal move. Enter your move.");
   System.out.print(game.getPlayer() + ":");
   }
   //If the game is won, call break;
   if(game.won())
   break;

   //game.printBoard();
   //Switch the turn
   game.switchTurn();

   }
   game.printBoard();
   if(game.won())
   {
   System.out.println("Player "+game.getPlayer()+" Wins!!!!");
   }
   else
   {
   System.out.println("Stalemate");
   }

   }

}
//end of program

Output:


Related Solutions

In a game of Tic Tac Toe, two players take turns making an available cell in...
In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...
In a game of Tic Tac Toe, two players take turns making an available cell in...
In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...
PYTHON (Game: Tic-tac-toe): Write a program that plays the tic-tac-toe game. Two players take turns clicking...
PYTHON (Game: Tic-tac-toe): Write a program that plays the tic-tac-toe game. Two players take turns clicking an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs when all the cells in the grid have been filled with tokens and neither player has...
Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional...
Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Displays the contents of the board array. Allows player 1 to select a location on the board for an X. The program should ask the user to enter the row...
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3...
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3 grid as shown below: The game is played by two players, who take turns. The first player marks moves with a circle, the second with a cross. The player who has formed a horizontal, vertical, or diagonal sequence of three marks wins. Your program should draw the game board, ask the user for the coordinates of the next mark (their move), change the players...
C++ Make a Tic Tac Toe game for 2 players to play using 2D arrays and...
C++ Make a Tic Tac Toe game for 2 players to play using 2D arrays and classes. Do not add more #include functions other than the ones listed. I never said what type of code I needed in a previous question. I apologize and I can't go back and change it so here is the same question with more information Using the tictactoeGame class, write a main program that uses a tictactoeGame to implement a game in which two players...
Make a Tic Tac Toe game for 2 players to play using 2D arrays and classes....
Make a Tic Tac Toe game for 2 players to play using 2D arrays and classes. Do not add more #include functions other than the ones listed (such as #include <stdio.h> etc). Using the tictactoeGame class, write a main program that uses a tictactoeGame to implement a game in which two players (you and a friend) take turns placing X’s and O’s onto the board. After each turn, the current board configuration should be displayed, and once a player connects...
How to make tic tac toe game in javascript with vue.js
How to make tic tac toe game in javascript with vue.js
Using C language Problem!! <3 x 3 tic tac toe> 2 players are doing tic tac...
Using C language Problem!! <3 x 3 tic tac toe> 2 players are doing tic tac toe alternatively. Anyone could win when they first make a bingo for any line(horizontal, vertical, diagonal) [Constraints] 1. Use 2dimensional Array(3 X 3) 2. Each elements are 1 or 2 so that can show their player1, player2's mark. 3. Inputs are 1 through 9 as you can see 1 2 3 4 5 6 7 8 9 4. No inputs are duplicated 5. if...
The objective of this assignment is to implement the tic-tac-toe game with a C program. The...
The objective of this assignment is to implement the tic-tac-toe game with a C program. The game is played by two players on a board defined as a 5x5 grid (array). Each board position can contain one of two possible markers, either ‘X’ or ‘O’. The first player plays with ‘X’ while the second player plays with ‘O’. Players place their markers in an empty position of the board in turns. The objective is to place 5 consecutive markers of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT