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