Question

Enhance and correct a Tic Tac Toe game. The game is intended to be played against...

Enhance and correct a Tic Tac Toe game. The game is intended to be played against a computer.

The object TicTacToeBoard is initialized to indicate if the computer is the player 1 or player 2. Your task is to allow turns between the player and computer and to determine if a winner exists.

Keyboard input implies using the Scanner object.

Review Section 7.7 in the textbook.

Ideally, do 1 task at a time and test the results. The tasks are arranged so that the previous work will help with your testing.

The TicTacToeBoard class uses a Character class which is a wrapper class for char. It allows for the value null. Thus, the board values can be ‘X’,’O’ or null.

Deliverables

Submit the modified and corrected TicTacToe class and TicTacToeBoard class.

Be sure to submit both files. If you neglect to include a file, you must email me the missing file before the due date.

The file GuiBoard.java does not need to be included as there are no required changes.

Program Assumptions

The TicTacToeBoard is instantiated with the Computer as player 2. This setting also determines who is ‘X’ and who is ‘O’. ‘X’ always goes first.

In the TicTacToe board will have null values in the ‘squares’ when started.

Program Requirements

  1. In the TicTacToe class and TicTacToeBoard class, modify the comment headers to include your name and student ID and semester.
  2. In the TicTacToe class, set the existing Long variable named securityCode with a value as defined below. The TicTacToeBoard instance will do these validations for you. The program must simply load a number that qualifies. You may need to test this several times to create a qualifying security code.
    1. securityCode must be a 16 digit number.
    2. securityCode must start with the digit 2.
    3. securityCode must not have sequential repeating digits.
      1. Such as ‘4’ in 271744.
    4. securityCode must not have sequential incrementing or decrementing digits. The next digit in the code cannot be 1 digit higher or 1 digit lower
      1. Such as ‘45’ in 27145.
      2. Such as ‘54’ in 27154.
    5. securityCode must contain every digit (0-9)
    6. Being that securityCode is a Long variable type, it must be defined with a following L.
      1. Long securityCode = 1234L.
    7. You may optionally define the security code value with underscores for readability.
      1. Long securityCode = 1234_4444_4444_4444L;
    8. Do not prompt for a security code, it must be coded inside the TicTacToe class.
  3. Create a loop in the TicTacToe class to play the game. This will be referred to as the ‘main’ loop for this process.
    1. Create an int variable for row position. This declaration should be done only once and before the loop starts.
    2. Create an int variable for column position. This declaration should be done before the loop starts.
    3. Inside the loop, do the following tasks
      1. Display “Your Turn” and prompt to enter a row number (0-2) to place your TicTacToe square.
      2. Prompt to enter a column number (0-2) to place your TicTacToe square.
      3. Call the setValue() method of the TicTacToeBoard instance with the input given.
        1. setValue requires 2 parameters, Row and Column.
        2. setValue is a boolean value method. It generates a true or false result. If the setValue method returns false, it was unable to process the request. When this occurs, display “Try again” and resume the loop at the beginning.
      4. Call the method hasWinner() of the TicTacToeBoard instance.
        1. If hasWinner() returns true then
          1. Call the method theWinnerIs() of the TicTacToeBoard instance and display the value returned from theWinnerIs() method as in the example below.
          2. i.e. “The winner is X”
          3. Exit the loop.
      5. Call the method theComputersTurn() of the TicTacToeBoard instance. If this method returns a false value, display that “The computer has forfeited” and exit the loop.
      6. Do task iv again.
    4. After the loop is completed – display “Game over” from the main() method.

  1. The method setValue() in the TicTacToeBoard class can be called with out of range numeric values and create a runtime error. Modify the setValue method so that it returns false if data passed is not in the range of possible values. (0 – 2).

  1. The TicTacToeBoard class does not have a way to indicate that all entries are loaded. Create a public method named hasSquaresAvailable() in the the TicTacToeBoard class that will report true if there are available squares or false is the board is full. (Review the existing checkFirstPlay() method for a similar example.)
    1. Call this new method from the TicTacToe class inside the main loop.
      1. Do this before calling setValue().
      2. Do this before calling theComputersTurn().
      3. If there are no remaining spaces then:
        1. Display “No Available spaces”.
        2. Terminate the loop.

  1. The TicTacToeBoard class currently only checks rows and columns.

          XXX           XOX

        OXO           XOO

        OOX           OOX

It does not check diagonal values.

         XXO         XOO

        OXX          XOX

        OOX         OXX

  1. Create a private method inside the TicTacToeBoard class named checkForDiagonalWin that will check for a possible diagonal win. This method does not need internal loops. Study how the private method checkRowOrColumnForWinner() works to understand what to look for. Be careful to check for null values before doing other compares as this can result in a null pointer exception.

  1. Call the method created above in step 8a from the theWinnerIs() method in the TicTacToeBoard class.

