]> git.cworth.org Git - empires-server/blob - empires.js
Use an express Router for each of the game-engine-specific sub-apps
[empires-server] / empires.js
1 const express = require("express");
2
3 const app = express.Router();
4
5 const GameState = {
6   JOIN:    1,
7   REVEAL:  2,
8   CAPTURE: 3,
9   properties: {
10     1: {name: "join"},
11     2: {name: "reveal"},
12     3: {name: "capture"}
13   }
14 };
15
16 /**
17  * Shuffles array in place.
18  * @param {Array} a items An array containing the items.
19  */
20 function shuffle(a) {
21   if (a === undefined)
22     return;
23
24   var j, x, i;
25   for (i = a.length - 1; i > 0; i--) {
26     j = Math.floor(Math.random() * (i + 1));
27     x = a[i];
28     a[i] = a[j];
29     a[j] = x;
30   }
31 }
32
33 class Game {
34   constructor() {
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.clients = [];
41     this.next_client_id = 1;
42     this.state = GameState.JOIN;
43
44     /* Send a comment to every connected client every 15 seconds. */
45     setInterval(() => {this.broadcast_string(":");}, 15000);
46   }
47
48   add_spectator(name, session_id) {
49     /* Don't add another spectator that matches an existing session. */
50     const existing = this._spectators.findIndex(
51       spectator => spectator.session_id === session_id);
52     if (existing >= 0)
53       return existing.id;
54
55     const new_spectator = {id: this.next_spectator_id,
56                            name: name,
57                            session_id: session_id
58                           };
59     this._spectators.push(new_spectator);
60     this.next_spectator_id++;
61     this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
62
63     return new_spectator.id;
64   }
65
66   remove_spectator(id) {
67     const index = this._spectators.findIndex(spectator => spectator.id === id);
68     this._spectators.splice(index, 1);
69
70     this.broadcast_event("spectator-leave", `{"id": ${id}}`);
71   }
72
73   add_player(name, character) {
74     const new_player = {id: this.next_player_id,
75                        name: name,
76                        character: character,
77                        captures: [],
78                        };
79     this._players.push(new_player);
80     this.next_player_id++;
81     /* The syntax here is using an anonymous function to create a new
82       object from new_player with just the subset of fields that we
83       want. */
84     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
85     this.broadcast_event("player-join", player_data);
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_state(GameState.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 state. */
108     if (this.state != GameState.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_state(GameState.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_state(GameState.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   add_client(response) {
187     const id = this.next_client_id;
188     this.clients.push({id: id,
189                        response: response});
190     this.next_client_id++;
191
192     return id;
193   }
194
195   remove_client(id) {
196     this.clients = this.clients.filter(client => client.id !== id);
197   }
198
199   /* Send a string to all clients */
200   broadcast_string(str) {
201     this.clients.forEach(client => client.response.write(str + '\n'));
202   }
203
204   /* Send an event to all clients.
205    *
206    * An event has both a declared type and a separate data block.
207    * It also ends with two newlines (to mark the end of the event).
208    */
209   broadcast_event(type, data) {
210     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
211   }
212
213   game_state_event_data(old_state, new_state) {
214     var old_state_name;
215     if (old_state)
216       old_state_name = GameState.properties[old_state].name;
217     else
218       old_state_name = "none";
219     const new_state_name = GameState.properties[new_state].name;
220
221     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
222   }
223
224   /* Inform clients about a state change. */
225   broadcast_state_change() {
226     const event_data = this.game_state_event_data(this.old_state, this.state);
227     this.broadcast_event("game-state", event_data);
228   }
229
230   /* Change game state and broadcast the change to all clients. */
231   change_state(state) {
232     /* Do nothing if there is no actual change happening. */
233     if (state === this.state)
234       return;
235
236     this.old_state = this.state;
237     this.state = state;
238
239     this.broadcast_state_change();
240   }
241 }
242
243 function handle_events(request, response) {
244   const game = request.game;
245   /* These headers will keep the connection open so we can stream events. */
246   const headers = {
247     "Content-type": "text/event-stream",
248     "Connection": "keep-alive",
249     "Cache-Control": "no-cache"
250   };
251   response.writeHead(200, headers);
252
253   /* Now that a client has connected, first we need to stream all of
254    * the existing spectators and players (if any). */
255   if (game._spectators.length > 0) {
256     const spectators_json = JSON.stringify(game.spectators);
257     const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
258     response.write(spectators_data);
259   }
260
261   if (game._players.length > 0) {
262     const players_json = JSON.stringify(game.players);
263     const players_data = `event: players\ndata: ${players_json}\n\n`;
264     response.write(players_data);
265   }
266
267   /* And we need to inform the client of the current game state.
268    *
269    * In fact, we need to cycle through each state transition from the
270    * beginning so the client can see each.
271    */
272   var old_state = null;
273   for (var state = GameState.JOIN; state <= game.state; state++) {
274     var event_data = game.game_state_event_data(old_state, state);
275     response.write("event: game-state\n" + "data: " + event_data + "\n\n");
276     old_state = state;
277   }
278
279   /* Add this new client to our list of clients. */
280   const id = game.add_client(response);
281
282   /* And queue up cleanup to be triggered on client close. */
283   request.on('close', () => {
284     game.remove_client(id);
285   });
286 }
287
288 app.get('/', (request, response) => {
289   if (! request.session.nickname)
290     response.render('choose-nickname.html', { game_name: "Empires" });
291   else
292     response.render('empires-game.html');
293 });
294
295 app.post('/spectator', (request, response) => {
296   const game = request.game;
297   var name = request.session.nickname;
298
299   /* If the request includes a name, that overrides the session nickname. */
300   if (request.body.name)
301     name = request.body.name;
302
303   const id = game.add_spectator(name, request.session.id);
304   response.send(JSON.stringify(id));
305 });
306
307 app.delete('/spectator/:id', (request, response) => {
308   const game = request.game;
309   game.remove_spectator(parseInt(request.params.id));
310   response.send();
311 });
312
313 app.post('/register', (request, response) => {
314   const game = request.game;
315   var name = request.session.nickname;;
316
317   /* If the request includes a name, that overrides the session nickname. */
318   if (request.body.name)
319     name = request.body.name;
320
321   game.add_player(name, request.body.character);
322   response.send();
323 });
324
325 app.post('/deregister/:id', (request, response) => {
326   const game = request.game;
327   game.remove_player(parseInt(request.params.id));
328   response.send();
329 });
330
331 app.post('/reveal', (request, response) => {
332   const game = request.game;
333   game.reveal();
334   response.send();
335 });
336
337 app.post('/start', (request, response) => {
338   const game = request.game;
339   game.start();
340   response.send();
341 });
342
343 app.post('/reset', (request, response) => {
344   const game = request.game;
345   game.reset();
346   response.send();
347 });
348
349 app.post('/capture/:captor/:captee', (request, response) => {
350   const game = request.game;
351   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
352   response.send();
353 });
354
355 app.post('/liberate/:id', (request, response) => {
356   const game = request.game;
357   game.liberate(parseInt(request.params.id));
358   response.send();
359 });
360
361 app.post('/restart', (request, response) => {
362   const game = request.game;
363   game.restart(parseInt(request.params.id));
364     response.send();
365 });
366
367 app.get('/characters', (request, response) => {
368   const game = request.game;
369   response.send(game.characters);
370 });
371
372 app.get('/empires', (request, response) => {
373   const game = request.game;
374   response.send(game.empires);
375 });
376
377 app.get('/spectators', (request, response) => {
378   const game = request.game;
379   response.send(game.spectators);
380 });
381
382 app.get('/players', (request, response) => {
383   const game = request.game;
384   response.send(game.players);
385 });
386
387 app.get('/events', handle_events);
388
389 exports.app = app;
390 exports.name = "empires";
391 exports.Game = Game;