1 const express = require("express");
3 const app = express.Router();
17 * Shuffles array in place.
18 * @param {Array} a items An array containing the items.
25 for (i = a.length - 1; i > 0; i--) {
26 j = Math.floor(Math.random() * (i + 1));
35 this._spectators = [];
36 this.next_spectator_id = 1;
38 this.next_player_id = 1;
39 this.characters_to_reveal = null;
41 this.next_client_id = 1;
42 this.state = GameState.JOIN;
44 /* Send a comment to every connected client every 15 seconds. */
45 setInterval(() => {this.broadcast_string(":");}, 15000);
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);
55 const new_spectator = {id: this.next_spectator_id,
57 session_id: session_id
59 this._spectators.push(new_spectator);
60 this.next_spectator_id++;
61 this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
63 return new_spectator.id;
66 remove_spectator(id) {
67 const index = this._spectators.findIndex(spectator => spectator.id === id);
68 this._spectators.splice(index, 1);
70 this.broadcast_event("spectator-leave", `{"id": ${id}}`);
73 add_player(name, character) {
74 const new_player = {id: this.next_player_id,
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
84 const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
85 this.broadcast_event("player-join", player_data);
89 const index = this._players.findIndex(player => player.id === id);
90 this._players.splice(index, 1);
92 this.broadcast_event("player-leave", `{"id": ${id}}`);
97 this.characters_to_reveal = null;
98 this.next_player_id = 1;
100 this.change_state(GameState.JOIN);
102 this.broadcast_event("spectators", "{}");
103 this.broadcast_event("players", "{}");
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);
113 if (this.reveal_index >= this.characters_to_reveal.length) {
114 clearInterval(this.reveal_interval);
115 this.broadcast_event("character-reveal", '{"character":""}');
118 const character = this.characters_to_reveal[this.reveal_index];
120 const character_data = JSON.stringify({"character":character});
121 this.broadcast_event("character-reveal", character_data);
125 this.change_state(GameState.REVEAL);
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);
133 shuffle(this.characters_to_reveal);
136 this.reveal_index = 0;
138 this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
142 this.change_state(GameState.CAPTURE);
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);
152 this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
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);
161 for (const player of this._players) {
162 player.captures = [];
167 return this._players.map(player => player.character);
171 return this._players.map(player => ({id: player.id, captures: player.captures}));
175 /* We return only "id" and "name" here (specifically not session_id!). */
176 return this._spectators.map(spectator => ({
183 return this._players.map(player => ({id: player.id, name: player.name }));
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++;
196 this.clients = this.clients.filter(client => client.id !== id);
199 /* Send a string to all clients */
200 broadcast_string(str) {
201 this.clients.forEach(client => client.response.write(str + '\n'));
204 /* Send an event to all clients.
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).
209 broadcast_event(type, data) {
210 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
213 game_state_event_data(old_state, new_state) {
216 old_state_name = GameState.properties[old_state].name;
218 old_state_name = "none";
219 const new_state_name = GameState.properties[new_state].name;
221 return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
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);
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)
236 this.old_state = this.state;
239 this.broadcast_state_change();
243 function handle_events(request, response) {
244 const game = request.game;
245 /* These headers will keep the connection open so we can stream events. */
247 "Content-type": "text/event-stream",
248 "Connection": "keep-alive",
249 "Cache-Control": "no-cache"
251 response.writeHead(200, headers);
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);
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);
267 /* And we need to inform the client of the current game state.
269 * In fact, we need to cycle through each state transition from the
270 * beginning so the client can see each.
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");
279 /* Add this new client to our list of clients. */
280 const id = game.add_client(response);
282 /* And queue up cleanup to be triggered on client close. */
283 request.on('close', () => {
284 game.remove_client(id);
288 app.get('/', (request, response) => {
289 if (! request.session.nickname)
290 response.render('choose-nickname.html', { game_name: "Empires" });
292 response.render('empires-game.html');
295 app.post('/spectator', (request, response) => {
296 const game = request.game;
297 var name = request.session.nickname;
299 /* If the request includes a name, that overrides the session nickname. */
300 if (request.body.name)
301 name = request.body.name;
303 const id = game.add_spectator(name, request.session.id);
304 response.send(JSON.stringify(id));
307 app.delete('/spectator/:id', (request, response) => {
308 const game = request.game;
309 game.remove_spectator(parseInt(request.params.id));
313 app.post('/register', (request, response) => {
314 const game = request.game;
315 var name = request.session.nickname;;
317 /* If the request includes a name, that overrides the session nickname. */
318 if (request.body.name)
319 name = request.body.name;
321 game.add_player(name, request.body.character);
325 app.post('/deregister/:id', (request, response) => {
326 const game = request.game;
327 game.remove_player(parseInt(request.params.id));
331 app.post('/reveal', (request, response) => {
332 const game = request.game;
337 app.post('/start', (request, response) => {
338 const game = request.game;
343 app.post('/reset', (request, response) => {
344 const game = request.game;
349 app.post('/capture/:captor/:captee', (request, response) => {
350 const game = request.game;
351 game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
355 app.post('/liberate/:id', (request, response) => {
356 const game = request.game;
357 game.liberate(parseInt(request.params.id));
361 app.post('/restart', (request, response) => {
362 const game = request.game;
363 game.restart(parseInt(request.params.id));
367 app.get('/characters', (request, response) => {
368 const game = request.game;
369 response.send(game.characters);
372 app.get('/empires', (request, response) => {
373 const game = request.game;
374 response.send(game.empires);
377 app.get('/spectators', (request, response) => {
378 const game = request.game;
379 response.send(game.spectators);
382 app.get('/players', (request, response) => {
383 const game = request.game;
384 response.send(game.players);
387 app.get('/events', handle_events);
390 exports.name = "empires";