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