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