Game Development Reference
In-Depth Information
How to do it...
We start by setting up a Game class. This will consist of the following six steps:
1. First of all, the Game class needs an ID. This is used by the server to keep track of
which game messages to relate to (since it supports many games at the same time),
and will also be used as a reference for other things.
2. The Game class needs the two Player objects, player1 and player2 , as well
as the ID of the player whose turn it currently is. We can call that cur-
rentPlayerId .
3. The Game class needs two boards; one for each player. The boards will be made of
2D Ship arrays. Each tile where there is a segment of a ship has a reference to the
Ship object; the others are null.
4. An integer status field lets us know what state the game currently is in, which is
useful for message filtering. We can also add constants for the different statuses
and set a default status, as follows:
public final static int GAME_WAITING = 0;
public final static int GAME_STARTED = 1;
public final static int GAME_ENDED = 2;
private int status = GAME_WAITING;
5. Now, we add a placeShip method. The method in this implementation is simpli-
fied and only contains verification that the ship is inside the board, as follows:
public void placeShip(int playerId, int shipId, int x,
int y, boolean horizontal){
Ship s = GameUtil.getShip(shipId);
Ship[][] board;
if(playerId == playerOne.getId()){
board = boardOne;
playerOne.increaseShips();
} else {
board = boardTwo;
playerTwo.increaseShips();
}
for(int i = 0;i < s.getSegments(); i++){
[verify segment is inside board bounds]
Search WWH ::




Custom Search