Step 4
Overview
In this step you will set up the response to "Start New Game" button
clicks.
This will only involve changes in the TicTacToe class.
You will need to change the initialization of the toPlay instance
variable, add getCell() and startNewGame() methods, and
registering a listener for the "Start New Game" button.
Changing the Initialization of toPlay
Change the initialization on the toPlay variable from
TTTCell.X to TTTCell.NO_ONE.
Due to the fact that the makePlay() method was designed to do
nothing when toPlay is TTTCell.NO_ONE, this change
prevents the user from changing marks when the applet starts up.
Changes made in later sections of this step will change toPlay to
TTTCell.X when the "Start New Game" button is clicked, allowing
the user to proceed.
The getCell() Method
This method is a convenience method that keeps ugly code from appearing in
a number of different places.
It returns a TTTCell and has an int parameter n.
It contains just one not very pretty statement.
return (TTTCell)board.getComponent(n);
When the 9 cells were added to the board, they were assigned numbers from 0
to 8.
They are retrieved using the getComponent() method, defined in
the old AWT Component class.
The parameter specifies the assigned cell number.
The getCell() method makes it easier to do something with all of
the cells.
You just write a for loop like the following.
for (int i = 0; i < 9; i++) {
TTTCell c = getCell(i);
do something with c
}
You will need loops like this in several places.
The first will be in the next section.
The startNewGame() Method
This method will be invoked in the button listener described in the next
section.
It has no parameters and no returned value.
It begins with a for loop to step through all of the cells in the game
board (use getCell()), sending a setMark(TTTCell.NO_ONE)
message to each.
This clears the marks from all of the cells.
After the loop, set the toPlay instance variable to
TTTCell.X.
This makes X the first player for the new game and allows the user to make
X marks in the cells.
Adding a Listener for the "Start New Game" Button
The only remaining change is adding an action listener to the
startNewGameButton instance variable.
This listener should be added in the init() method.
The listener's actionPerformed() method should just invoke your
startNewGame() method.
After you have made the above changes, recompile your TTTCell class and
run the applet with appletviewer.
You should see two changes in the behavior of the applet.
First, nothing will happen when you click on a cell until you have clicked
on the "Start New Game" button.
After that, X marks will appear in cells that you click on, as before.
The second change is that all of the marks will be cleared whenever you
click on the "Start New Game" button.
Demonstration Applet