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