Question

In: Computer Science

Write a class (and a client class to test it) that encapsulates a tic-tac-toe board. A...

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.

Solutions

Expert Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TicTacToeGame {

   private char[][] board = new char[3][3];
   private String playername1;
   private String playername2;
   private int currentplayingPlayer;
   private char markerpoint1;
   private char markerpoint2;
   private int noplays;
   private BufferedReader bufferedreader = new BufferedReader(
           new InputStreamReader(System.in));

   protected void init() {
       int counter = 0;
       for (int i = 0; i < 3; i++) {
           for (int j1 = 0; j1 < 3; j1++) {
               board[i][j1] = Character.forDigit(++counter, 10);
           }
       }
       currentplayingPlayer = 1;
       noplays = 0;
   }

   protected void switchPlayers() {
       if (getCurrentplayingPlayer() == 1) {
           setCurrentplayingPlayer(2);
       } else {
           setCurrentplayingPlayer(1);
       }
       setNoplays(getNoplays() + 1);
   }

   protected boolean placeMarkerpoint(int play) {
       for (int i = 0; i < 3; i++) {
           for (int i1 = 0; i1 < 3; i1++) {
               if (board[i][i1] == Character.forDigit(play, 10)) {
                   board[i][i1] = (getCurrentplayingPlayer() == 1) ? getMarkerpoint1()
                           : getMarkerpoint2();
                   return true;
               }
           }
       }
       return false;
   }

   protected boolean winner() {
       // Checking rows
       char current = ' ';
       for (int i = 0; i < 3; i++) {
           int i1 = 0;
           for (i1 = 0; i1 < 3; i1++) {
               if (!Character.isLetter(board[i][i1])) {
                   break;
               }
               if (i1 == 0) {
                   current = board[i][i1];
               } else if (current != board[i][i1]) {
                   break;
               }
               if (i1 == 2) {
                   // Found winner
                   return true;
               }
           }
       }
       // Checking columns
       for (int i = 0; i < 3; i++) {
           current = ' ';
           int i1 = 0;
           for (i1 = 0; i1 < 3; i1++) {
               if (!Character.isLetter(board[i1][i])) {
                   break;
               }
               if (i1 == 0) {
                   current = board[i1][i];
               } else if (current != board[i1][i]) {
                   break;
               }
               if (i1 == 2) {
                   // Found winner
                   return true;
               }
           }
       }
       // Checking diagonals
       current = board[0][0];
       if (Character.isLetter(current) && board[1][1] == current
               && board[2][2] == current) {
           return true;
       }
       current = board[2][0];
       if (Character.isLetter(current) && board[1][1] == current
               && board[0][2] == current) {
           return true;
       }
       return false;
   }

   protected String getRules() {
       StringBuilder builder = new StringBuilder();
       builder.append("Players take turns marking a square. Only squares \n");
       builder.append("not already marked can be picked. Once a player has \n");
       builder.append("marked three squares in a row, the player wins! If all squares \n");
       builder.append("are marked and no three squares are the same, a tie game is declared.\n");
       builder.append("Have Fun! \n\n");
       return builder.toString();
   }

   protected String getPrompt() {
       String prompting = "";
       try {
           prompting = bufferedreader.readLine();
       } catch (IOException ex) {
           ex.printStackTrace();
       }
       return prompting;
   }

   protected String drawBoard() {
       StringBuilder stringbuilder = new StringBuilder(
               "tic tac toe Game board: \n");
       for (int i = 0; i < 3; i++) {
           for (int i1 = 0; i1 < 3; i1++) {
               stringbuilder.append("[" + board[i][i1] + "]");
           }
           stringbuilder.append("\n");
       }
       return stringbuilder.toString();
   }

   public String getPlayername1() {
       return playername1;
   }

   public void setPlayername1(String playername1) {
       this.playername1 = playername1;
   }

   public String getPlayername2() {
       return playername2;
   }

   public void setPlayername2(String playername2) {
       this.playername2 = playername2;
   }

   public char getMarkerpoint1() {
       return markerpoint1;
   }

   public void setMarkerpoint1(char markerpoint1) {
       this.markerpoint1 = markerpoint1;
   }

   public char getMarkerpoint2() {
       return markerpoint2;
   }

   public void setMarkerpoint2(char markerpoint2) {
       this.markerpoint2 = markerpoint2;
   }

   public int getCurrentplayingPlayer() {
       return currentplayingPlayer;
   }

   public void setCurrentplayingPlayer(int currentplayingPlayer) {
       this.currentplayingPlayer = currentplayingPlayer;
   }

   public int getNoplays() {
       return noplays;
   }

   public void setNoplays(int noplays) {
       this.noplays = noplays;
   }

}

