Question

In java //Create a New Project called LastNameTicTacToe.// //Write a class (and a client class to...

In java

//Create a New Project called LastNameTicTacToe.//

//Write a class (and a client class to test it) that encapsulates a tic-tac-toe board. // A tic-tac-toe board looks like a table of three rows and three columns partially or completely filled with the characters X and O. // At any point, a cell of that table could be empty or could contain an X or an O. You should have one instance variable, a two-dimensional array of values representing the tic-tac-toe board.

//This game should involve one human player vs. the computer. At the start of each game, randomly select if the computer will play X or O and who (i.e. human or computer) will make the first move.

//Your default constructor should instantiate the array so that it represents an empty board.

//You should include the following methods:

a method that generates a valid play by the computer and displays the board after each play.

a method that requests a valid play from the human and displays the board after each play.

a method to display the tic-tac-toe board.

//a method checking if a player has won based on the contents of the board; this method takes no parameter. It returns X if the "X player" has won, O if the "O player" has won, T if the game was a tie. A player wins if he or she has placed an X (or an O) in all cells in a row, all cells in a column, or all cells in one of the diagonals.

//NOTE: Be sure to display the board after each move. // You must provide clear prompts for the human player to select a space on the tic-tac-toe board.

//Input Validation: Verify that all moves by the human player are to a valid space on the tic-tac-toe board. An incorrect choice should not halt or terminate the game.

Homework Answers

Answer #1

import java.util.Scanner;

public class TicTacToeBoard {
  
     
   public static final int EMPTY = 0;
   public static final int CROSS = 1;
   public static final int NOUGHT = 2;
     
  
   public static final int PLAYING = 0;
   public static final int DRAW = 1;
   public static final int CROSS_WON = 2;
   public static final int NOUGHT_WON = 3;
     
     
   public static final int ROWS = 3, COLS = 3;
   public static int[][] board = new int[ROWS][COLS];
   public static int currentState;
   public static int currentPlayer;
   public static int currntRow, currentCol;
     
   public static Scanner in = new Scanner(System.in);
     
  
   public static void main(String[] args) {
     
   initGame();
  
   do {
   playerMove(currentPlayer);
   updateGame(currentPlayer, currntRow, currentCol);
   printBoard();
  
   if (currentState == CROSS_WON) {
   System.out.println("'X' won! Bye!");
   } else if (currentState == NOUGHT_WON) {
   System.out.println("'O' won! Bye!");
   } else if (currentState == DRAW) {
   System.out.println("It's a Draw! Bye!");
   }
  
   currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
   } while (currentState == PLAYING); // repeat if not game-over
   }
     
  
   public static void initGame() {
   for (int row = 0; row < ROWS; ++row) {
   for (int col = 0; col < COLS; ++col) {
   board[row][col] = EMPTY; // all cells empty
   }
   }
   currentState = PLAYING; // ready to play
   currentPlayer = CROSS; // cross plays first
   }
     
   /** Player with the "theSeed" makes one move, with input validation.
   Update global variables "currentRow" and "currentCol". */
   public static void playerMove(int theSeed) {
   boolean validInput = false; // for input validation
   do {
   if (theSeed == CROSS) {
   System.out.print("Player 'X', enter your move (row[1-3] column[1-3]): ");
   } else {
   System.out.print("Player 'O', enter your move (row[1-3] column[1-3]): ");
   }
   int row = in.nextInt() - 1; // array index starts at 0 instead of 1
   int col = in.nextInt() - 1;
   if (row >= 0 && row < ROWS && col >= 0 && col < COLS && board[row][col] == EMPTY) {
   currntRow = row;
   currentCol = col;
   board[currntRow][currentCol] = theSeed; // update game-board content
   validInput = true; // input okay, exit loop
   } else {
   System.out.println("This move at (" + (row + 1) + "," + (col + 1)
   + ") is not valid. Try again...");
   }
   } while (!validInput); // repeat until input is valid
   }
     
   /** Update the "currentState" after the player with "theSeed" has placed on
   (currentRow, currentCol). */
   public static void updateGame(int theSeed, int currentRow, int currentCol) {
   if (hasWon(theSeed, currentRow, currentCol)) { // check if winning move
   currentState = (theSeed == CROSS) ? CROSS_WON : NOUGHT_WON;
   } else if (isDraw()) { // check for draw
   currentState = DRAW;
   }
   // Otherwise, no change to currentState (still PLAYING).
   }
     
  
   public static boolean isDraw() {
   for (int row = 0; row < ROWS; ++row) {
   for (int col = 0; col < COLS; ++col) {
   if (board[row][col] == EMPTY) {
   return false; // an empty cell found, not draw, exit
   }
   }
   }
   return true; // no empty cell, it's a draw
   }
     
