1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
20 * Shuffles array in place.
21 * @param {Array} a items An array containing the items.
28 for (i = a.length - 1; i > 0; i--) {
29 j = Math.floor(Math.random() * (i + 1));
39 this.characters_to_reveal = null;
40 this.next_player_id = 1;
42 this.next_client_id = 1;
43 this.state = GameState.JOIN;
45 /* Send a comment to every connected client every 15 seconds. */
46 setInterval(() => {this.broadcast_string(":");}, 15000);
49 add_player(name, character) {
50 const new_player = {id: this.next_player_id,
55 this._players.push(new_player);
56 this.next_player_id++;
57 /* The syntax here is using an anonymous function to create a new
58 object from new_player with just the subset of fields that we
60 const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
61 this.broadcast_event("player-join", player_data);
65 const index = this._players.findIndex(player => player.id === id);
66 this._players.splice(index, 1);
68 this.broadcast_event("player-leave", `{"id": ${id}}`);
71 remove_all_players() {
73 this.next_player_id = 1;
77 if (this.reveal_index >= this.characters_to_reveal.length) {
78 clearInterval(this.reveal_interval);
79 this.broadcast_event("character-reveal", '{"character":""}');
82 const character = this.characters_to_reveal[this.reveal_index];
84 const character_data = JSON.stringify({"character":character});
85 this.broadcast_event("character-reveal", character_data);
89 this.change_state(GameState.REVEAL);
91 if (this.characters_to_reveal === null) {
92 this.characters_to_reveal = [];
93 this.characters_to_reveal = this._players.reduce((characters, player) => {
94 characters.push(player.character);
97 shuffle(this.characters_to_reveal);
100 this.reveal_index = 0;
102 this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
106 this.change_state(GameState.CAPTURE);
109 capture(captor_id, captee_id) {
110 /* TODO: Fix to fail on already-captured players (or to move the
111 * captured player from an old captor to a new—need to clarify in
112 * the API specification which we want here. */
113 let captor = this._players.find(player => player.id === captor_id);
114 captor.captures.push(captee_id);
116 this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
119 liberate(captee_id) {
120 let captor = this._players.find(player => player.captures.includes(captee_id));
121 captor.captures.splice(captor.captures.indexOf(captee_id), 1);
125 for (const player of this._players) {
126 player.captures = [];
131 return this._players.map(player => player.character);
135 return this._players.map(player => ({id: player.id, captures: player.captures}));
139 return this._players.map(player => ({id: player.id, name: player.name }));
142 add_client(response) {
143 const id = this.next_client_id;
144 this.clients.push({id: id,
145 response: response});
146 this.next_client_id++;
152 this.clients = this.clients.filter(client => client.id !== id);
155 /* Send a string to all clients */
156 broadcast_string(str) {
157 this.clients.forEach(client => client.response.write(str + '\n'));
160 /* Send an event to all clients.
162 * An event has both a declared type and a separate data block.
163 * It also ends with two newlines (to mark the end of the event).
165 broadcast_event(type, data) {
166 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
169 game_state_event_data() {
172 old_state_name = GameState.properties[this.old_state].name;
174 old_state_name = "none";
175 const new_state_name = GameState.properties[this.state].name;
177 return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
180 /* Inform clients about a state change. */
181 broadcast_state_change() {
182 this.broadcast_event("game-state", this.game_state_event_data());
185 /* Change game state and broadcast the change to all clients. */
186 change_state(state) {
187 /* Do nothing if there is no actual change happening. */
188 if (state === this.state)
191 this.old_state = this.state;
194 this.broadcast_state_change();
198 const game = new Game();
200 app.use(body_parser.urlencoded({ extended: false }));
201 app.use(body_parser.json());
203 function handle_events(request, response) {
204 /* These headers will keep the connection open so we can stream events. */
206 "Content-type": "text/event-stream",
207 "Connection": "keep-alive",
208 "Cache-Control": "no-cache"
210 response.writeHead(200, headers);
212 /* Now that a client has connected, first we need to stream all of
213 * the existing players (if any). */
214 if (game._players.length > 0) {
215 const players_json = JSON.stringify(game.players);
216 const players_data = `event: players\ndata: ${players_json}\n\n`;
217 response.write(players_data);
220 /* And we need to inform the client of the current game state. */
221 response.write("event: game-state\n" + "data: " + game.game_state_event_data() + "\n\n");
223 /* Add this new client to our list of clients. */
224 const id = game.add_client(response);
226 /* And queue up cleanup to be triggered on client close. */
227 request.on('close', () => {
228 game.remove_client(id);
232 app.get('/', (request, response) => {
233 response.send('Hello World!');
236 app.post('/register', (request, response) => {
237 game.add_player(request.body.name, request.body.character);
241 app.post('/deregister/:id', (request, response) => {
242 game.remove_player(parseInt(request.params.id));
246 app.post('/reveal', (request, response) => {
251 app.post('/start', (request, response) => {
256 app.post('/reset', (request, response) => {
257 game.remove_all_players();
261 app.post('/capture/:captor/:captee', (request, response) => {
262 game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
266 app.post('/liberate/:id', (request, response) => {
267 game.liberate(parseInt(request.params.id));
271 app.post('/restart', (request, response) => {
272 game.restart(parseInt(request.params.id));
276 app.get('/characters', (request, response) => {
277 response.send(game.characters);
280 app.get('/empires', (request, response) => {
281 response.send(game.empires);
284 app.get('/players', (request, response) => {
285 response.send(game.players);
288 app.get('/events', handle_events);
290 app.listen(3000, function () {
291 console.log('Empires server listening on localhost:3000');