Java Reference
In-Depth Information
Taking Turns
The last bit of missing functionality in the Reversi application is the ability for players to take turns placing pieces on
the board. We already have the infrastructure needed to accept mouse input and display pieces. All that is needed is a
little glue code, plus some model enhancements to finish the game play.
Picking up where we left off in the previous section, the first step is to add an onMouseClicked event handler to
the ReversiSquare init method:
setOnMouseClicked(t -> {
model.play(x, y);
highlightTransition.setRate(-1);
highlightTransition.play();
});
This method both calls the model function to play the current turn and also removes the highlight from the
current cell, similar to the mouse exited event handler.
The play() function in the model class needs to perform several activities for each legal move:
Set the clicked cell to be owned by the current player.
Flip over captured pieces in any of eight possible directions.
Change the turn to be the opposite player's.
An example implementation of the play() method is shown in Listing 5-17.
Listing 5-17. Example play() Method That Flips Cells in Eight Directions
public void play(int cellX, int cellY) {
if (legalMove(cellX, cellY).get()) {
board[cellX][cellY].setValue(turn.get());
flip(cellX, cellY, 0, -1, turn);
flip(cellX, cellY, -1, -1, turn);
flip(cellX, cellY, -1, 0, turn);
flip(cellX, cellY, -1, 1, turn);
flip(cellX, cellY, 0, 1, turn);
flip(cellX, cellY, 1, 1, turn);
flip(cellX, cellY, 1, 0, turn);
flip(cellX, cellY, 1, -1, turn);
turn.setValue(turn.getValue().opposite());
}
}
Notice that it follows the same pattern as the legalMove() function we defined earlier to determine whether any
pieces can be flipped, with the main difference being that it does not make use of binding. The implementation of the
flip method also shares many similarities to the algorithm used in the canFlip() method, but again does not need to
bother with creating a binding:
public void flip(int cellX, int cellY, int directionX, int directionY, ObjectProperty<Owner> turn) {
if (canFlip(cellX, cellY, directionX, directionY, turn).get()) {
int x = cellX + directionX;
int y = cellY + directionY;
while (x >=0 && x < BOARD_SIZE && y >=0 && y < BOARD_SIZE && board[x][y].get() != turn.get()) {
 
Search WWH ::




Custom Search