Java Reference
In-Depth Information
what you have learned to work in developing comprehensive projects. In this section, we will
develop a Java applet with which to play the popular game of tic-tac-toe.
Two players take turns marking an available cell in a grid with their respective
tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or
diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs
when all the cells on the grid have been filled with tokens and neither player has achieved a
win. Figure 18.10 shows the representative sample runs of the example.
3
*
3
(a) The X player won the game
(b) Draw—no winners
(c) The O player won the game
F IGURE 18.10
Two players play a tic-tac-toe game.
All the examples you have seen so far show simple behaviors that are easy to model with
classes. The behavior of the tic-tac-toe game is somewhat more complex. To create classes
that model the behavior, you need to study and understand the game.
Assume that all the cells are initially empty, and that the first player takes the X token and
the second player the O token. To mark a cell, the player points the mouse to the cell and
clicks it. If the cell is empty, the token (X or O) is displayed. If the cell is already filled, the
player's action is ignored.
From the preceding description, it is obvious that a cell is a GUI object that handles the
mouse-click event and displays tokens. Such an object could be either a button or a panel.
Drawing on panels is more flexible than drawing on buttons, because on a panel the token (X
or O) can be drawn in any size, but on a button it can be displayed only as a text label. There-
fore, a panel should be used to model a cell. How do you know the state of the cell (empty, X,
or O)? You use a property named token of the char type in the Cell class. The Cell class
is responsible for drawing the token when an empty cell is clicked, so you need to write the
code for listening to the MouseEvent and for painting the shapes for tokens X and O. The
Cell class can be defined as shown in Figure 18.11.
javax.swing.JPanel
Cell
-token: char
Token used in the cell (default: ' ').
+getToken(): char
+setToken(token: char): void
#paintComponent(g: Graphics): void
Returns the token in the cell.
Sets a new token in the cell.
Paints the token in the cell.
F IGURE 18.11
The Cell class paints the token in a cell.
 
Search WWH ::




Custom Search