The constructor for this class has no parameters. It just sets the background color to white.
Near the top of the class definition, define the following int constants.
NAME | Initial Value |
---|---|
NO_ONE | 0 |
X | 1 |
O | 2; |
DRAW | 3; |
These constants will be used as parameters or return values for various methods to specify a player, a mark to place in a cell, or a game status. When used inside the TTTCell class, these constants can be used just by specifiying their name. When used outside the TTTCell class, their name must be preceeded by TTTCell. as in TTTCell.X.
Now declare an int instance variable named mark initialized to NO_ONE. You should also write a getter method getMark() and setter method setMark(). In addition to changing the value of mark, setMark() should invoke repaint() so that a cell is repainted whenever its mark is changed.
Finally, you need to override the paintComponent() method. In this method, declare local variables w and h which are one less than the width and height of the cell. You can obtain the width and height of the cell by invoking getWidth() and getHeight(). Then draw a border around the cell. The border is a w by h rectangle whose upper left corner is the point (0, 0). If mark is X then draw a line from (w/4, h/4) to (3*w/4, 3*h/4) and another line from (w/4, 3*h/4) to (3*w/4, w/4). These lines form an X mark in a cell. If mark is O then draw an oval to form an O mark. The bounding rectangle for the oval has its upper left corner at (w/4, w/4). Its width is w/2 and its height is h/2.
for (int i = 0; i < 9; i++) { TTTCell c = new TTTCell(); c.setMark(i%3); // The i%3 will change in Step 3. board.add(c); }This is a Java for loop. It repeats the statements inside under the control of the three clauses within the parentheses in the first line. The clause int i = 0 declares a new variable i for use within the loop. Its initialization gives i the value 0 for the first repetition. The clause i++ increments i at the end of each repetition. The clause i < 9 is a condition that controls how long the statements inside are repeated. It is tested at the beginning of each repetition. If it is false then the repetitions terminate.
This loop repeats 9 times with i going from 0 t0 8. It creates 9 new cells and adds them to the board. The marks are set to three different values so that you can see how your TTTCell class draws its marks. i%3 is the remainder when i is divided by 3.
For the last modification to the TicTacToe class, add a statement that invokes setupBoard() at the beginning of your init() method.
After you have created the TTTCell class and modified the TicTacToe class, compile both classes and run the applet with appletviewer. At this time, the applet does not respond to any user actions. It should look like the following demonstration applet.