Question

In Java create a program where a user plays Tic Tac Toe against the computer. Create...

In Java create a program where a user plays Tic Tac Toe against the computer. Create a class TicTacToe that will enable you write a program to play Tic-Tac-Toe. The class contains a private 3x3 two-dimensional array. Use an enum type to represent the value in each cell of the array. The enum’s constants should be named X, O, and EMPTY (for a position that does not contain an X or O). The constructor should initialize the board elements to EMPTY.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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{
      
//       Random r = new Random();
//      
//       int n = r.nextInt(5000);
//      
//       System.out.println("Random Number is: " + n);
//      
//       Thread.sleep(n);
//      
//      
//       System.out.println("Program Ends here after the delay ");
//      
      
       // 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.

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

Add a comment
Know the answer?
Add Answer to:
In Java create a program where a user plays Tic Tac Toe against the computer. Create...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe....

    (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enumeration to represent the value in each cell of the array. The enumeration’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X...

  • (Tic-Tac-Toe) Create class TicTacToe that will enable you to write a complete app to play the...

    (Tic-Tac-Toe) Create class TicTacToe that will enable you to write a complete app to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 rectangular array of integers. The constructor should initialize the empty board to all 0s. Allow two human players. Wherever the first player moves, place a 1 in the specified square, and place a 2 wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has...

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

  • Please do this in Java (Java FX) Tic-Tac-Toe game (aka X's and O's) in which the...

    Please do this in Java (Java FX) Tic-Tac-Toe game (aka X's and O's) in which the player, who is "X", plays against the application, which is "O". The game should be built using the basic window-with-canvas code used for the various tutorials and course assignments. The user plays by dragging "X" tokens onto the Tic-Tac-Toe board area after which the application will automatically play by moving an "O" onto the board area. When a game is over the app should...

  • Tic-Tac-Toe (arrays and multidimensional arrays) C++ Write an interactive program that plays tic-tac-toe. Represent the board...

    Tic-Tac-Toe (arrays and multidimensional arrays) C++ Write an interactive program that plays tic-tac-toe. Represent the board as a 3 X 3 character array. Initialize the array to blanks and ask each player in turn to input a position. The first player's position is marked on the board with a O and the second player's position is marked with an X. Continue the process until a player wins or the game is a draw. To win, a player must have 3...

  • Objective: To write a program to allow a game of Tic Tac Toe to be played,...

    Objective: To write a program to allow a game of Tic Tac Toe to be played, and to determine when the game is over Complete the TicTacToe program below. It will allow for a full game of Tic Tac Toe between two players, and it will tell you who won or if the game is over with no winner. Details: The TicTacToe board is stored in a 3x3 multidimensional list of characters containing spaces at the start of the game...

  • Writing a code in C# console app Create class TicTacToe that will enable you to write...

    Writing a code in C# console app Create class TicTacToe that will enable you to write a complete app to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 rectangular array of integers. The constructor should initialize the empty board to all 0s. Allow two human players. Wherever the first player moves, place a 1 in the specified square, and place a 2 wherever the second player moves. Each move must be to an empty square. After each...

  • Write a program to Simulate a game of tic tac toe in c#

    Write a program to Simulate a game of tic tac toe. A game of tic tac toe has two players. A Player class is required to store /represent information about each player. The UML diagram is given below.Player-name: string-symbol :charPlayer (name:string,symbol:char)getName():stringgetSymbol():chargetInfo():string The tic tac toe board will be represented by a two dimensional array of size 3 by 3 characters. At the start of the game each cell is empty (must be set to the underscore character ‘_’). Program flow:1)    ...

  • 18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use di...

    18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use 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: Write . 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...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT