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