Java Reference
In-Depth Information
javafx.scene.layout.Pane
Cell
-token: char
Token used in the cell (default: ' ').
+getToken(): char
+setToken(token: char): void
-handleMouseClick(): void
Returns the token in the cell.
Sets a new token in the cell.
Handles a mouse click event.
F IGURE 16.28
The Cell class displays the token in a cell.
The tic-tac-toe board consists of nine cells, created using new Cell[3][3] . To determine
which player's turn it is, you can introduce a variable named whoseTurn of the char type.
whoseTurn is initially 'X' , then changes to 'O' , and subsequently changes between 'X' and
'O' whenever a new cell is occupied. When the game is over, set whoseTurn to ' ' .
How do you know whether the game is over, whether there is a winner, and who the
winner, if any? You can define a method named isWon(char token) to check whether a
specified token has won and a method named isFull() to check whether all the cells are
occupied.
Clearly, two classes emerge from the foregoing analysis. One is the Cell class, which
handles operations for a single cell; the other is the TicTacToe class, which plays the whole
game and deals with all the cells. The relationship between these two classes is shown in
FigureĀ 16.29.
Cell
javafx.application.Application
9
1
TicTacToe
-whoseTurn: char
-cell: Cell[][]
-lblStatus: Label
Indicates which player has the turn, initially X.
A 3
3, two-dimensional array for cells.
A label to display game status.
+TicTacToe()
+isFull(): boolean
+isWon(token: char): boolean
Constructs the TicTacToe user interface.
Returns true if all cells are filled.
Returns true if a player with the specified token has won.
F IGURE 16.29
The TicTacToe class contains nine cells.
Since the Cell class is only to support the TicTacToe class, it can be defined as an inner
class in TicTacToe . The complete program is given in Listing 16.13.
L ISTING 16.13
TicTacToe.java
1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.scene.Scene;
4 import javafx.scene.control.Label;
5 import javafx.scene.layout.BorderPane;
 
 
Search WWH ::




Custom Search