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 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

import java.util.Random;
import java.util.Scanner;

public class TicTacToe {

   public static void initializeBoard(char board[][]) {
       for (int i = 0; i < 3; i++)
           for (int j = 0; j < 3; j++)
               board[i][j] = ' ';
   }

   public static boolean validMove(char board[][], int x, int y) {
       if (x < 0 || x > 2 || y < 0 || y > 2)
           return false;
       if (board[x][y] == 'X' || board[x][y] == 'O')
           return false;
       else
           return true;

   }

   public static void displayBoard(char board[][]) {
       int t;
       for (t = 0; t < 3; t++) {
           System.out.print(" " + board[t][0] + " | " + board[t][1] + " | " + board[t][2]);
           if (t != 2)
               System.out.print("\n---|---|---\n");
       }
       System.out.println();
   }

   // public static void getInput(char board[][], char marker, int x, int y) {
   //
   // }

   public static void markBoard(char board[][], int x, int y, char marker) {
       board[x][y] = marker;
   }

   public static boolean gameOver(char board[][]) {
       if (checkHorizontal(board, 'X')) {
           printWinner('X');
           return true;
       }
       if (checkVertical(board, 'X')) {
           printWinner('X');
           return true;
       }
       if (checkDiagonal(board, 'X')) {
           printWinner('X');
           return true;
       }
       if (checkHorizontal(board, 'O')) {
           printWinner('O');
           return true;
       }
       if (checkVertical(board, 'O')) {
           printWinner('O');
           return true;
       }
       if (checkDiagonal(board, 'O')) {
           printWinner('O');
           return true;
       }
       if (checkTie(board)) {
           printWinner('T');
           return true;
       }
       return false;
   }

   public static boolean checkHorizontal(char board[][], char marker) {
       int i, j, count;
       for (i = 0; i < 3; i++) {
           count = 0;
           for (j = 0; j < 3; j++)
               if (board[i][j] == marker)
                   count++;
           if (count == 3)
               return true;
       }
       return false;
   }

   public static boolean checkVertical(char board[][], char marker) {
       int i, j, count;
       for (i = 0; i < 3; i++) {
           count = 0;
           for (j = 0; j < 3; j++)
               if (board[j][i] == marker)
                   count++;
           if (count == 3)
               return true;
       }
       return false;

   }

   public static boolean checkDiagonal(char board[][], char marker) {
       if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] == marker)
           return true;
       if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] == marker)
           return true;
       return false;
   }

   public static boolean checkTie(char board[][]) {
       int i, j;
       for (i = 0; i < 3; i++)
           for (j = 0; j < 3; j++)
               if (board[i][j] == ' ')
                   return false;
       return true;
   }

   public static void printWinner(char marker) {
       if (marker == 'T')
           System.out.println("TIE GAME!\n");
       else
           System.out.println("The winner is " + marker + " !!!\n");
   }
  
  

   public static void main(String[] args) throws Exception{
      
       // TODO Auto-generated method stub

       // srand(time(0));
       // int start=rand()%2;
       char board[][] = new char[3][3];
       char exit;
       char f, s;
       int x = 0, y = 0;
       f = 'X';
       s = 'O';
       initializeBoard(board);
       displayBoard(board);
       Scanner sc = new Scanner(System.in);
       while (true) {
           // getInput(board, f, x, y);

           for (;;) {
               System.out.print("Player " + f + " Enter a Row and Column (between 1-3): ");
               x = sc.nextInt();
               y = sc.nextInt();
               x--;
               y--;
               if (validMove(board, x, y))
                   break;
               System.out.print("Invalid Move: Please Try Again\n\n");
           }
           markBoard(board, x, y, f);
           displayBoard(board);
           if (gameOver(board))
               break;
           for (;;) {
               System.out.print("Player " + f + " Enter a Row and Column (between 1-3): ");
               x = sc.nextInt();
               y = sc.nextInt();
               x--;
               y--;
               if (validMove(board, x, y))
                   break;
               System.out.print("Invalid Move: Please Try Again\n\n");
           }
           markBoard(board, x, y, s);
           displayBoard(board);
           if (gameOver(board))
               break;
       }

   }

}

--------------------------------------------------------

SEE OUTPUT

PLEASE COMMENT if there is any concern.

==========================================


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