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