Game Development Reference
In-Depth Information
5. We create another class called
FireActionMessage
, which also extends
GameMessage
.
6. This has a reference to the player firing and an
x
and
y
coordinate.
Message handling on the server is similar to the one on the client. We have a
Server-
MessageHandler
class implementing the
MessageListener
interface. This has to
handle receiving messages from the player placing ships, and firing.
1. Inside the
messageReceived
method, catch all
PlaceShipMessages
.
Using the supplied
gameId
, we get the game instance from the server's
getGame
method and call the
placeShip
method. Once this is done, we check
to see whether both players have placed all their ships. If that is the case, it's time
to start the game:
public void messageReceived(HostedConnection conn,
Message m) {
if (m instanceof PlaceShipMessage){
PlaceShipMessage shipMessage = (PlaceShipMessage)
m;
int gameId = shipMessage.getGameId();
Game game = gameServer.getGame(gameId);
game.placeShip( … );
if(game.getPlayerOne().getShips() == 5 &&
game.getPlayerTwo() != null&&
game.getPlayerTwo().getShips() == 5){
gameServer.startGame(gameId);
}
2. In the
startGame
method, the first thing we need to do is send a message to let
the players know the game is now started. We know what clients to send the mes-
sage to by getting the list of connections from the
connectionFilters
map
as follows:
public Game startGame(int gameId){
Game game = games.get(gameId);
List<HostedConnection> connsForGame =
connectionFilters.get(gameId);
GameStatusMessage startMessage = new
GameStatusMessage();