Java Reference
In-Depth Information
The animation stops if the rate is 0. If the rate is greater than 20, the animation will be too fast.
So, we purposely set the rate to a value between 0 and 20. This value is bound to the slider
value (line 13). So the slider max value is set to 20 (line 12).
16.34
How do you create a horizontal slider? How do you create a vertical slider?
Check
16.35
How do you add a listener to handle the property value change of a slider?
Point
16.36
How do you get the value from a slider? How do you get the maximum value from a
slider?
16.12 Case Study: Developing a Tic-Tac-Toe Game
This section develops a program for playing tic-tac-toe.
Key
Point
From the many examples in this and earlier chapters you have learned about objects, classes,
arrays, class inheritance, GUI, and event-driven programming. Now it is time to put what you
have learned to work in developing comprehensive projects. In this section, we will develop
a JavaFX program with which to play the popular game of tic-tac-toe.
Two players take turns marking an available cell in a 3
VideoNote
TicTacToe
3 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 16.27 shows the representative sample runs of the game.
*
(a) The X player won the game
(b) Draw — no winners
(c) The O player won the game
F IGURE 16.27
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 define 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. There are many choices for this object. We
will use a pane to model a cell and to display a token (X or O). 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 mouse-clicked action and
for painting the shapes for tokens X and O. The Cell class can be defined as shown in
Figure 16.28.
 
 
 
Search WWH ::




Custom Search