]> git.cworth.org Git - empires-server/blob - empires.js
Move the keepalive functionality from Empires up to Game
[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   add_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   get players() {
180     return this._players.map(player => ({id: player.id, name: player.name }));
181   }
182
183   game_phase_event_data(old_phase, new_phase) {
184     var old_phase_name;
185     if (old_phase)
186       old_phase_name = GamePhase.properties[old_phase].name;
187     else
188       old_phase_name = "none";
189     const new_phase_name = GamePhase.properties[new_phase].name;
190
191     return `{"old_phase":"${old_phase_name}","new_phase":"${new_phase_name}"}`;
192   }
193
194   /* Inform clients about a phase change. */
195   broadcast_phase_change() {
196     const event_data = this.game_phase_event_data(this.old_phase, this.phase);
197     this.broadcast_event("game-phase", event_data);
198   }
199
200   /* Change game phase and broadcast the change to all clients. */
201   change_phase(phase) {
202     /* Do nothing if there is no actual change happening. */
203     if (phase === this.phase)
204       return;
205
206     this.old_phase = this.phase;
207     this.phase = phase;
208
209     this.broadcast_phase_change();
210   }
211
212   handle_events(request, response) {
213
214     super.handle_events(request, response);
215
216     /* Now that a client has connected, first we need to stream all of
217      * the existing spectators and players (if any). */
218     if (this._spectators.length > 0) {
219       const spectators_json = JSON.stringify(this.spectators);
220       const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
221       response.write(spectators_data);
222     }
223
224     if (this._players.length > 0) {
225       const players_json = JSON.stringify(this.players);
226       const players_data = `event: players\ndata: ${players_json}\n\n`;
227       response.write(players_data);
228     }
229
230     /* And we need to inform the client of the current game phase.
231      *
232      * In fact, we need to cycle through each phase transition from the
233      * beginning so the client can see each.
234      */
235     var old_phase = null;
236     for (var phase = GamePhase.JOIN; phase <= this.phase; phase++) {
237       var event_data = this.game_phase_event_data(old_phase, phase);
238       response.write("event: game-phase\n" + "data: " + event_data + "\n\n");
239       old_phase = phase;
240     }
241   }
242
243 }
244
245 Empires.router = express.Router();
246 const router = Empires.router;
247
248 router.post('/spectator', (request, response) => {
249   const game = request.game;
250   var name = request.session.nickname;
251
252   /* If the request includes a name, that overrides the session nickname. */
253   if (request.body.name)
254     name = request.body.name;
255
256   const id = game.add_spectator(name, request.session.id);
257   response.send(JSON.stringify(id));
258 });
259
260 router.delete('/spectator/:id', (request, response) => {
261   const game = request.game;
262   game.remove_spectator(parseInt(request.params.id));
263   response.send();
264 });
265
266 router.post('/register', (request, response) => {
267   const game = request.game;
268   var name = request.session.nickname;;
269
270   /* If the request includes a name, that overrides the session nickname. */
271   if (request.body.name)
272     name = request.body.name;
273
274   const player = game.add_player(name, request.body.character);
275   response.send(JSON.stringify(player.id));
276 });
277
278 router.post('/deregister/:id', (request, response) => {
279   const game = request.game;
280   game.remove_player(parseInt(request.params.id));
281   response.send();
282 });
283
284 router.post('/reveal', (request, response) => {
285   const game = request.game;
286   game.reveal();
287   response.send();
288 });
289
290 router.post('/start', (request, response) => {
291   const game = request.game;
292   game.start();
293   response.send();
294 });
295
296 router.post('/reset', (request, response) => {
297   const game = request.game;
298   game.reset();
299   response.send();
300 });
301
302 router.post('/capture/:captor/:captee', (request, response) => {
303   const game = request.game;
304   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
305   response.send();
306 });
307
308 router.post('/liberate/:id', (request, response) => {
309   const game = request.game;
310   game.liberate(parseInt(request.params.id));
311   response.send();
312 });
313
314 router.post('/restart', (request, response) => {
315   const game = request.game;
316   game.restart(parseInt(request.params.id));
317     response.send();
318 });
319
320 router.get('/characters', (request, response) => {
321   const game = request.game;
322   response.send(game.characters);
323 });
324
325 router.get('/empires', (request, response) => {
326   const game = request.game;
327   response.send(game.empires);
328 });
329
330 router.get('/spectators', (request, response) => {
331   const game = request.game;
332   response.send(game.spectators);
333 });
334
335 router.get('/players', (request, response) => {
336   const game = request.game;
337   response.send(game.players);
338 });
339
340 Empires.meta = {
341   name: "Empires",
342   identifier: "empires"
343 };
344
345 exports.Game = Empires;