Game Development Reference
In-Depth Information
1. Since the server is meant to handle several instances of a game at once, we'll
define a couple of HashMaps to keep a track of the game objects. For each game
we create, we put the Game object in the games map with the ID as a key:
private HashMap<Integer, Game> games = new
HashMap<Integer, Game>();
2. We'll also use Filters to only send messages to players in a related game. To
do this, we store a list of HostedConnections , with each being an address to
a client, with the game ID as a key:
private HashMap<Integer, List<HostedConnection>>
connectionFilters = new HashMap<Integer,
List<HostedConnection>>();
3. Since we're continuously giving out a new player ID and increasing the value of
the game ID, we'll have two fields for that as well: nextGameId and nex-
tPlayerId .
4. Everything starts with a connecting client. Like in the Setting up a server and cli-
ent recipe, we use ConnectionListener to handle this. The method either
adds the player to an existing game, or creates a new one if none are available.
Regardless of whether a new game is created or not, the addPlayer method is
called afterwards, as shown in the following code snippet:
public void connectionAdded(Server server,
HostedConnection conn) {
Game game = null;
if(games.isEmpty() || games.get(nextGameId -
1).getPlayerTwo() != null){
game = createGame();
} else {
game = games.get(nextGameId - 1);
}
addPlayer(game, conn);
}
5. The createGame method creates a new game object and sets the correct ID.
After placing it in the games map, it creates a new List<HostedConnec-
tion> called connsForGame and adds it to the connectionFilters map.
Search WWH ::




Custom Search