Java Reference
In-Depth Information
inform the other device that it is ready. Only when both devices have
received the initialization message do they start the game loop:
// called when Bluetooth connection is established
public void startNewGame() throws Exception
{
...
controller.getDisplay().setCurrent(gameScreen);
notifyInitialised();
...
}
private void notifyInitialised()
{
try
gameStatus = GAME_STATUS_INITIALISED;
if(isMultiPlayerGame())
{
bluetoothManager.sendMessage(MSG_GAME_INITIALISED);
}
else
{
// single player game so just start
startGame();
}
}
...
}
// called whenever the Bluetooth connection receives a message
public void notifyMessageReceived(String message)
{
if(message.equals(MSG_GAME_INITIALISED))
{
startGame();
}
else
{
// remote player score updated
gameScreen.handleMessage(message);
}
}
Once everything has been constructed and synchronized, we only
exchange messages when either player's score changes. In this case, it is
our
GameEngine
instance that handles this:
// called from game thread - update local points and notify
// remote player when playing multi-player game
private void updateScore()
{
try
pointsP1 += POINTS_PER_ATTACKER;
if(gameController.isMultiPlayerGame())
{
bluetoothManager.sendMessage(String.valueOf(pointsP1));
}
}
...
}
In a more complex game, it would be advisable to define a mes-
sage abstraction class instead of just passing strings back and forth. For
example, a common approach is to use messages containing pre-defined
integer codes (opcodes) and an optional payload. However you do it, in