]> git.cworth.org Git - empires-server/blob - empires.js
Eliminate code duplication for root path
[empires-server] / empires.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 const engine_name = "empires";
5
6 const router = express.Router();
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 Empires extends Game {
37   constructor() {
38     super(engine_name);
39     this._spectators = [];
40     this.next_spectator_id = 1;
41     this._players = [];
42     this.next_player_id = 1;
43     this.characters_to_reveal = null;
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_spectator(name, session_id) {
51     /* Don't add another spectator that matches an existing session. */
52     const existing = this._spectators.findIndex(
53       spectator => spectator.session_id === session_id);
54     if (existing >= 0)
55       return existing.id;
56
57     const new_spectator = {id: this.next_spectator_id,
58                            name: name,
59                            session_id: session_id
60                           };
61     this._spectators.push(new_spectator);
62     this.next_spectator_id++;
63     this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
64
65     return new_spectator.id;
66   }
67
68   remove_spectator(id) {
69     const index = this._spectators.findIndex(spectator => spectator.id === id);
70     this._spectators.splice(index, 1);
71
72     this.broadcast_event("spectator-leave", `{"id": ${id}}`);
73   }
74
75   add_player(name, character) {
76     const new_player = {id: this.next_player_id,
77                        name: name,
78                        character: character,
79                        captures: [],
80                        };
81     this._players.push(new_player);
82     this.next_player_id++;
83     /* The syntax here is using an anonymous function to create a new
84       object from new_player with just the subset of fields that we
85       want. */
86     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
87     this.broadcast_event("player-join", player_data);
88
89     return new_player;
90   }
91
92   remove_player(id) {
93     const index = this._players.findIndex(player => player.id === id);
94     this._players.splice(index, 1);
95
96     this.broadcast_event("player-leave", `{"id": ${id}}`);
97   }
98
99   reset() {
100     this._players = [];
101     this.characters_to_reveal = null;
102     this.next_player_id = 1;
103
104     this.change_state(GameState.JOIN);
105
106     this.broadcast_event("spectators", "{}");
107     this.broadcast_event("players", "{}");
108   }
109
110   reveal_next() {
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);
114       return;
115     }
116
117     if (this.reveal_index >= this.characters_to_reveal.length) {
118       clearInterval(this.reveal_interval);
119       this.broadcast_event("character-reveal", '{"character":""}');
120       return;
121     }
122     const character = this.characters_to_reveal[this.reveal_index];
123     this.reveal_index++;
124     const character_data = JSON.stringify({"character":character});
125     this.broadcast_event("character-reveal", character_data);
126   }
127
128   reveal() {
129     this.change_state(GameState.REVEAL);
130
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);
135         return characters;
136       }, []);
137       shuffle(this.characters_to_reveal);
138     }
139
140     this.reveal_index = 0;
141
142     this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
143   }
144
145   start() {
146     this.change_state(GameState.CAPTURE);
147   }
148
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);
155
156     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
157   }
158
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);
162   }
163
164   restart() {
165     for (const player of this._players) {
166       player.captures = [];
167     }
168   }
169
170   get characters() {
171     return this._players.map(player => player.character);
172   }
173
174   get empires() {
175     return this._players.map(player => ({id: player.id, captures: player.captures}));
176   }
177
178   get spectators() {
179     /* We return only "id" and "name" here (specifically not session_id!). */
180     return this._spectators.map(spectator => ({
181       id: spectator.id,
182       name: spectator.name
183     }));
184   }
185
186   get players() {
187     return this._players.map(player => ({id: player.id, name: player.name }));
188   }
189
190   game_state_event_data(old_state, new_state) {
191     var old_state_name;
192     if (old_state)
193       old_state_name = GameState.properties[old_state].name;
194     else
195       old_state_name = "none";
196     const new_state_name = GameState.properties[new_state].name;
197
198     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
199   }
200
201   /* Inform clients about a state change. */
202   broadcast_state_change() {
203     const event_data = this.game_state_event_data(this.old_state, this.state);
204     this.broadcast_event("game-state", event_data);
205   }
206
207   /* Change game state and broadcast the change to all clients. */
208   change_state(state) {
209     /* Do nothing if there is no actual change happening. */
210     if (state === this.state)
211       return;
212
213     this.old_state = this.state;
214     this.state = state;
215
216     this.broadcast_state_change();
217   }
218
219   handle_events(request, response) {
220
221     super.handle_events(request, response);
222
223     /* Now that a client has connected, first we need to stream all of
224      * the existing spectators and players (if any). */
225     if (this._spectators.length > 0) {
226       const spectators_json = JSON.stringify(this.spectators);
227       const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
228       response.write(spectators_data);
229     }
230
231     if (this._players.length > 0) {
232       const players_json = JSON.stringify(this.players);
233       const players_data = `event: players\ndata: ${players_json}\n\n`;
234       response.write(players_data);
235     }
236
237     /* And we need to inform the client of the current game state.
238      *
239      * In fact, we need to cycle through each state transition from the
240      * beginning so the client can see each.
241      */
242     var old_state = null;
243     for (var state = GameState.JOIN; state <= this.state; state++) {
244       var event_data = this.game_state_event_data(old_state, state);
245       response.write("event: game-state\n" + "data: " + event_data + "\n\n");
246       old_state = state;
247     }
248   }
249
250 }
251
252 router.post('/spectator', (request, response) => {
253   const game = request.game;
254   var name = request.session.nickname;
255
256   /* If the request includes a name, that overrides the session nickname. */
257   if (request.body.name)
258     name = request.body.name;
259
260   const id = game.add_spectator(name, request.session.id);
261   response.send(JSON.stringify(id));
262 });
263
264 router.delete('/spectator/:id', (request, response) => {
265   const game = request.game;
266   game.remove_spectator(parseInt(request.params.id));
267   response.send();
268 });
269
270 router.post('/register', (request, response) => {
271   const game = request.game;
272   var name = request.session.nickname;;
273
274   /* If the request includes a name, that overrides the session nickname. */
275   if (request.body.name)
276     name = request.body.name;
277
278   const player = game.add_player(name, request.body.character);
279   response.send(JSON.stringify(player.id));
280 });
281
282 router.post('/deregister/:id', (request, response) => {
283   const game = request.game;
284   game.remove_player(parseInt(request.params.id));
285   response.send();
286 });
287
288 router.post('/reveal', (request, response) => {
289   const game = request.game;
290   game.reveal();
291   response.send();
292 });
293
294 router.post('/start', (request, response) => {
295   const game = request.game;
296   game.start();
297   response.send();
298 });
299
300 router.post('/reset', (request, response) => {
301   const game = request.game;
302   game.reset();
303   response.send();
304 });
305
306 router.post('/capture/:captor/:captee', (request, response) => {
307   const game = request.game;
308   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
309   response.send();
310 });
311
312 router.post('/liberate/:id', (request, response) => {
313   const game = request.game;
314   game.liberate(parseInt(request.params.id));
315   response.send();
316 });
317
318 router.post('/restart', (request, response) => {
319   const game = request.game;
320   game.restart(parseInt(request.params.id));
321     response.send();
322 });
323
324 router.get('/characters', (request, response) => {
325   const game = request.game;
326   response.send(game.characters);
327 });
328
329 router.get('/empires', (request, response) => {
330   const game = request.game;
331   response.send(game.empires);
332 });
333
334 router.get('/spectators', (request, response) => {
335   const game = request.game;
336   response.send(game.spectators);
337 });
338
339 router.get('/players', (request, response) => {
340   const game = request.game;
341   response.send(game.players);
342 });
343
344 router.get('/events', (request, response) => {
345   const game = request.game;
346   game.handle_events(request, response);
347 });
348
349 exports.router = router;
350 exports.name = engine_name;
351 exports.Game = Empires;
352
353 Empires.meta = {
354   name: "Empires",
355   identifier: "empires"
356 };
357
358 exports.meta = Empires.meta;