Java Reference
In-Depth Information
Going back to the Reversi game rules, a move is valid only in the following circumstances.
There is not already another piece at the same location.
The piece is placed adjacent to a piece of the opposite color, and on that same line, there is
another piece of the same color on the opposite end that would allow a flip of one or more of
the opposing player's pieces.
To start with, you need to add a legalMove function to the model class that checks whether the cell is empty and
then verifies all eight directions around a given Cell :
public BooleanBinding legalMove(int x, int y) {
return board[x][y].isEqualTo(Owner.NONE).and(
canFlip(x, y, 0, -1, turn).or(
canFlip(x, y, -1, -1, turn).or(
canFlip(x, y, -1, 0, turn).or(
canFlip(x, y, -1, 1, turn).or(
canFlip(x, y, 0, 1, turn).or(
canFlip(x, y, 1, 1, turn).or(
canFlip(x, y, 1, 0, turn).or(
canFlip(x, y, 1, -1, turn))))))))
);
}
We have chosen to make all the public model functions return bindings. this makes it possible to use property
binding to update the ui and will efficiently defer updates until the playing board changes.
Note
The canFlip method validates the second condition for the given direction indicated by the cellX , cellY
arguments and the player whose turn is indicated. Because it would be more complicated and less efficient to use the
fluent binding interface, we chose to create a custom binding instead.
Creating a custom binding involves the following.
First override the binding class (in this case
BooleanBinding ) with an inner class.
To set up the bound variables, use a static initializer that calls the bind function for each
variable on which the algorithm depends.
computeValue method, and return the new calculated value of the binding.
The basic algorithm for calculating whether this is a legal move is to check the first cell in the given direction to
make sure it is a different color, and if it is, continue walking cells until you find one that is the same color. If you do
find one that is the same color, it is a legal move with pieces to flip, but if the next cell is the same color or there is no
opposite color piece at the other end, it is not a legal move.
This means that the static initializer needs to add a property binding for every cell in the given direction, and the
algorithm needs to use a loop to go through all of the cells, checking their owner, as shown in the following code.
Override the
public BooleanBinding canFlip(final int cellX, final int cellY, final int directionX, final int
directionY, final ObjectProperty<Owner> turn) {
return new BooleanBinding() {
{
bind(turn);
int x = cellX + directionX;
 
 
Search WWH ::




Custom Search