5 points Extra Credit – Change the valid input range from 0 -2 to 1-3 for the row and column indicators as part of the processing in the TicTacToe class. Do not change the setValue method in the TicTacToeBoard class. All other work must be completed to receive extra credit.

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

///////////////////////////////////////////////////////// TicTacToeBoard.java


import java.util.Random;


public class TicTacToeBoard {
private Character [][] board;// to hold all character
private Character player1;/// player 1
private Character player2;// player 2
  
public TicTacToeBoard(){
board=new Character[3][3];
  
// initialize board
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
this.board[i][j]=null;
}
}
  
// set computer as 2nd player
this.player1='X';
this.player2='O';
}
// display
  
void display(){
for(int i=0;i<3;i++){
System.out.print(" ");
  
for(int j=0;j<3;j++){
if(this.board[i][j]==null){
System.out.print(" ");
}
else{
System.out.print(this.board[i][j]);
}
  
  
if(j<2){
System.out.print(" | ");
}
}
  
if(i<2){
System.out.println("\n--------------");
}
System.out.println();
}
}
  
// set computer as first player
  
void setPlayer(){
this.player1='O';
this.player2='X';
}
  
  
// set for user move
  
boolean setValue(int i,int j){
boolean ret=false;
  
// out of the index list
  
if((i<0 || i>2) && (j<0 || j>2)){
ret=false;
}
else{
  
// if space available
  
if(hasSquaresAvailable(i,j)==true){
  
this.board[i][j]=this.player1;
  
ret=true;
}
}
  
return(ret);
}
  
  
// check space is occupied or not
public boolean hasSquaresAvailable(int i,int j){
return(this.board[i][j]==null);
}
  
// retun winner or not
  
public boolean hasWinner(){
  
   /* return win result */
  
   return(this.checkForDiagonalWin() || this.checkRowOrColumnForWinner());
  
}
  
  
// get winner name
public Character theWinnerIs(){
Character ret=' ';
int i=0;
  
   /* check each row */
   /* if each block in a row are same */
  
   for(i=0;i<3;i++){
if(this.board[i][0]!=null && this.board[i][0]==this.board[i][1] && this.board[i][1]==this.board[i][2]){
       ret=this.board[i][0];
       break;
}
   }
  
  
   /* check each col */
   /* if each block in a col are same */
  
   for(i=0;i<3;i++){
if(ret==' ' && this.board[0][i]!=null && this.board[0][i]==this.board[1][i] && this.board[1][i]==this.board[2][i]){
       ret=this.board[0][i];
       break;
}
   }
  
  
   /* if each block in 1st digonal are same */
  
   if(ret==' ' && this.board[0][0]!=null && this.board[0][0]==this.board[1][i] && this.board[1][1]==this.board[2][2]){
ret=this.board[0][0];
   }
  
   /* if each block in 2nd digonal are same */
  
   if(ret==' ' && this.board[2][0]!=null && this.board[2][0]==this.board[1][i] && this.board[1][1]==this.board[0][2]){
ret=this.board[2][0];
   }
  
   /* return win result */
  
return(ret);
}
  
  
// return computer turn
  
public boolean ComputersTurn(){
boolean ret=false;
  
// checking any space is available or not
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(this.board[i][j]==null){
ret=true;
break;
}
}
}
  
if(ret==false){
return(false);
}
  
// random turn
Random r=new Random();
  
  
int row=r.nextInt(3);
int col=r.nextInt(3);
  
// if move not available
while(this.hasSquaresAvailable(row,col)==false){
row=r.nextInt(3);
col=r.nextInt(3);
}
  
this.board[row][col]=this.player2;
  
return(true);
}
  
  
// if first player is user then return false;
// otherwise true
  
boolean checkFirstPlay(){
if(this.player1=='X'){
return(false);
}
else{
return(true);
}
}

  
// each digonal check
private boolean checkForDiagonalWin(){
boolean ret=false;
  
/* if each block in 1st digonal are same */
  
   if(this.board[0][0]!=null && this.board[0][0]==this.board[1][1] && this.board[1][1]==this.board[2][2]){
ret=true;
   }
  
   /* if each block in 2nd digonal are same */
  
   if(ret==false && this.board[2][0]!=null && this.board[2][0]==this.board[1][1] && this.board[1][1]==this.board[0][2]){
ret=true;
   }
  
return(ret);
}
  
  
// each row and column check for winner
private boolean checkRowOrColumnForWinner(){
boolean ret=false;
int i=0;
  
  
   /* check each row */
   /* if each block in a row are same */
  
   for(i=0;i<3;i++){
if(this.board[i][0]!=null && this.board[i][0]==this.board[i][1] && this.board[i][1]==this.board[i][2]){
       ret=true;
       break;
}
   }
  
  
   /* check each col */
   /* if each block in a col are same */
  
   for(i=0;i<3;i++){
if(ret==false && this.board[0][i]!=null && this.board[0][i]==this.board[1][i] && this.board[1][i]==this.board[2][i]){
       ret=true;
       break;
}
   }
  
return(ret);
}
}

