+ add_player(session, connection) {
+ /* First see if we already have a player object for this session. */
+ const existing = this.players[session.id];
+ if (existing) {
+ existing.add_connection(connection);
+ return existing;
+ }
+
+ /* No existing player. Add a new one. */
+ const id = this.next_player_id;
+ const player = new Player(id, session.nickname, connection);
+
+ /* Broadcast before adding player to list (to avoid announcing the
+ * new player to itself). */
+ const player_data = JSON.stringify({ id: player.id, name: player.name });
+ this.broadcast_event("player-enter", player_data);
+
+ this.players[session.id] = player;
+ this.next_player_id++;
+
+ return player;
+ }
+
+ /* Drop a connection object from a player, and if it's the last one,
+ * then drop that player from the game's list of players. */
+ remove_player_connection(player, connection) {
+ const remaining = player.remove_connection(connection);
+ if (remaining === 0) {
+ const player_data = JSON.stringify({ id: player.id });
+ this.players.filter(p => p !== player);
+ this.broadcast_event("player-exit", player_data);
+ }