Step 3


Overview

In this step you will set up the response to mouse clicks in cells. This will involve several changes in the TicTacToe class. You will add three instance variables, a makePlay() method, and add some code to the setupBoard() method. These changes are described in detail in the following sections.

Adding TicTacToe Class Instance Variables

You will need to add three int instance variables. They are described in the following table.
Name Initialization
userMark TTTCell.X
myMark TTTCell.O
toPlay TTTCell.X
The first two variables hold the marks that are currently used by the user (the human player) and the computer. The third keeps track of who is supposed to play next. Its initialization is only temporary, so that you can see marks when you click on cells. It will be changed in Step 4. You may want to put a conspicuous comment on it so that it will be easy to find.

The TicTacToe Class makePlay() Method

Next, add a method named makePlay(). This method has void return type. It has two parameters as described in the following table.
Type Name
int plyr
TTTCell c
The method should return immediately if any of the the following is true. You can use a single if statement to do this, with the three boolean clauses joined with the || (or) operator. After the if statement, you should have one more statement. It should send c a setMark() message, setting the cell mark to toPlay. The if statement prevents this change if it is not plyr's turn to play, if c is null, or if the cell is already marked with an X or an O. The possibility that c is null will arise later when you add code to make a play for the computer.

Adding Code to the TicTacToe Class setupBoard() Method

In the loop that is adding cells to the board, change the parameter in the setMark() message from i%3 to TTTCell.NO_ONE. Also, register a mouse listener for the cell with the following code.
    c.addMouseListener(new MouseAdapter() {
	public void mouseClicked(MouseEvent e) {
	    TTTCell cell = (TTTCell)e.getSource();
	    makePlay(userMark, cell);
	}
    });
In this listener, you are actually using the event parameter of the listener method for a change. Here, you are using it to get the cell that generated the event so that you can make a play there.

The Java class libraries define adapter classes for most of the listener interfaces that have more than one method. The adapter class just provides do nothing implementations of all of the methods. It simplifies creation of listeners that only need to implement one of the methods.

After you have made the above changes, recompile your TicTacToe class and run the applet with appletviewer. When you click on cells, X marks should appear in them. Your applet should look and work like the following demonstration applet.

Demonstration Applet