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");
9 app.use(body_parser.urlencoded({ extended: false }));
10 app.use(body_parser.json());
12 nunjucks.configure("templates", {
29 * Shuffles array in place.
30 * @param {Array} a items An array containing the items.
37 for (i = a.length - 1; i > 0; i--) {
38 j = Math.floor(Math.random() * (i + 1));
47 this._spectators = [];
48 this.next_spectator_id = 1;
50 this.next_player_id = 1;
51 this.characters_to_reveal = null;
53 this.next_client_id = 1;
54 this.state = GameState.JOIN;
56 /* Send a comment to every connected client every 15 seconds. */
57 setInterval(() => {this.broadcast_string(":");}, 15000);
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);
67 const new_spectator = {id: this.next_spectator_id,
69 session_id: session_id
71 this._spectators.push(new_spectator);
72 this.next_spectator_id++;
73 this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
75 return new_spectator.id;
78 remove_spectator(id) {
79 const index = this._spectators.findIndex(spectator => spectator.id === id);
80 this._spectators.splice(index, 1);
82 this.broadcast_event("spectator-leave", `{"id": ${id}}`);
85 add_player(name, character) {
86 const new_player = {id: this.next_player_id,
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
96 const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
97 this.broadcast_event("player-join", player_data);
101 const index = this._players.findIndex(player => player.id === id);
102 this._players.splice(index, 1);
104 this.broadcast_event("player-leave", `{"id": ${id}}`);
109 this.characters_to_reveal = null;
110 this.next_player_id = 1;
112 this.change_state(GameState.JOIN);
114 this.broadcast_event("spectators", "{}");
115 this.broadcast_event("players", "{}");
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);
125 if (this.reveal_index >= this.characters_to_reveal.length) {
126 clearInterval(this.reveal_interval);
127 this.broadcast_event("character-reveal", '{"character":""}');
130 const character = this.characters_to_reveal[this.reveal_index];
132 const character_data = JSON.stringify({"character":character});
133 this.broadcast_event("character-reveal", character_data);
137 this.change_state(GameState.REVEAL);
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);
145 shuffle(this.characters_to_reveal);
148 this.reveal_index = 0;
150 this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
154 this.change_state(GameState.CAPTURE);
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);
164 this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
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);
173 for (const player of this._players) {
174 player.captures = [];
179 return this._players.map(player => player.character);
183 return this._players.map(player => ({id: player.id, captures: player.captures}));
187 /* We return only "id" and "name" here (specifically not session_id!). */
188 return this._spectators.map(spectator => ({
195 return this._players.map(player => ({id: player.id, name: player.name }));
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++;
208 this.clients = this.clients.filter(client => client.id !== id);
211 /* Send a string to all clients */
212 broadcast_string(str) {
213 this.clients.forEach(client => client.response.write(str + '\n'));
216 /* Send an event to all clients.
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).
221 broadcast_event(type, data) {
222 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
225 game_state_event_data(old_state, new_state) {
228 old_state_name = GameState.properties[old_state].name;
230 old_state_name = "none";
231 const new_state_name = GameState.properties[new_state].name;
233 return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
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);
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)
248 this.old_state = this.state;
251 this.broadcast_state_change();
255 function handle_events(request, response) {
256 const game = request.game;
257 /* These headers will keep the connection open so we can stream events. */
259 "Content-type": "text/event-stream",
260 "Connection": "keep-alive",
261 "Cache-Control": "no-cache"
263 response.writeHead(200, headers);
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);
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);
279 /* And we need to inform the client of the current game state.
281 * In fact, we need to cycle through each state transition from the
282 * beginning so the client can see each.
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");
291 /* Add this new client to our list of clients. */
292 const id = game.add_client(response);
294 /* And queue up cleanup to be triggered on client close. */
295 request.on('close', () => {
296 game.remove_client(id);
300 app.get('/', (request, response) => {
301 if (! request.session.nickname)
302 response.render('choose-nickname.html', { game_name: "Empires" });
304 response.render('empires-game.html');
307 app.post('/spectator', (request, response) => {
308 const game = request.game;
309 var name = request.session.nickname;
311 /* If the request includes a name, that overrides the session nickname. */
312 if (request.body.name)
313 name = request.body.name;
315 const id = game.add_spectator(name, request.session.id);
316 response.send(JSON.stringify(id));
319 app.delete('/spectator/:id', (request, response) => {
320 const game = request.game;
321 game.remove_spectator(parseInt(request.params.id));
325 app.post('/register', (request, response) => {
326 const game = request.game;
327 var name = request.session.nickname;;
329 /* If the request includes a name, that overrides the session nickname. */
330 if (request.body.name)
331 name = request.body.name;
333 game.add_player(name, request.body.character);
337 app.post('/deregister/:id', (request, response) => {
338 const game = request.game;
339 game.remove_player(parseInt(request.params.id));
343 app.post('/reveal', (request, response) => {
344 const game = request.game;
349 app.post('/start', (request, response) => {
350 const game = request.game;
355 app.post('/reset', (request, response) => {
356 const game = request.game;
361 app.post('/capture/:captor/:captee', (request, response) => {
362 const game = request.game;
363 game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
367 app.post('/liberate/:id', (request, response) => {
368 const game = request.game;
369 game.liberate(parseInt(request.params.id));
373 app.post('/restart', (request, response) => {
374 const game = request.game;
375 game.restart(parseInt(request.params.id));
379 app.get('/characters', (request, response) => {
380 const game = request.game;
381 response.send(game.characters);
384 app.get('/empires', (request, response) => {
385 const game = request.game;
386 response.send(game.empires);
389 app.get('/spectators', (request, response) => {
390 const game = request.game;
391 response.send(game.spectators);
394 app.get('/players', (request, response) => {
395 const game = request.game;
396 response.send(game.players);
399 app.get('/events', handle_events);