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}}`);
73 this.characters_to_reveal = null;
74 this.next_player_id = 1;
76 this.change_state(GameState.JOIN);
78 this.broadcast_event("players", "{}");
82 if (this.reveal_index >= this.characters_to_reveal.length) {
83 clearInterval(this.reveal_interval);
84 this.broadcast_event("character-reveal", '{"character":""}');
87 const character = this.characters_to_reveal[this.reveal_index];
89 const character_data = JSON.stringify({"character":character});
90 this.broadcast_event("character-reveal", character_data);
94 this.change_state(GameState.REVEAL);
96 if (this.characters_to_reveal === null) {
97 this.characters_to_reveal = [];
98 this.characters_to_reveal = this._players.reduce((characters, player) => {
99 characters.push(player.character);
102 shuffle(this.characters_to_reveal);
105 this.reveal_index = 0;
107 this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
111 this.change_state(GameState.CAPTURE);
114 capture(captor_id, captee_id) {
115 /* TODO: Fix to fail on already-captured players (or to move the
116 * captured player from an old captor to a new—need to clarify in
117 * the API specification which we want here. */
118 let captor = this._players.find(player => player.id === captor_id);
119 captor.captures.push(captee_id);
121 this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
124 liberate(captee_id) {
125 let captor = this._players.find(player => player.captures.includes(captee_id));
126 captor.captures.splice(captor.captures.indexOf(captee_id), 1);
130 for (const player of this._players) {
131 player.captures = [];
136 return this._players.map(player => player.character);
140 return this._players.map(player => ({id: player.id, captures: player.captures}));
144 return this._players.map(player => ({id: player.id, name: player.name }));
147 add_client(response) {
148 const id = this.next_client_id;
149 this.clients.push({id: id,
150 response: response});
151 this.next_client_id++;
157 this.clients = this.clients.filter(client => client.id !== id);
160 /* Send a string to all clients */
161 broadcast_string(str) {
162 this.clients.forEach(client => client.response.write(str + '\n'));
165 /* Send an event to all clients.
167 * An event has both a declared type and a separate data block.
168 * It also ends with two newlines (to mark the end of the event).
170 broadcast_event(type, data) {
171 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
174 game_state_event_data(old_state, new_state) {
177 old_state_name = GameState.properties[old_state].name;
179 old_state_name = "none";
180 const new_state_name = GameState.properties[new_state].name;
182 return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
185 /* Inform clients about a state change. */
186 broadcast_state_change() {
187 const event_data = this.game_state_event_data(this.old_state, this.state);
188 this.broadcast_event("game-state", event_data);
191 /* Change game state and broadcast the change to all clients. */
192 change_state(state) {
193 /* Do nothing if there is no actual change happening. */
194 if (state === this.state)
197 this.old_state = this.state;
200 this.broadcast_state_change();
204 const game = new Game();
206 app.use(body_parser.urlencoded({ extended: false }));
207 app.use(body_parser.json());
209 function handle_events(request, response) {
210 /* These headers will keep the connection open so we can stream events. */
212 "Content-type": "text/event-stream",
213 "Connection": "keep-alive",
214 "Cache-Control": "no-cache"
216 response.writeHead(200, headers);
218 /* Now that a client has connected, first we need to stream all of
219 * the existing players (if any). */
220 if (game._players.length > 0) {
221 const players_json = JSON.stringify(game.players);
222 const players_data = `event: players\ndata: ${players_json}\n\n`;
223 response.write(players_data);
226 /* And we need to inform the client of the current game state.
228 * In fact, we need to cycle through each state transition from the
229 * beginning so the client can see each.
231 var old_state = null;
232 for (var state = GameState.JOIN; state <= game.state; state++) {
233 var event_data = game.game_state_event_data(old_state, state);
234 response.write("event: game-state\n" + "data: " + event_data + "\n\n");
238 /* Add this new client to our list of clients. */
239 const id = game.add_client(response);
241 /* And queue up cleanup to be triggered on client close. */
242 request.on('close', () => {
243 game.remove_client(id);
247 app.get('/', (request, response) => {
248 response.send('Hello World!');
251 app.post('/register', (request, response) => {
252 game.add_player(request.body.name, request.body.character);
256 app.post('/deregister/:id', (request, response) => {
257 game.remove_player(parseInt(request.params.id));
261 app.post('/reveal', (request, response) => {
266 app.post('/start', (request, response) => {
271 app.post('/reset', (request, response) => {
276 app.post('/capture/:captor/:captee', (request, response) => {
277 game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
281 app.post('/liberate/:id', (request, response) => {
282 game.liberate(parseInt(request.params.id));
286 app.post('/restart', (request, response) => {
287 game.restart(parseInt(request.params.id));
291 app.get('/characters', (request, response) => {
292 response.send(game.characters);
295 app.get('/empires', (request, response) => {
296 response.send(game.empires);
299 app.get('/players', (request, response) => {
300 response.send(game.players);
303 app.get('/events', handle_events);
305 app.listen(3000, function () {
306 console.log('Empires server listening on localhost:3000');