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));
48 this.characters_to_reveal = null;
49 this.next_player_id = 1;
51 this.next_client_id = 1;
52 this.state = GameState.JOIN;
54 /* Send a comment to every connected client every 15 seconds. */
55 setInterval(() => {this.broadcast_string(":");}, 15000);
58 add_player(name, character) {
59 const new_player = {id: this.next_player_id,
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
69 const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
70 this.broadcast_event("player-join", player_data);
74 const index = this._players.findIndex(player => player.id === id);
75 this._players.splice(index, 1);
77 this.broadcast_event("player-leave", `{"id": ${id}}`);
82 this.characters_to_reveal = null;
83 this.next_player_id = 1;
85 this.change_state(GameState.JOIN);
87 this.broadcast_event("players", "{}");
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);
97 if (this.reveal_index >= this.characters_to_reveal.length) {
98 clearInterval(this.reveal_interval);
99 this.broadcast_event("character-reveal", '{"character":""}');
102 const character = this.characters_to_reveal[this.reveal_index];
104 const character_data = JSON.stringify({"character":character});
105 this.broadcast_event("character-reveal", character_data);
109 this.change_state(GameState.REVEAL);
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);
117 shuffle(this.characters_to_reveal);
120 this.reveal_index = 0;
122 this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
126 this.change_state(GameState.CAPTURE);
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);
136 this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
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);
145 for (const player of this._players) {
146 player.captures = [];
151 return this._players.map(player => player.character);
155 return this._players.map(player => ({id: player.id, captures: player.captures}));
159 return this._players.map(player => ({id: player.id, name: player.name }));
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++;
172 this.clients = this.clients.filter(client => client.id !== id);
175 /* Send a string to all clients */
176 broadcast_string(str) {
177 this.clients.forEach(client => client.response.write(str + '\n'));
180 /* Send an event to all clients.
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).
185 broadcast_event(type, data) {
186 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
189 game_state_event_data(old_state, new_state) {
192 old_state_name = GameState.properties[old_state].name;
194 old_state_name = "none";
195 const new_state_name = GameState.properties[new_state].name;
197 return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
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);
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)
212 this.old_state = this.state;
215 this.broadcast_state_change();
219 function handle_events(request, response) {
220 const game = request.game;
221 /* These headers will keep the connection open so we can stream events. */
223 "Content-type": "text/event-stream",
224 "Connection": "keep-alive",
225 "Cache-Control": "no-cache"
227 response.writeHead(200, headers);
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);
237 /* And we need to inform the client of the current game state.
239 * In fact, we need to cycle through each state transition from the
240 * beginning so the client can see each.
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");
249 /* Add this new client to our list of clients. */
250 const id = game.add_client(response);
252 /* And queue up cleanup to be triggered on client close. */
253 request.on('close', () => {
254 game.remove_client(id);
258 app.get('/', (request, response) => {
259 if (! request.session.nickname)
260 response.render('choose-nickname.html');
262 response.sendFile(path.join(__dirname, './game.html'));
265 app.post('/register', (request, response) => {
266 const game = request.game;
267 game.add_player(request.body.name, request.body.character);
271 app.post('/deregister/:id', (request, response) => {
272 const game = request.game;
273 game.remove_player(parseInt(request.params.id));
277 app.post('/reveal', (request, response) => {
278 const game = request.game;
283 app.post('/start', (request, response) => {
284 const game = request.game;
289 app.post('/reset', (request, response) => {
290 const game = request.game;
295 app.post('/capture/:captor/:captee', (request, response) => {
296 const game = request.game;
297 game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
301 app.post('/liberate/:id', (request, response) => {
302 const game = request.game;
303 game.liberate(parseInt(request.params.id));
307 app.post('/restart', (request, response) => {
308 const game = request.game;
309 game.restart(parseInt(request.params.id));
313 app.get('/characters', (request, response) => {
314 const game = request.game;
315 response.send(game.characters);
318 app.get('/empires', (request, response) => {
319 const game = request.game;
320 response.send(game.empires);
323 app.get('/players', (request, response) => {
324 const game = request.game;
325 response.send(game.players);
328 app.get('/events', handle_events);