]> git.cworth.org Git - empires-server/blob - empires.js
choose-nickname: Make this page parameterizable
[empires-server] / empires.js
1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
4 const path = require("path");
5 const nunjucks = require("nunjucks");
6
7 const app = express();
8 app.use(cors());
9 app.use(body_parser.urlencoded({ extended: false }));
10 app.use(body_parser.json());
11
12 nunjucks.configure("templates", {
13   autoescape: true,
14   express: app
15 });
16
17 const GameState = {
18   JOIN:    1,
19   REVEAL:  2,
20   CAPTURE: 3,
21   properties: {
22     1: {name: "join"},
23     2: {name: "reveal"},
24     3: {name: "capture"}
25   }
26 };
27
28 /**
29  * Shuffles array in place.
30  * @param {Array} a items An array containing the items.
31  */
32 function shuffle(a) {
33   if (a === undefined)
34     return;
35
36   var j, x, i;
37   for (i = a.length - 1; i > 0; i--) {
38     j = Math.floor(Math.random() * (i + 1));
39     x = a[i];
40     a[i] = a[j];
41     a[j] = x;
42   }
43 }
44
45 class Game {
46   constructor() {
47     this._spectators = [];
48     this.next_spectator_id = 1;
49     this._players = [];
50     this.next_player_id = 1;
51     this.characters_to_reveal = null;
52     this.clients = [];
53     this.next_client_id = 1;
54     this.state = GameState.JOIN;
55
56     /* Send a comment to every connected client every 15 seconds. */
57     setInterval(() => {this.broadcast_string(":");}, 15000);
58   }
59
60   add_spectator(name, session_id) {
61     /* Don't add another spectator that matches an existing session. */
62     const existing = this._spectators.findIndex(
63       spectator => spectator.session_id === session_id);
64     if (existing >= 0)
65       return existing.id;
66
67     const new_spectator = {id: this.next_spectator_id,
68                            name: name,
69                            session_id: session_id
70                           };
71     this._spectators.push(new_spectator);
72     this.next_spectator_id++;
73     this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
74
75     return new_spectator.id;
76   }
77
78   remove_spectator(id) {
79     const index = this._spectators.findIndex(spectator => spectator.id === id);
80     this._spectators.splice(index, 1);
81
82     this.broadcast_event("spectator-leave", `{"id": ${id}}`);
83   }
84
85   add_player(name, character) {
86     const new_player = {id: this.next_player_id,
87                        name: name,
88                        character: character,
89                        captures: [],
90                        };
91     this._players.push(new_player);
92     this.next_player_id++;
93     /* The syntax here is using an anonymous function to create a new
94       object from new_player with just the subset of fields that we
95       want. */
96     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
97     this.broadcast_event("player-join", player_data);
98   }
99
100   remove_player(id) {
101     const index = this._players.findIndex(player => player.id === id);
102     this._players.splice(index, 1);
103
104     this.broadcast_event("player-leave", `{"id": ${id}}`);
105   }
106
107   reset() {
108     this._players = [];
109     this.characters_to_reveal = null;
110     this.next_player_id = 1;
111
112     this.change_state(GameState.JOIN);
113
114     this.broadcast_event("spectators", "{}");
115     this.broadcast_event("players", "{}");
116   }
117
118   reveal_next() {
119     /* Don't try to reveal anything if we aren't in the reveal state. */
120     if (this.state != GameState.REVEAL) {
121       clearInterval(this.reveal_interval);
122       return;
123     }
124
125     if (this.reveal_index >= this.characters_to_reveal.length) {
126       clearInterval(this.reveal_interval);
127       this.broadcast_event("character-reveal", '{"character":""}');
128       return;
129     }
130     const character = this.characters_to_reveal[this.reveal_index];
131     this.reveal_index++;
132     const character_data = JSON.stringify({"character":character});
133     this.broadcast_event("character-reveal", character_data);
134   }
135
136   reveal() {
137     this.change_state(GameState.REVEAL);
138
139     if (this.characters_to_reveal === null) {
140       this.characters_to_reveal = [];
141       this.characters_to_reveal = this._players.reduce((characters, player) => {
142         characters.push(player.character);
143         return characters;
144       }, []);
145       shuffle(this.characters_to_reveal);
146     }
147
148     this.reveal_index = 0;
149
150     this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
151   }
152
153   start() {
154     this.change_state(GameState.CAPTURE);
155   }
156
157   capture(captor_id, captee_id) {
158     /* TODO: Fix to fail on already-captured players (or to move the
159      * captured player from an old captor to a new—need to clarify in
160      * the API specification which we want here. */
161     let captor = this._players.find(player => player.id === captor_id);
162     captor.captures.push(captee_id);
163
164     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
165   }
166
167   liberate(captee_id) {
168     let captor = this._players.find(player => player.captures.includes(captee_id));
169     captor.captures.splice(captor.captures.indexOf(captee_id), 1);
170   }
171
172   restart() {
173     for (const player of this._players) {
174       player.captures = [];
175     }
176   }
177
178   get characters() {
179     return this._players.map(player => player.character);
180   }
181
182   get empires() {
183     return this._players.map(player => ({id: player.id, captures: player.captures}));
184   }
185
186   get spectators() {
187     /* We return only "id" and "name" here (specifically not session_id!). */
188     return this._spectators.map(spectator => ({
189       id: spectator.id,
190       name: spectator.name
191     }));
192   }
193
194   get players() {
195     return this._players.map(player => ({id: player.id, name: player.name }));
196   }
197
198   add_client(response) {
199     const id = this.next_client_id;
200     this.clients.push({id: id,
201                        response: response});
202     this.next_client_id++;
203
204     return id;
205   }
206
207   remove_client(id) {
208     this.clients = this.clients.filter(client => client.id !== id);
209   }
210
211   /* Send a string to all clients */
212   broadcast_string(str) {
213     this.clients.forEach(client => client.response.write(str + '\n'));
214   }
215
216   /* Send an event to all clients.
217    *
218    * An event has both a declared type and a separate data block.
219    * It also ends with two newlines (to mark the end of the event).
220    */
221   broadcast_event(type, data) {
222     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
223   }
224
225   game_state_event_data(old_state, new_state) {
226     var old_state_name;
227     if (old_state)
228       old_state_name = GameState.properties[old_state].name;
229     else
230       old_state_name = "none";
231     const new_state_name = GameState.properties[new_state].name;
232
233     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
234   }
235
236   /* Inform clients about a state change. */
237   broadcast_state_change() {
238     const event_data = this.game_state_event_data(this.old_state, this.state);
239     this.broadcast_event("game-state", event_data);
240   }
241
242   /* Change game state and broadcast the change to all clients. */
243   change_state(state) {
244     /* Do nothing if there is no actual change happening. */
245     if (state === this.state)
246       return;
247
248     this.old_state = this.state;
249     this.state = state;
250
251     this.broadcast_state_change();
252   }
253 }
254
255 function handle_events(request, response) {
256   const game = request.game;
257   /* These headers will keep the connection open so we can stream events. */
258   const headers = {
259     "Content-type": "text/event-stream",
260     "Connection": "keep-alive",
261     "Cache-Control": "no-cache"
262   };
263   response.writeHead(200, headers);
264
265   /* Now that a client has connected, first we need to stream all of
266    * the existing spectators and players (if any). */
267   if (game._spectators.length > 0) {
268     const spectators_json = JSON.stringify(game.spectators);
269     const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
270     response.write(spectators_data);
271   }
272
273   if (game._players.length > 0) {
274     const players_json = JSON.stringify(game.players);
275     const players_data = `event: players\ndata: ${players_json}\n\n`;
276     response.write(players_data);
277   }
278
279   /* And we need to inform the client of the current game state.
280    *
281    * In fact, we need to cycle through each state transition from the
282    * beginning so the client can see each.
283    */
284   var old_state = null;
285   for (var state = GameState.JOIN; state <= game.state; state++) {
286     var event_data = game.game_state_event_data(old_state, state);
287     response.write("event: game-state\n" + "data: " + event_data + "\n\n");
288     old_state = state;
289   }
290
291   /* Add this new client to our list of clients. */
292   const id = game.add_client(response);
293
294   /* And queue up cleanup to be triggered on client close. */
295   request.on('close', () => {
296     game.remove_client(id);
297   });
298 }
299
300 app.get('/', (request, response) => {
301   if (! request.session.nickname)
302     response.render('choose-nickname.html', { game_name: "Empires" });
303   else
304     response.render('empires-game.html');
305 });
306
307 app.post('/spectator', (request, response) => {
308   const game = request.game;
309   var name = request.session.nickname;
310
311   /* If the request includes a name, that overrides the session nickname. */
312   if (request.body.name)
313     name = request.body.name;
314
315   const id = game.add_spectator(name, request.session.id);
316   response.send(JSON.stringify(id));
317 });
318
319 app.delete('/spectator/:id', (request, response) => {
320   const game = request.game;
321   game.remove_spectator(parseInt(request.params.id));
322   response.send();
323 });
324
325 app.post('/register', (request, response) => {
326   const game = request.game;
327   var name = request.session.nickname;;
328
329   /* If the request includes a name, that overrides the session nickname. */
330   if (request.body.name)
331     name = request.body.name;
332
333   game.add_player(name, request.body.character);
334   response.send();
335 });
336
337 app.post('/deregister/:id', (request, response) => {
338   const game = request.game;
339   game.remove_player(parseInt(request.params.id));
340   response.send();
341 });
342
343 app.post('/reveal', (request, response) => {
344   const game = request.game;
345   game.reveal();
346   response.send();
347 });
348
349 app.post('/start', (request, response) => {
350   const game = request.game;
351   game.start();
352   response.send();
353 });
354
355 app.post('/reset', (request, response) => {
356   const game = request.game;
357   game.reset();
358   response.send();
359 });
360
361 app.post('/capture/:captor/:captee', (request, response) => {
362   const game = request.game;
363   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
364   response.send();
365 });
366
367 app.post('/liberate/:id', (request, response) => {
368   const game = request.game;
369   game.liberate(parseInt(request.params.id));
370   response.send();
371 });
372
373 app.post('/restart', (request, response) => {
374   const game = request.game;
375   game.restart(parseInt(request.params.id));
376     response.send();
377 });
378
379 app.get('/characters', (request, response) => {
380   const game = request.game;
381   response.send(game.characters);
382 });
383
384 app.get('/empires', (request, response) => {
385   const game = request.game;
386   response.send(game.empires);
387 });
388
389 app.get('/spectators', (request, response) => {
390   const game = request.game;
391   response.send(game.spectators);
392 });
393
394 app.get('/players', (request, response) => {
395   const game = request.game;
396   response.send(game.players);
397 });
398
399 app.get('/events', handle_events);
400
401 exports.app = app;
402 exports.Game = Game;