]> git.cworth.org Git - empires-server/blob - game.js
Don't send a re-connecting player a player-enter event for themself
[empires-server] / game.js
1 const no_team = { name: "" };
2
3 /* A single player can have multiple connections, (think, multiple
4  * browser windows with a common session cookie). */
5 class Player {
6   constructor(id, session_id, name, connection) {
7     this.id = id;
8     this.session_id = session_id;
9     this.name = name;
10     this.connections = [connection];
11     this.team = no_team;
12     this.active = true;
13   }
14
15   add_connection(connection) {
16     /* Don't add a duplicate connection if this player already has it. */
17     for (let c of this.connections) {
18       if (c === connection)
19         return;
20     }
21
22     this.connections.push(connection);
23   }
24
25   /* Returns the number of remaining connections after this one is removed. */
26   remove_connection(connection) {
27     this.connections = this.connections.filter(c => c !== connection);
28     return this.connections.length;
29   }
30
31   /* Send a string to all connections for this player. */
32   send(data) {
33     this.connections.forEach(connection => connection.write(data));
34   }
35
36   info_json() {
37     return JSON.stringify({
38       id: this.id,
39       name: this.name,
40       team: this.team.name,
41       score: this.score
42     });
43   }
44 }
45
46 /* This replacer function allows for JSON.stringify to give results
47  * for objects of various types that are used in game state.
48  */
49 function stringify_replacer(key, value) {
50   if (typeof value === 'object' && value instanceof Set) {
51     return [...value];
52   }
53   return value;
54 }
55
56 /* Base class providing common code for game engine implementations. */
57 class Game {
58   constructor(id) {
59     this.id = id;
60     this.players = [];
61     this.players_by_session = {};
62     this.active_players = 0;
63     this.next_player_id = 1;
64     this.teams = [];
65     this.state = {
66       team_to_play: no_team
67     };
68     this.first_move = true;
69
70     /* Send a comment to every connected client every 15 seconds. */
71     setInterval(() => {this.broadcast_string(":");}, 15000);
72   }
73
74   /* Suport for game meta-data.
75    *
76    * What we want here is an effectively static field that is
77    * accessible through either the class name (SomeGame.meta) or an
78    * instance (some_game.meta). To pull this off we do keep two copies
79    * of the data. But the game classes can just set SomeGame.meta once
80    * and then reference it either way.
81    */
82   static set meta(data) {
83     /* This allows class access (SomeGame.meta) via the get method below. */
84     this._meta = data;
85
86     /* While this allows access via an instance (some_game.meta). */
87     this.prototype.meta = data;
88   }
89
90   static get meta() {
91     return this._meta;
92   }
93
94   /* Just performs some checks for whether a move is definitely not
95    * legal (such as not the player's turn). A child class is expected
96    * to override this (and call super.add_move early!) to implement
97    * the actual logic for a move. */
98   add_move(player, move) {
99
100     /* The checks here don't apply on the first move. */
101     if (! this.first_move) {
102
103       /* Discard any move asserting to be the first move if it's no
104        * longer the first move. This resolves the race condition if
105        * multiple players attempt to make the first move. */
106       if (move.assert_first_move) {
107         return { legal: false,
108                  message: "Your opponent beat you to the first move" };
109       }
110
111       /* Cannot move if you are not on a team. */
112       if (player.team === no_team)
113       {
114         return { legal: false,
115                  message: "You must be on a team to take a turn" };
116       }
117
118       /* Cannot move if it's not this player's team's turn. */
119       if (player.team !== this.state.team_to_play)
120       {
121         return { legal: false,
122                  message: "It's not your turn to move" };
123       }
124     }
125
126     return { legal: true };
127   }
128
129   /* Assign team only if player is unassigned.
130    * Return true if assignment made, false otherwise. */
131   assign_player_to_team_perhaps(player, team)
132   {
133     if (player.team !== no_team)
134       return false;
135
136     player.team = team;
137     this.broadcast_event("player-update", player.info_json());
138
139     return true;
140   }
141
142   /* This function is called after the child add_move has returned
143    * 'result' so that any generic processing can happen.
144    *
145    * In particular, we assign teams for a two-player game where a
146    * player assumed a team by making the first move. */
147   post_move(player, result)
148   {
149     if (this.first_move && result.legal) {
150       this.first_move = false;
151
152       this.assign_player_to_team_perhaps(player, this.teams[0]);
153
154       /* Yes, start at 1 to skip teams[0] which we just assigned. */
155       for (let i = 1; i < this.teams.length; i++) {
156         const other = this.players.find(p => (p !== player) && (p.team === no_team));
157         if (!other)
158           return;
159         this.assign_player_to_team_perhaps(other, this.teams[i]);
160       }
161     }
162   }
163
164   add_player(session, connection) {
165     /* First see if we already have a player object for this session. */
166     const existing = this.players_by_session[session.id];
167     if (existing) {
168       if (! existing.active) {
169         /* If we're re-activating a previously idled player, then we
170          * need to alert everyone that this player is now back.
171          */
172         existing.active = true;
173         this.active_players++;
174         this.broadcast_event("player-enter", existing.info_json());
175       }
176       existing.add_connection(connection);
177       return existing;
178     }
179
180     /* No existing player. Add a new one. */
181     const id = this.next_player_id;
182     let nickname = session.nickname;
183     if (nickname === "")
184       nickname = "Guest";
185     const nickname_orig = nickname;
186
187     /* Ensure we don't have a name collision with a previous player. */
188     let unique_suffix = 1;
189     while (this.players.find(player => player.name === nickname))
190     {
191       nickname = `${nickname_orig}${unique_suffix.toString().padStart(2, '0')}`;
192       unique_suffix++;
193     }
194
195     const player = new Player(id, session.id, nickname, connection);
196
197     /* Broadcast before adding player to list (to avoid announcing the
198      * new player to itself). */
199     this.broadcast_event("player-enter", player.info_json());
200
201     this.players.push(player);
202     this.players_by_session[session.id] = player;
203     this.active_players++;
204     this.next_player_id++;
205
206     /* After adding the player to the list, and if we are already past
207      * the first move, assign this player to the first team that
208      * doesn't already have a player assigned (if any). */
209     if (! this.first_move) {
210       const have_players = Array(this.teams.length).fill(false);
211       this.players.forEach(p => {
212         if (p.team.id !== undefined)
213           have_players[p.team.id] = true;
214       });
215       const first_empty = have_players.findIndex(i => i === false);
216       this.assign_player_to_team_perhaps(player, this.teams[first_empty]);
217     }
218
219     return player;
220   }
221
222   /* Drop a connection object from a player, and if it's the last one,
223    * then drop that player from the game's list of players. */
224   remove_player_connection(player, connection) {
225     const remaining = player.remove_connection(connection);
226     if (remaining === 0) {
227       player.active = false;
228       this.active_players--;
229       const player_data = JSON.stringify({ id: player.id });
230       this.broadcast_event("player-exit", player_data);
231     }
232   }
233
234   /* Send a string to all players */
235   broadcast_string(str) {
236     this.players.forEach(player => player.send(str + '\n'));
237   }
238
239   /* Send an event to all players.
240    *
241    * An event has both a declared type and a separate data block.
242    * It also ends with two newlines (to mark the end of the event).
243    */
244   broadcast_event(type, data) {
245     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
246   }
247
248   broadcast_event_object(type, obj) {
249     this.broadcast_event(type, JSON.stringify(obj));
250   }
251
252   handle_events(request, response) {
253     /* These headers will keep the connection open so we can stream events. */
254     const headers = {
255       "Content-type": "text/event-stream",
256       "Connection": "keep-alive",
257       "Cache-Control": "no-cache"
258     };
259     response.writeHead(200, headers);
260
261     /* Add this new player. */
262     const player = this.add_player(request.session, response);
263
264     /* And queue up cleanup to be triggered on client close. */
265     request.on('close', () => {
266       this.remove_player_connection(player, response);
267     });
268
269     /* Give the client the game-info event. */
270     const game_info_json = JSON.stringify({
271       id: this.id,
272       url: `${request.protocol}://${request.hostname}/${this.id}`
273     });
274     response.write(`event: game-info\ndata: ${game_info_json}\n\n`);
275
276     /* And the player-info event. */
277     response.write(`event: player-info\ndata: ${player.info_json()}\n\n`);
278
279     /* As well as player-enter events for all existing, active players. */
280     this.players.filter(p => p !== player && p.active).forEach(p => {
281       response.write(`event: player-enter\ndata: ${p.info_json()}\n\n`);
282     });
283
284     /* Finally, if this game class has a "state" property, stream that
285      * current state to the client. */
286     if (this.state) {
287       const state_json = JSON.stringify(this.state, stringify_replacer);
288       response.write(`event: game-state\ndata: ${state_json}\n\n`);
289     }
290   }
291
292   handle_player(request, response) {
293     const player = this.players_by_session[request.session.id];
294     const name = request.body.name;
295     const team_name = request.body.team;
296     var updated = false;
297     if (! player) {
298       response.sendStatus(404);
299       return;
300     }
301
302     if (name && (player.name !== name)) {
303       player.name = name;
304
305       /* In addition to setting the name within this game's player
306        * object, also set the name in the session. */
307       request.session.nickname = name;
308       request.session.save();
309
310       updated = true;
311     }
312
313     if (team_name !== null && (player.team.name !== team_name))
314     {
315       if (team_name === "") {
316         player.team = no_team;
317         updated = true;
318       } else {
319         const index = this.teams.findIndex(t => t.name === team_name);
320         if (index >= 0) {
321           player.team = this.teams[index];
322           updated = true;
323         }
324       }
325     }
326
327     if (updated)
328       this.broadcast_event("player-update", player.info_json());
329
330     response.send("");
331   }
332
333   broadcast_move(move) {
334     this.broadcast_event("move", JSON.stringify(move));
335   }
336
337 }
338
339 module.exports = Game;