Do one method at a time and make it work before moving on


In a game of tic-tac-toe, 2 players take turns marking an available cell in a 3x3 grid with their respective tokens (either X or O). When one player has placed 3 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 on the grid have been filled with tokens and neither player has achieved a win. Design a program for playing tic-tac-toe.

The program prompts 2 players to enter an X token and O token alternately. Whenever a token is entered, the program redisplays the board on the console and determines the status of the game (win, draw or continue). 

MUST USE THE FOLLOWING TWO CLASSES IN THE SOLUTION:

TicTacToe Class

This class is the driver program. It contains one method: main() which uses the GameBoard class to play the game of Tic-Tac-Toe. It also contains a flag 'keepPlaying' that is set when the game is over (win or draw).

Here is the UML:

TicTacToe

+ main(String): void

Here is the algorithm:

displayBoard
while (keepPlaying)
    makeAMove X
    diplayBoard
    if (isWon X) 
        X player won
    else if (isDraw)
        No winner
    if (keepPlaying) //no need to continue if X won/draw
        displayBoard
        makeAMove O
        if (isWon O)
            O player won
        else if (isDraw)
            No winner

GameBoard Class

This class holds the reference to the 2-D array representing the board and contains all the methods needed to display the board, have one user make a move, check if there is a winner, and check if there is a draw.

The constructor should initialize each cell to a character of choice (I used '$' but can use anything even blank ' '). Use a nested loop to:

Here is the UML:

GameBoard

- board: char[ ][ ]

- input: Scanner

+ GameBoard(): GameBoard

+ displayBoard(): void

+ makeAMove(char): void

+ isDraw(): boolean

+ isWon(char): boolean

The ONLY classes may use are: GameBoard and the driver: TicTacToe

Input

One user acts as BOTH player X and player O and is prompted to enter the row and then the column they want. Example (user input in bold):

Enter a row for player X: 1

Enter a column for player X: 2

Hint: 

Do one method at a time and make it work before moving on to the next method. Start with displaying the board using a nested for-loop.

Note: in the constructor for GameBoard class, use nested loops to initialize the 2-D array named board

Solution Preview :

Prepared by a verified Expert
Basic Computer Science: Do one method at a time and make it work before moving on
Reference No:- TGS02740465

Now Priced at $20 (50% Discount)

Recommended (93%)

Rated (4.5/5)