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