public class TicTacToeGameMain {

   public void play() {

       TicTacToeGame maingame = new TicTacToeGame();

       System.out.println("Welcome! Tic Tac Toe is a two player game.");
       System.out.print("Enter player one's name: ");
       maingame.setPlayername1(maingame.getPrompt());
       System.out.print("Enter player two's name: ");
       maingame.setPlayername2(maingame.getPrompt());
       boolean markerpointOk = false;
       while (!markerpointOk) {
           System.out.print("Select any letter as "
                   + maingame.getPlayername1() + "'s marker: ");
           String markerpoint = maingame.getPrompt();
           if (markerpoint.length() == 1
                   && Character.isLetter(markerpoint.toCharArray()[0])) {
               markerpointOk = true;
               maingame.setMarkerpoint1(markerpoint.toCharArray()[0]);
           } else {
               System.out.println("Invalid marker, try again");
           }
       }
       markerpointOk = false;
       while (!markerpointOk) {
           System.out.print("Select any letter as "
                   + maingame.getPlayername2() + "'s marker: ");
           String markerpoint2 = maingame.getPrompt();
           if (markerpoint2.length() == 1
                   && Character.isLetter(markerpoint2.toCharArray()[0])) {
               markerpointOk = true;
               maingame.setMarkerpoint2(markerpoint2.toCharArray()[0]);
           } else {
               System.out.println("Invalid marker, try again");
           }
       }

       boolean continuePlaying = true;

       while (continuePlaying) {

           maingame.init();
           System.out.println();
           System.out.println(maingame.getRules());
           System.out.println();
           System.out.println(maingame.drawBoard());
           System.out.println();

           String player = null;
           while (!maingame.winner() && maingame.getNoplays() < 9) {
               player = maingame.getCurrentplayingPlayer() == 1 ? maingame
                       .getPlayername1() : maingame.getPlayername2();
               boolean validPick = false;
               while (!validPick) {
                   System.out.print("It is " + player
                           + "'s turn. Pick a square: ");
                   String square = maingame.getPrompt();
                   if (square.length() == 1
                           && Character.isDigit(square.toCharArray()[0])) {
                       int pick = 0;
                       try {
                           pick = Integer.parseInt(square);
                       } catch (NumberFormatException e) {
                           // Do nothing here, it'll evaluate as an invalid
                           // pick on the next row.
                       }
                       validPick = maingame.placeMarkerpoint(pick);
                   }
                   if (!validPick) {
                       System.out.println("Square can not be selected. Retry");
                   }
               }
               maingame.switchPlayers();
               System.out.println();
               System.out.println(maingame.drawBoard());
               System.out.println();
           }
           if (maingame.winner()) {
               System.out.println("Game Over - " + player + " WINS!!!");
           } else {
               System.out.println("Game Over - Draw");
           }
           System.out.println();
           System.out.print("Play again? (Y/N): ");
           String choice = maingame.getPrompt();
           if (!choice.equalsIgnoreCase("Y")) {
               continuePlaying = false;
           }
       }
   }

   /**
   * @param args
   * the command line arguments
   */
   public static void main(String[] args) {
       TicTacToeGameMain mainclass = new TicTacToeGameMain();
       mainclass.play();
   }
}

output

Welcome! Tic Tac Toe is a two player game.
Enter player one's name: mark
Enter player two's name: smith
Select any letter as mark's marker: x
Select any letter as smith's marker: o

Players take turns marking a square. Only squares
not already marked can be picked. Once a player has
marked three squares in a row, the player wins! If all squares
are marked and no three squares are the same, a tie game is declared.
Have Fun!

tic tac toe Game board:
[1][2][3]
[4][5][6]
[7][8][9]


It is mark's turn. Pick a square: 1

tic tac toe Game board:
[x][2][3]
[4][5][6]
[7][8][9]


It is smith's turn. Pick a square: 2

tic tac toe Game board:
[x][o][3]
[4][5][6]
[7][8][9]


It is mark's turn. Pick a square: 3

tic tac toe Game board:
[x][o][x]
[4][5][6]
[7][8][9]


It is smith's turn. Pick a square: 5

tic tac toe Game board:
[x][o][x]
[4][o][6]
[7][8][9]


It is mark's turn. Pick a square: 6

tic tac toe Game board:
[x][o][x]
[4][o][x]
[7][8][9]


