]> git.cworth.org Git - empires-server/blob - empires.js
empires: Pull the body_parser use statements up to the top of the file
[empires-server] / empires.js
1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
4 const path = require("path");
5
6 const app = express();
7 app.use(cors());
8 app.use(body_parser.urlencoded({ extended: false }));
9 app.use(body_parser.json());
10
11 const GameState = {
12   JOIN:    1,
13   REVEAL:  2,
14   CAPTURE: 3,
15   properties: {
16     1: {name: "join"},
17     2: {name: "reveal"},
18     3: {name: "capture"}
19   }
20 };
21
22 /**
23  * Shuffles array in place.
24  * @param {Array} a items An array containing the items.
25  */
26 function shuffle(a) {
27   if (a === undefined)
28     return;
29
30   var j, x, i;
31   for (i = a.length - 1; i > 0; i--) {
32     j = Math.floor(Math.random() * (i + 1));
33     x = a[i];
34     a[i] = a[j];
35     a[j] = x;
36   }
37 }
38
39 class Game {
40   constructor() {
41     this._players = [];
42     this.characters_to_reveal = null;
43     this.next_player_id = 1;
44     this.clients = [];
45     this.next_client_id = 1;
46     this.state = GameState.JOIN;
47
48     /* Send a comment to every connected client every 15 seconds. */
49     setInterval(() => {this.broadcast_string(":");}, 15000);
50   }
51
52   add_player(name, character) {
53     const new_player = {id: this.next_player_id,
54                        name: name,
55                        character: character,
56                        captures: [],
57                        };
58     this._players.push(new_player);
59     this.next_player_id++;
60     /* The syntax here is using an anonymous function to create a new
61       object from new_player with just the subset of fields that we
62       want. */
63     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
64     this.broadcast_event("player-join", player_data);
65   }
66
67   remove_player(id) {
68     const index = this._players.findIndex(player => player.id === id);
69     this._players.splice(index, 1);
70
71     this.broadcast_event("player-leave", `{"id": ${id}}`);
72   }
73
74   reset() {
75     this._players = [];
76     this.characters_to_reveal = null;
77     this.next_player_id = 1;
78
79     this.change_state(GameState.JOIN);
80
81     this.broadcast_event("players", "{}");
82   }
83
84   reveal_next() {
85     /* Don't try to reveal anything if we aren't in the reveal state. */
86     if (this.state != GameState.REVEAL) {
87       clearInterval(this.reveal_interval);
88       return;
89     }
90
91     if (this.reveal_index >= this.characters_to_reveal.length) {
92       clearInterval(this.reveal_interval);
93       this.broadcast_event("character-reveal", '{"character":""}');
94       return;
95     }
96     const character = this.characters_to_reveal[this.reveal_index];
97     this.reveal_index++;
98     const character_data = JSON.stringify({"character":character});
99     this.broadcast_event("character-reveal", character_data);
100   }
101
102   reveal() {
103     this.change_state(GameState.REVEAL);
104
105     if (this.characters_to_reveal === null) {
106       this.characters_to_reveal = [];
107       this.characters_to_reveal = this._players.reduce((characters, player) => {
108         characters.push(player.character);
109         return characters;
110       }, []);
111       shuffle(this.characters_to_reveal);
112     }
113
114     this.reveal_index = 0;
115
116     this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
117   }
118
119   start() {
120     this.change_state(GameState.CAPTURE);
121   }
122
123   capture(captor_id, captee_id) {
124     /* TODO: Fix to fail on already-captured players (or to move the
125      * captured player from an old captor to a new—need to clarify in
126      * the API specification which we want here. */
127     let captor = this._players.find(player => player.id === captor_id);
128     captor.captures.push(captee_id);
129
130     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
131   }
132
133   liberate(captee_id) {
134     let captor = this._players.find(player => player.captures.includes(captee_id));
135     captor.captures.splice(captor.captures.indexOf(captee_id), 1);
136   }
137
138   restart() {
139     for (const player of this._players) {
140       player.captures = [];
141     }
142   }
143
144   get characters() {
145     return this._players.map(player => player.character);
146   }
147
148   get empires() {
149     return this._players.map(player => ({id: player.id, captures: player.captures}));
150   }
151
152   get players() {
153     return this._players.map(player => ({id: player.id, name: player.name }));
154   }
155
156   add_client(response) {
157     const id = this.next_client_id;
158     this.clients.push({id: id,
159                        response: response});
160     this.next_client_id++;
161
162     return id;
163   }
164
165   remove_client(id) {
166     this.clients = this.clients.filter(client => client.id !== id);
167   }
168
169   /* Send a string to all clients */
170   broadcast_string(str) {
171     this.clients.forEach(client => client.response.write(str + '\n'));
172   }
173
174   /* Send an event to all clients.
175    *
176    * An event has both a declared type and a separate data block.
177    * It also ends with two newlines (to mark the end of the event).
178    */
179   broadcast_event(type, data) {
180     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
181   }
182
183   game_state_event_data(old_state, new_state) {
184     var old_state_name;
185     if (old_state)
186       old_state_name = GameState.properties[old_state].name;
187     else
188       old_state_name = "none";
189     const new_state_name = GameState.properties[new_state].name;
190
191     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
192   }
193
194   /* Inform clients about a state change. */
195   broadcast_state_change() {
196     const event_data = this.game_state_event_data(this.old_state, this.state);
197     this.broadcast_event("game-state", event_data);
198   }
199
200   /* Change game state and broadcast the change to all clients. */
201   change_state(state) {
202     /* Do nothing if there is no actual change happening. */
203     if (state === this.state)
204       return;
205
206     this.old_state = this.state;
207     this.state = state;
208
209     this.broadcast_state_change();
210   }
211 }
212
213 function handle_events(request, response) {
214   const game = request.game;
215   /* These headers will keep the connection open so we can stream events. */
216   const headers = {
217     "Content-type": "text/event-stream",
218     "Connection": "keep-alive",
219     "Cache-Control": "no-cache"
220   };
221   response.writeHead(200, headers);
222
223   /* Now that a client has connected, first we need to stream all of
224    * the existing players (if any). */
225   if (game._players.length > 0) {
226     const players_json = JSON.stringify(game.players);
227     const players_data = `event: players\ndata: ${players_json}\n\n`;
228     response.write(players_data);
229   }
230
231   /* And we need to inform the client of the current game state.
232    *
233    * In fact, we need to cycle through each state transition from the
234    * beginning so the client can see each.
235    */
236   var old_state = null;
237   for (var state = GameState.JOIN; state <= game.state; state++) {
238     var event_data = game.game_state_event_data(old_state, state);
239     response.write("event: game-state\n" + "data: " + event_data + "\n\n");
240     old_state = state;
241   }
242
243   /* Add this new client to our list of clients. */
244   const id = game.add_client(response);
245
246   /* And queue up cleanup to be triggered on client close. */
247   request.on('close', () => {
248     game.remove_client(id);
249   });
250 }
251
252 app.get('/', (request, response) => {
253   response.sendFile(path.join(__dirname, './game.html'));
254 });
255
256 app.post('/register', (request, response) => {
257   const game = request.game;
258   game.add_player(request.body.name, request.body.character);
259   response.send();
260 });
261
262 app.post('/deregister/:id', (request, response) => {
263   const game = request.game;
264   game.remove_player(parseInt(request.params.id));
265   response.send();
266 });
267
268 app.post('/reveal', (request, response) => {
269   const game = request.game;
270   game.reveal();
271   response.send();
272 });
273
274 app.post('/start', (request, response) => {
275   const game = request.game;
276   game.start();
277   response.send();
278 });
279
280 app.post('/reset', (request, response) => {
281   const game = request.game;
282   game.reset();
283   response.send();
284 });
285
286 app.post('/capture/:captor/:captee', (request, response) => {
287   const game = request.game;
288   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
289   response.send();
290 });
291
292 app.post('/liberate/:id', (request, response) => {
293   const game = request.game;
294   game.liberate(parseInt(request.params.id));
295   response.send();
296 });
297
298 app.post('/restart', (request, response) => {
299   const game = request.game;
300   game.restart(parseInt(request.params.id));
301     response.send();
302 });
303
304 app.get('/characters', (request, response) => {
305   const game = request.game;
306   response.send(game.characters);
307 });
308
309 app.get('/empires', (request, response) => {
310   const game = request.game;
311   response.send(game.empires);
312 });
313
314 app.get('/players', (request, response) => {
315   const game = request.game;
316   response.send(game.players);
317 });
318
319 app.get('/events', handle_events);
320
321 exports.app = app;
322 exports.Game = Game;