   /** Return true if the player with "theSeed" has won after placing at
   (currentRow, currentCol) */
   public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
   return (board[currentRow][0] == theSeed // 3-in-the-row
   && board[currentRow][1] == theSeed
   && board[currentRow][2] == theSeed
   || board[0][currentCol] == theSeed // 3-in-the-column
   && board[1][currentCol] == theSeed
   && board[2][currentCol] == theSeed
   || currentRow == currentCol // 3-in-the-diagonal
   && board[0][0] == theSeed
   && board[1][1] == theSeed
   && board[2][2] == theSeed
   || currentRow + currentCol == 2 // 3-in-the-opposite-diagonal
   && board[0][2] == theSeed
   && board[1][1] == theSeed
   && board[2][0] == theSeed);
   }
     
     
   public static void printBoard() {
   for (int row = 0; row < ROWS; ++row) {
   for (int col = 0; col < COLS; ++col) {
   printCell(board[row][col]); // print each of the cells
   if (col != COLS - 1) {
   System.out.print("|"); // print vertical partition
   }
   }
   System.out.println();
   if (row != ROWS - 1) {
   System.out.println("-----------"); // print horizontal partition
   }
   }
   System.out.println();
   }
     
  
   public static void printCell(int content) {
   switch (content) {
   case EMPTY: System.out.print(" "); break;
   case NOUGHT: System.out.print(" O "); break;
   case CROSS: System.out.print(" X "); break;
   }
   }

}

Output:

Know the answer?
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
Similar Questions
Write a program that allows two players to play a game of tic-tac-toe. Use a twodimensional...
Write a program that allows two players to play a game of tic-tac-toe. Use a twodimensional char array with three rows and three columns as the game board. Each element in the array should be initialized with an asterisk (*). The program should run a loop that: • 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 and...
PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1....
PYTHON Exercise 2. Tic-Tac-Toe In this exercise we are going to create a Tic-Tac-Toe game. 1. Create the data structure – Nine slots that can each contain an X, an O, or a blank. – To represent the board with a dictionary, you can assign each slot a string-value key. – String values in the key-value pair to represent what’s in each slot on the board: ■ 'X' ■ 'O' ■ ‘ ‘ 2. Create a function to print the...
in c++ : Problem Domain: The classic TicTacToe game alternatively place Xs and Os on a...
in c++ : Problem Domain: The classic TicTacToe game alternatively place Xs and Os on a 3x3 grid. The winner is the first player to place 3 consecutive marks in a horizontal, vertical or diagonal row. Understanding the Problem: In this assignment, you will: 1) Create a tic tac toe board data structure. 2) Check for game over. 3) Clear the tic tac toe game for each game. 4) Display the tic tac toe board to screen. 5) Simulate playing...
A Tic-tac-toe board has 9 spaces. The first player fills one of the spaces with an...
A Tic-tac-toe board has 9 spaces. The first player fills one of the spaces with an X, then the second player fills a space with an O. The players continue to alternate filling a space with their respective symbol until no empty spaces remain on the board. How many different arrangements of X’s and O’s are possible at the end of the game? You must fully justify your answer.
Can you create a 2-player Tic Tac Toe game (also known as noughts and crosses) on...
Can you create a 2-player Tic Tac Toe game (also known as noughts and crosses) on MATLAB, using nested loops (for, if, else, while loops) arrays, conditional execution and functions, as well as displaying the game board of X and O on a plot.
R-S-P Requirement: - write one C++ program that mimics the Rock-Scissor-Paper game. This program will ask...
R-S-P Requirement: - write one C++ program that mimics the Rock-Scissor-Paper game. This program will ask user to enter an input (out of R-S-P), and the computer will randomly pick one and print out the result (user wins / computer wins). - User's input along with computer's random pick will be encoded in the following format: -- user's rock: 10 -- user's scissor:          20 -- user's paper:            30 -- comp's rock:            1 -- comp's scissor:        2 -- comp's...
Part 1: Create the grid tic-tac-toe gameboard using buttons and iteration. Part 2: Human user gets...
Part 1: Create the grid tic-tac-toe gameboard using buttons and iteration. Part 2: Human user gets to select an open cell on the grid - place an X on that button selected Part 3: Check for a win using DOM iteration - new game option if row or column matching X pattern Part 4: Computer gets to select an open cell on the grid - place an O on that button selected Part 5: Check for a win using DOM...
Write a C++ program. Here is the project description. The game of "23" is a two-player...
Write a C++ program. Here is the project description. The game of "23" is a two-player game that begins with a pile of 23 toothpicks. Players take turns, withdrawing either 1, 2, or 3 toothpicks at a time. The player to withdraw the last toothpick loses the game. Write a human vs. computer program that plays "23". The human should always move first. When it is the computer's turn, it should play according to the following rules: 1. If there...
Step 1: Create a new Java project in NetBeans called “PartnerLab1” Create a new Java Class...
Step 1: Create a new Java project in NetBeans called “PartnerLab1” Create a new Java Class in that project called "BouncyHouse" Create a new Java Class in that project called “Person” Step 2: Implement a properly encapsulated "BouncyHouse" class that has the following attributes: Weight limit Total current weight of all occupants in the bouncy house (Note: all weights in this assignment can be represented as whole numbers) …and methods to perform the following tasks: Set the weight limit Set...
Java programming. Write a public Java class called WriteToFile that opens a file called words.dat which...
Java programming. Write a public Java class called WriteToFile that opens a file called words.dat which is empty. Your program should read a String array called words and write each word onto a new line in the file. Your method should include an appropriate throws clause and should be defined within a class called TextFileEditor. The string should contain the following words: {“the”, “quick”, “brown”, “fox”}