1 const express = require("express");
2 const Game = require("./game.js");
4 const engine_name = "empires";
6 const router = express.Router();
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));
36 class Empires extends Game {
39 this._spectators = [];
40 this.next_spectator_id = 1;
42 this.next_player_id = 1;
43 this.characters_to_reveal = null;
45 this.next_client_id = 1;
46 this.state = GameState.JOIN;
48 /* Send a comment to every connected client every 15 seconds. */
49 setInterval(() => {this.broadcast_string(":");}, 15000);
52 add_spectator(name, session_id) {
53 /* Don't add another spectator that matches an existing session. */
54 const existing = this._spectators.findIndex(
55 spectator => spectator.session_id === session_id);
59 const new_spectator = {id: this.next_spectator_id,
61 session_id: session_id
63 this._spectators.push(new_spectator);
64 this.next_spectator_id++;
65 this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
67 return new_spectator.id;
70 remove_spectator(id) {
71 const index = this._spectators.findIndex(spectator => spectator.id === id);
72 this._spectators.splice(index, 1);
74 this.broadcast_event("spectator-leave", `{"id": ${id}}`);
77 add_player(name, character) {
78 const new_player = {id: this.next_player_id,
83 this._players.push(new_player);
84 this.next_player_id++;
85 /* The syntax here is using an anonymous function to create a new
86 object from new_player with just the subset of fields that we
88 const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
89 this.broadcast_event("player-join", player_data);
93 const index = this._players.findIndex(player => player.id === id);
94 this._players.splice(index, 1);
96 this.broadcast_event("player-leave", `{"id": ${id}}`);
101 this.characters_to_reveal = null;
102 this.next_player_id = 1;
104 this.change_state(GameState.JOIN);
106 this.broadcast_event("spectators", "{}");
107 this.broadcast_event("players", "{}");
111 /* Don't try to reveal anything if we aren't in the reveal state. */
112 if (this.state != GameState.REVEAL) {
113 clearInterval(this.reveal_interval);
117 if (this.reveal_index >= this.characters_to_reveal.length) {
118 clearInterval(this.reveal_interval);
119 this.broadcast_event("character-reveal", '{"character":""}');
122 const character = this.characters_to_reveal[this.reveal_index];
124 const character_data = JSON.stringify({"character":character});
125 this.broadcast_event("character-reveal", character_data);
129 this.change_state(GameState.REVEAL);
131 if (this.characters_to_reveal === null) {
132 this.characters_to_reveal = [];
133 this.characters_to_reveal = this._players.reduce((characters, player) => {
134 characters.push(player.character);
137 shuffle(this.characters_to_reveal);
140 this.reveal_index = 0;
142 this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
146 this.change_state(GameState.CAPTURE);
149 capture(captor_id, captee_id) {
150 /* TODO: Fix to fail on already-captured players (or to move the
151 * captured player from an old captor to a new—need to clarify in
152 * the API specification which we want here. */
153 let captor = this._players.find(player => player.id === captor_id);
154 captor.captures.push(captee_id);
156 this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
159 liberate(captee_id) {
160 let captor = this._players.find(player => player.captures.includes(captee_id));
161 captor.captures.splice(captor.captures.indexOf(captee_id), 1);
165 for (const player of this._players) {
166 player.captures = [];
171 return this._players.map(player => player.character);
175 return this._players.map(player => ({id: player.id, captures: player.captures}));
179 /* We return only "id" and "name" here (specifically not session_id!). */
180 return this._spectators.map(spectator => ({
187 return this._players.map(player => ({id: player.id, name: player.name }));
190 add_client(response) {
191 const id = this.next_client_id;
192 this.clients.push({id: id,
193 response: response});
194 this.next_client_id++;
200 this.clients = this.clients.filter(client => client.id !== id);
203 /* Send a string to all clients */
204 broadcast_string(str) {
205 this.clients.forEach(client => client.response.write(str + '\n'));
208 /* Send an event to all clients.
210 * An event has both a declared type and a separate data block.
211 * It also ends with two newlines (to mark the end of the event).
213 broadcast_event(type, data) {
214 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
217 game_state_event_data(old_state, new_state) {
220 old_state_name = GameState.properties[old_state].name;
222 old_state_name = "none";
223 const new_state_name = GameState.properties[new_state].name;
225 return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
228 /* Inform clients about a state change. */
229 broadcast_state_change() {
230 const event_data = this.game_state_event_data(this.old_state, this.state);
231 this.broadcast_event("game-state", event_data);
234 /* Change game state and broadcast the change to all clients. */
235 change_state(state) {
236 /* Do nothing if there is no actual change happening. */
237 if (state === this.state)
240 this.old_state = this.state;
243 this.broadcast_state_change();
247 function handle_events(request, response) {
248 const game = request.game;
249 /* These headers will keep the connection open so we can stream events. */
251 "Content-type": "text/event-stream",
252 "Connection": "keep-alive",
253 "Cache-Control": "no-cache"
255 response.writeHead(200, headers);
257 /* Now that a client has connected, first we need to stream all of
258 * the existing spectators and players (if any). */
259 if (game._spectators.length > 0) {
260 const spectators_json = JSON.stringify(game.spectators);
261 const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
262 response.write(spectators_data);
265 if (game._players.length > 0) {
266 const players_json = JSON.stringify(game.players);
267 const players_data = `event: players\ndata: ${players_json}\n\n`;
268 response.write(players_data);
271 /* And we need to inform the client of the current game state.
273 * In fact, we need to cycle through each state transition from the
274 * beginning so the client can see each.
276 var old_state = null;
277 for (var state = GameState.JOIN; state <= game.state; state++) {
278 var event_data = game.game_state_event_data(old_state, state);
279 response.write("event: game-state\n" + "data: " + event_data + "\n\n");
283 /* Add this new client to our list of clients. */
284 const id = game.add_client(response);
286 /* And queue up cleanup to be triggered on client close. */
287 request.on('close', () => {
288 game.remove_client(id);
292 router.get('/', (request, response) => {
293 if (! request.session.nickname)
294 response.render('choose-nickname.html', { game_name: "Empires" });
296 response.render('empires-game.html');
299 router.post('/spectator', (request, response) => {
300 const game = request.game;
301 var name = request.session.nickname;
303 /* If the request includes a name, that overrides the session nickname. */
304 if (request.body.name)
305 name = request.body.name;
307 const id = game.add_spectator(name, request.session.id);
308 response.send(JSON.stringify(id));
311 router.delete('/spectator/:id', (request, response) => {
312 const game = request.game;
313 game.remove_spectator(parseInt(request.params.id));
317 router.post('/register', (request, response) => {
318 const game = request.game;
319 var name = request.session.nickname;;
321 /* If the request includes a name, that overrides the session nickname. */
322 if (request.body.name)
323 name = request.body.name;
325 game.add_player(name, request.body.character);
329 router.post('/deregister/:id', (request, response) => {
330 const game = request.game;
331 game.remove_player(parseInt(request.params.id));
335 router.post('/reveal', (request, response) => {
336 const game = request.game;
341 router.post('/start', (request, response) => {
342 const game = request.game;
347 router.post('/reset', (request, response) => {
348 const game = request.game;
353 router.post('/capture/:captor/:captee', (request, response) => {
354 const game = request.game;
355 game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
359 router.post('/liberate/:id', (request, response) => {
360 const game = request.game;
361 game.liberate(parseInt(request.params.id));
365 router.post('/restart', (request, response) => {
366 const game = request.game;
367 game.restart(parseInt(request.params.id));
371 router.get('/characters', (request, response) => {
372 const game = request.game;
373 response.send(game.characters);
376 router.get('/empires', (request, response) => {
377 const game = request.game;
378 response.send(game.empires);
381 router.get('/spectators', (request, response) => {
382 const game = request.game;
383 response.send(game.spectators);
386 router.get('/players', (request, response) => {
387 const game = request.game;
388 response.send(game.players);
391 router.get('/events', handle_events);
393 exports.router = router;
394 exports.name = engine_name;
395 exports.Game = Empires;