This assignment is designed to give you additional practice with native arrays. Also, it is awesome.
Write a class called TicTacToe to handle the basics
of a two-player game of Tic-Tac-Toe. The required methods are below.
If you've done things correctly, save a copy of the file provided below
into the same folder as TicTacToe.java and compile and run
it to play a game.
You must store the "board" in a two-dimensional array of Strings.
The only tricky part about the game is determining if a given person has won. The more straightforward way to do it takes 8 if statements.
| Instance Variables | |
|---|---|
board | a two-dimensional array of Strings |
turns | an integer keeping track of the number of turns played this game |
| Constructors | |
TicTacToe() | the default constructor, which just
creates the two-dimensional array and fills each slot with
" " (a blank space) and initializes the other attributes
|
| Accessors | |
boolean isWinner(String p) | returns
true if the letter passed in currently has three in a row.
That is, isWinner("X") will return true if X has won,
and isWinner("O") will return true if O has won
|
boolean isOver() | returns true if nine
turns have been played and false otherwise
|
boolean isCat() | returns true if all
nine spaces are filled AND neither X nor O has won
|
boolean isValid( int r, int c ) | returns true if the
given row and column corresponds to a valid space on the board
|
int numTurns() | returns the numbers of turns played so far |
String playerAt( int r, int c ) | returns the String
representing the player at the given location. Should return either
" ", "X", or "O".
|
void displayBoard() | displays the current board on the screen (code provided below) |
| Modifiers | |
void playMove(String p, int r, int c) | allows the given player to place their move at the given row and column. The row and column numbers are 0-based, so valid numbers are 0, 1, or 2 |
(...a game already in progress) X O O X X X O 'O', choose your location (row, column): 0 1 X O O O X X X O 'X', choose your location (row, column): 2 0 X O O O X X X X O The game is a tie.
// starter code for displaying the board. You're welcome to modify this if you like.
public void displayBoard()
{
System.out.println("THE BOARD");
for ( int r=0; r<3; r++ )
{
System.out.print("\t"); // a tab at the beginning of the line
for ( int c=0; c<3; c++ )
{
System.out.print( board[r][c] + " " );
}
System.out.println(); // end the line
}
}