////////////////////// TicTacToe.java


import java.util.Scanner;

public class TicTacToe {
private TicTacToeBoard board;
private long securityCode;
  
public TicTacToe(){
  
// sequrity code
  
this.securityCode=2910_3970_1482_7531L;
  
board=new TicTacToeBoard();
this.game();
}
  
void game(){
  
Scanner sc=new Scanner(System.in);
  
// user choice for compute first or not
  
System.out.print("Choose Player1 [C for computer /U for user] : ");
String inp=sc.next();
  
// user set for player
  
if(inp.charAt(0)=='C' || inp.charAt(0)=='c'){
this.board.setPlayer();
}
  
int row,col;
  
// check for computer is first player or not
  
if(this.board.checkFirstPlay()==true){
this.board.ComputersTurn();
}
  
  
  
while(true){
  
  
// display board
this.board.display();
  
// user move
System.out.print("\nYour Turn\nEnter Row Number [0-2] : ");
row=sc.nextInt();
  
System.out.print("Enter column Number [0-2] : ");
col=sc.nextInt();
  
// check user move is correct or not
  
// if ok , go to next step
if((row>=0 && row<=2) && (col>=0 && col<=2)){
  
  
// set user move
if(this.board.setValue(row, col)==true){
  
// check winner status for user
if(this.board.hasWinner()==true){
this.board.display();

System.out.println("\nThe Winner is "+this.board.theWinnerIs());
break;
}
else{
  
// if not win computer move
  
// if not move possible . break loop
if(this.board.ComputersTurn()==false){
this.board.display();
  
// if no computer move available break loop , and it is draw
  
System.out.println("\nNo Available spaces”");
System.out.println("The computer has forfeited");
break;
}
  
// move possible
else{
  
// check computer won the game or not
if(this.board.hasWinner()==true){
  
this.board.display();

System.out.println("\nThe Winner is "+this.board.theWinnerIs());
break;
}
}
}
}
  
// wrong bad user move
else{
System.out.println("Space is already occupied .Try Again.");
}
}
else{
System.out.println("Wrong Input , please choose correct inputs.");
}
  
  
}
  
System.out.println("Game Over.");
  
sc.close();
}
  
  
}

////////////////////////////////////  GuiBoard.java


public class GuiBoard {

public static void main(String[] args) {
TicTacToe t=new TicTacToe();
}
  
}

Add a comment
Know the answer?
Add Answer to:
Enhance and correct a Tic Tac Toe game. The game is intended to be played against...
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
  • The object ticTacToeBoard is initialized to indicate if the computer is the player 1 or player...

    The object ticTacToeBoard is initialized to indicate if the computer is the player 1 or player 2. Your task is to allow turns between the player and computer and to determine if a winner exists. The TicTacToeBoard class uses a Character class which is a wrapper class for char. It allows for the value null. Thus, the board values can be ‘X’,’O’ or null. Program Requirements In the TicTacToe class, set the existing Long variable named securityCode with a value...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

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

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

    Tic-Tac-Toe Game 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...

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

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

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

  • You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....

    You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of his/her marks on the board in a row, column, or diagonal, he/she wins. When the board fills up with neither player winning, the game ends in a draw 1) Player 1 VS Player 2: Two players are playing the game...

  • (C++) Please create a tic tac toe game. Must write a Player class to store each...

    (C++) Please create a tic tac toe game. Must write a Player class to store each players’ information (name and score) and to update their information (increase their score if appropriate) and to retrieve their information (name and score).The players must be called by name during the game. The turns alternate starting with player 1 in the first move of round 1. Whoever plays last in a round will play second in the next round (assuming there is one).The rows...

  • I need to create a Tic Tac Toe program in C++. These are the requirements Write...

    I need to create a Tic Tac Toe program in C++. These are the requirements Write a program that allows the computer to play TicTacToe against a human player or allow two human players to play one another. Implement the following conditions: The player that wins the current game goes first in the next round, and their symbol is X. The other player will be O. Keep track of the number of games played, wins, and draws for each player....

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
ADVERTISEMENT