It is smith's turn. Pick a square: 7

tic tac toe Game board:
[x][o][x]
[4][o][x]
[o][8][9]


It is mark's turn. Pick a square: 8

tic tac toe Game board:
[x][o][x]
[4][o][x]
[o][x][9]


It is smith's turn. Pick a square: 9

tic tac toe Game board:
[x][o][x]
[4][o][x]
[o][x][o]


It is mark's turn. Pick a square: 4

tic tac toe Game board:
[x][o][x]
[x][o][x]
[o][x][o]


Game Over - Draw

Play again? (Y/N): y

Players take turns marking a square. Only squares
not already marked can be picked. Once a player has
marked three squares in a row, the player wins! If all squares
are marked and no three squares are the same, a tie game is declared.
Have Fun!

tic tac toe Game board:
[1][2][3]
[4][5][6]
[7][8][9]


It is mark's turn. Pick a square: 1

tic tac toe Game board:
[x][2][3]
[4][5][6]
[7][8][9]


It is smith's turn. Pick a square: 2

tic tac toe Game board:
[x][o][3]
[4][5][6]
[7][8][9]


It is mark's turn. Pick a square: 3

tic tac toe Game board:
[x][o][x]
[4][5][6]
[7][8][9]


It is smith's turn. Pick a square: 5

tic tac toe Game board:
[x][o][x]
[4][o][6]
[7][8][9]


It is mark's turn. Pick a square: 6

tic tac toe Game board:
[x][o][x]
[4][o][x]
[7][8][9]


It is smith's turn. Pick a square: 8

tic tac toe Game board:
[x][o][x]
[4][o][x]
[7][o][9]


Game Over - smith WINS!!!

Play again? (Y/N): n


Related Solutions

Write a class (and a client class to test it) that encapsulates a tic-tac-toe board. A...
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....
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# (Tic-Tac-Toe) Create class TicTacToe that will enable you to write a complete app to play...
C# (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...
Python Code Needed Two-Player, Two-Dimensional Tic-Tac-Toe Write a script to play two-dimensional Tic-Tac-Toe between two human...
Python Code Needed Two-Player, Two-Dimensional Tic-Tac-Toe Write a script to play two-dimensional Tic-Tac-Toe between two human players who alternate entering their moves on the same computer. Create a 3-by-3 two-dimensional array. Each player indicates their moves by entering a pair of numbers representing the row and column indices of the square in which they want to place their mark, either an 'X' or an 'O'. When the first player moves, place an 'X' in the specified square. When the second...
Stewart invented “Max” a board game similar to “Tic Tac Toe.” In May 2017, Stewart began...
Stewart invented “Max” a board game similar to “Tic Tac Toe.” In May 2017, Stewart began negotiating with Big Board, Inc., to license “Max” for distribution outside the United States. On June 11, 2017, the parties met and orally discussed terms. As compensation, Big Board promised to pay Stewart the amount due from another board game he had developed for Big Board two years ago. On June 26, 2017, Lisa, a Big Board employee, sent Stewart an email titled “Max...
If you were to write a game of tic-tac-toe, you may store the representation of the...
If you were to write a game of tic-tac-toe, you may store the representation of the game board as a two dimensional list such as   [['X', '', 'X'], ['O', 'X', ''], ['', 'O', 'X']] where each sublist is a row in the board.   Empty strings ('') denote a space that does not yet have a value. Assuming this representation, write functions (contained in the same file) that do the following: a) Create a new empty tic-tac-toe board. This function should...
For this assignment, you will write a tic-tac-toe application in HTML and JavaScript, using an HTML...
For this assignment, you will write a tic-tac-toe application in HTML and JavaScript, using an HTML <canvas> tag. The game will be played "hot seat" where players take turns using the same device. Requirements: The canvas should be 600px tall and wide, with the gameplay area occupying most of the canvas. The X's and O's may be drawn using polygons or large-font text The grid should be drawn using polygons, specifically long, thin rectangles Before & between games, the canvas...
If anyone can please write a code for a 5x5 tic tac toe game in matlab...
If anyone can please write a code for a 5x5 tic tac toe game in matlab I would greatly appreciate it. Its extra credit. PLEASE HELP ME :(
QUESTION: This is a tic-tac-toe game in react.js. Covert the following class-based components in React.js to...
QUESTION: This is a tic-tac-toe game in react.js. Covert the following class-based components in React.js to Functional Based component in React. //CODE import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i];...
How to make tic tac toe game in javascript with vue.js
How to make tic tac toe game in javascript with vue.js
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT