]> git.cworth.org Git - empires-server/blob - empires.js
Include still-answering players when ruling on end-asnwering majority
[empires-server] / empires.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 const GamePhase = {
5   JOIN:    1,
6   REVEAL:  2,
7   CAPTURE: 3,
8   properties: {
9     1: {name: "join"},
10     2: {name: "reveal"},
11     3: {name: "capture"}
12   }
13 };
14
15 /**
16  * Shuffles array in place.
17  * @param {Array} a items An array containing the items.
18  */
19 function shuffle(a) {
20   if (a === undefined)
21     return;
22
23   var j, x, i;
24   for (i = a.length - 1; i > 0; i--) {
25     j = Math.floor(Math.random() * (i + 1));
26     x = a[i];
27     a[i] = a[j];
28     a[j] = x;
29   }
30 }
31
32 class Empires extends Game {
33   constructor(id) {
34     super(id);
35     this._spectators = [];
36     this.next_spectator_id = 1;
37     this._players = [];
38     this.next_player_id = 1;
39     this.characters_to_reveal = null;
40     this.phase = GamePhase.JOIN;
41   }
42
43   add_spectator(name, session_id) {
44     /* Don't add another spectator that matches an existing session. */
45     const existing = this._spectators.findIndex(
46       spectator => spectator.session_id === session_id);
47     if (existing >= 0)
48       return existing.id;
49
50     const new_spectator = {id: this.next_spectator_id,
51                            name: name,
52                            session_id: session_id
53                           };
54     this._spectators.push(new_spectator);
55     this.next_spectator_id++;
56     this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
57
58     return new_spectator.id;
59   }
60
61   remove_spectator(id) {
62     const index = this._spectators.findIndex(spectator => spectator.id === id);
63     this._spectators.splice(index, 1);
64
65     this.broadcast_event("spectator-leave", `{"id": ${id}}`);
66   }
67
68   register_player(name, character) {
69     const new_player = {id: this.next_player_id,
70                        name: name,
71                        character: character,
72                        captures: [],
73                        };
74     this._players.push(new_player);
75     this.next_player_id++;
76     /* The syntax here is using an anonymous function to create a new
77       object from new_player with just the subset of fields that we
78       want. */
79     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
80     this.broadcast_event("player-join", player_data);
81
82     return new_player;
83   }
84
85   remove_player(id) {
86     const index = this._players.findIndex(player => player.id === id);
87     this._players.splice(index, 1);
88
89     this.broadcast_event("player-leave", `{"id": ${id}}`);
90   }
91
92   reset() {
93     this._players = [];
94     this.characters_to_reveal = null;
95     this.next_player_id = 1;
96
97     this.change_phase(GamePhase.JOIN);
98
99     this.broadcast_event("spectators", "{}");
100     this.broadcast_event("players", "{}");
101   }
102
103   reveal_next() {
104     /* Don't try to reveal anything if we aren't in the reveal phase. */
105     if (this.phase != GamePhase.REVEAL) {
106       clearInterval(this.reveal_interval);
107       return;
108     }
109
110     if (this.reveal_index >= this.characters_to_reveal.length) {
111       clearInterval(this.reveal_interval);
112       this.broadcast_event("character-reveal", '{"character":""}');
113       return;
114     }
115     const character = this.characters_to_reveal[this.reveal_index];
116     this.reveal_index++;
117     const character_data = JSON.stringify({"character":character});
118     this.broadcast_event("character-reveal", character_data);
119   }
120
121   reveal() {
122     this.change_phase(GamePhase.REVEAL);
123
124     if (this.characters_to_reveal === null) {
125       this.characters_to_reveal = [];
126       this.characters_to_reveal = this._players.reduce((characters, player) => {
127         characters.push(player.character);
128         return characters;
129       }, []);
130       shuffle(this.characters_to_reveal);
131     }
132
133     this.reveal_index = 0;
134
135     this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
136   }
137
138   start() {
139     this.change_phase(GamePhase.CAPTURE);
140   }
141
142   capture(captor_id, captee_id) {
143     /* TODO: Fix to fail on already-captured players (or to move the
144      * captured player from an old captor to a new—need to clarify in
145      * the API specification which we want here. */
146     let captor = this._players.find(player => player.id === captor_id);
147     captor.captures.push(captee_id);
148
149     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
150   }
151
152   liberate(captee_id) {
153     let captor = this._players.find(player => player.captures.includes(captee_id));
154     captor.captures.splice(captor.captures.indexOf(captee_id), 1);
155   }
156
157   restart() {
158     for (const player of this._players) {
159       player.captures = [];
160     }
161   }
162
163   get characters() {
164     return this._players.map(player => player.character);
165   }
166
167   get empires() {
168     return this._players.map(player => ({id: player.id, captures: player.captures}));
169   }
170
171   get spectators() {
172     /* We return only "id" and "name" here (specifically not session_id!). */
173     return this._spectators.map(spectator => ({
174       id: spectator.id,
175       name: spectator.name
176     }));
177   }
178
179   /* The base class recently acquired Game.players which works like
180    * Empires.spectators, (and meanwhile the Empires._players
181    * functionality could perhaps be reworked into
182    * Game.players[].team). Until we do that rework, lets use
183    * .registered_players as the getter for the Empires-specific
184    * ._players property to avoid mixing it up with the distinct
185    * Game.players property. */
186   get registered_players() {
187     return this._players.map(player => ({id: player.id, name: player.name }));
188   }
189
190   game_phase_event_data(old_phase, new_phase) {
191     var old_phase_name;
192     if (old_phase)
193       old_phase_name = GamePhase.properties[old_phase].name;
194     else
195       old_phase_name = "none";
196     const new_phase_name = GamePhase.properties[new_phase].name;
197
198     return `{"old_phase":"${old_phase_name}","new_phase":"${new_phase_name}"}`;
199   }
200
201   /* Inform clients about a phase change. */
202   broadcast_phase_change() {
203     const event_data = this.game_phase_event_data(this.old_phase, this.phase);
204     this.broadcast_event("game-phase", event_data);
205   }
206
207   /* Change game phase and broadcast the change to all clients. */
208   change_phase(phase) {
209     /* Do nothing if there is no actual change happening. */
210     if (phase === this.phase)
211       return;
212
213     this.old_phase = this.phase;
214     this.phase = phase;
215
216     this.broadcast_phase_change();
217   }
218
219   handle_events(request, response) {
220
221     super.handle_events(request, response);
222
223     /* Now that a client has connected, first we need to stream all of
224      * the existing spectators and players (if any). */
225     if (this._spectators.length > 0) {
226       const spectators_json = JSON.stringify(this.spectators);
227       const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
228       response.write(spectators_data);
229     }
230
231     if (this._players.length > 0) {
232       const players_json = JSON.stringify(this.registered_players);
233       const players_data = `event: players\ndata: ${players_json}\n\n`;
234       response.write(players_data);
235     }
236
237     /* And we need to inform the client of the current game phase.
238      *
239      * In fact, we need to cycle through each phase transition from the
240      * beginning so the client can see each.
241      */
242     var old_phase = null;
243     for (var phase = GamePhase.JOIN; phase <= this.phase; phase++) {
244       var event_data = this.game_phase_event_data(old_phase, phase);
245       response.write("event: game-phase\n" + "data: " + event_data + "\n\n");
246       old_phase = phase;
247     }
248   }
249
250 }
251
252 Empires.router = express.Router();
253 const router = Empires.router;
254
255 router.post('/spectator', (request, response) => {
256   const game = request.game;
257   var name = request.session.nickname;
258
259   /* If the request includes a name, that overrides the session nickname. */
260   if (request.body.name)
261     name = request.body.name;
262
263   const id = game.add_spectator(name, request.session.id);
264   response.send(JSON.stringify(id));
265 });
266
267 router.delete('/spectator/:id', (request, response) => {
268   const game = request.game;
269   game.remove_spectator(parseInt(request.params.id));
270   response.send();
271 });
272
273 router.post('/register', (request, response) => {
274   const game = request.game;
275   var name = request.session.nickname;;
276
277   /* If the request includes a name, that overrides the session nickname. */
278   if (request.body.name)
279     name = request.body.name;
280
281   const player = game.register_player(name, request.body.character);
282   response.send(JSON.stringify(player.id));
283 });
284
285 router.post('/deregister/:id', (request, response) => {
286   const game = request.game;
287   game.remove_player(parseInt(request.params.id));
288   response.send();
289 });
290
291 router.post('/reveal', (request, response) => {
292   const game = request.game;
293   game.reveal();
294   response.send();
295 });
296
297 router.post('/start', (request, response) => {
298   const game = request.game;
299   game.start();
300   response.send();
301 });
302
303 router.post('/reset', (request, response) => {
304   const game = request.game;
305   game.reset();
306   response.send();
307 });
308
309 router.post('/capture/:captor/:captee', (request, response) => {
310   const game = request.game;
311   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
312   response.send();
313 });
314
315 router.post('/liberate/:id', (request, response) => {
316   const game = request.game;
317   game.liberate(parseInt(request.params.id));
318   response.send();
319 });
320
321 router.post('/restart', (request, response) => {
322   const game = request.game;
323   game.restart(parseInt(request.params.id));
324     response.send();
325 });
326
327 router.get('/characters', (request, response) => {
328   const game = request.game;
329   response.send(game.characters);
330 });
331
332 router.get('/empires', (request, response) => {
333   const game = request.game;
334   response.send(game.empires);
335 });
336
337 router.get('/spectators', (request, response) => {
338   const game = request.game;
339   response.send(game.spectators);
340 });
341
342 router.get('/players', (request, response) => {
343   const game = request.game;
344   response.send(game.registered_players);
345 });
346
347 Empires.meta = {
348   name: "Empires",
349   identifier: "empires"
350 };
351
352 exports.Game = Empires;