Java Reference
In-Depth Information
}
initBoard();
}
public static ReversiModel getInstance() {
return ReversiModelHolder.INSTANCE;
}
private static class ReversiModelHolder {
private static final ReversiModel INSTANCE = new ReversiModel();
}
}
There are a few things to point out about this model.
It uses the Java singleton pattern for creating and providing access to an instance.
The board size is defined via a constant, which makes it easy to adjust the dimensions in the
future.
The turn variable is declared as an observable object property so that we can make use of it in
bind statements.
The board is declared as a two-dimensional array containing observable object properties,
allowing binding to the current game state.
Owner class for both the board contents and the current turn.
Next we need to define the Owner enumeration that is used in the ReversiModel . As shown in the following code,
you can define the Owner class as a Java enum that contains states for WHITE , BLACK , and, in the case of empty cells, NONE .
The model references an
public enum Owner {
NONE,
WHITE,
BLACK;
public Owner opposite() {
return this == WHITE ? BLACK : this == BLACK ? WHITE : NONE;
}
public Color getColor() {
return this == Owner.WHITE ? Color.WHITE : Color.BLACK;
}
public String getColorStyle() {
return this == Owner.WHITE ? "white" : "black";
}
}
This enumeration class contains a few extra helper functions that we make use of later. The first is called
opposite() and can be used to convert from black to white and vice versa, which is very useful for swapping turns and
implementing the game algorithm later. The next two methods return a color as either a JavaFX Color object or a style
String for use within style properties in the UI.
 
Search WWH ::




Custom Search