The second and third sections of this step describe how to get the players to alternate. The second adds an otherPlayer() method to the TTTCell class. The third describes how to invoke otherPlayer() in the TicTacToe init() method.
By themselves, these changes do not make any sense because there is no mechanism for making plays by the computer. That issue is tackled in the fourth and fifth sections. The fourth adds a getBestPlay() method to the TicTacToe class. The fifth registers an action listener on the "Make Computer Play" button. This listener invokes getBestPlay() for the computer.
The sixth and seventh sections deal with the user message. The sixth involves writing a updateStatus() method that sets the message according to whose turn it is. The seventh describes where to invoke updateStatus().
This is the only change to the TTTCell class for this step. The rest of the changes are all in the TicTacToe class. You should recompile the TTTCell class at this time to check for syntax errors.
toPlay = TTTCell.otherPlayer(toPlay);
Whenever a method is declared static, it is handled by the class rather than any of its objects. That is the reason that you send the otherPlayer() message to the TTTCell class. Generally, methods are declared static when an object other than the class object is not needed to determine the return value.
You code for the method should begin with a TTTCell local variable named bestCell, which is initialized to null. The null value can be assigned to any object variable to indicate that there is no object.
The method should then loop through the cells checking each to see if its mark is TTTCell.NO_ONE. If it is then assign the current cell to bestCell. After the loop, return bestCell.
makePlay(myMark, getBestPlay(myMark));This will make the computer make the best play for the computer when the button is clicked.
At this time, you have enough code that you can recompile the TicacToe class and run your applet. It should behave like the demonstration applet at the bottom of this web page except for the user messages.
The method code will give you some practice with if statements. If toPlay equals myMark (the computer's mark) you should send a setText() message to the message variable, setting its text to "Push Make Computer Play Button". If toPlay equals userMark you should send a setText() message to the message variable, setting its text to "Your Play". Finally, you should enable makeComputerPlayButton if toPlay equals myMark and disable it they are not equal.
After you have added these two statements, recompile your TicTacToe class and run the applet with appletviewer. Your applet should look and behave like the following demonstration applet. It should not let either a user or computer play be made out of turn. The label at the bottom should indicate what the user should do next, except at the end of the game. That will be fixed in the next step.