]> git.cworth.org Git - empires-server/blob - empires.js
Put add_client/remove_client and the various broadcast functions into Game
[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
90   remove_player(id) {
91     const index = this._players.findIndex(player => player.id === id);
92     this._players.splice(index, 1);
93
94     this.broadcast_event("player-leave", `{"id": ${id}}`);
95   }
96
97   reset() {
98     this._players = [];
99     this.characters_to_reveal = null;
100     this.next_player_id = 1;
101
102     this.change_state(GameState.JOIN);
103
104     this.broadcast_event("spectators", "{}");
105     this.broadcast_event("players", "{}");
106   }
107
108   reveal_next() {
109     /* Don't try to reveal anything if we aren't in the reveal state. */
110     if (this.state != GameState.REVEAL) {
111       clearInterval(this.reveal_interval);
112       return;
113     }
114
115     if (this.reveal_index >= this.characters_to_reveal.length) {
116       clearInterval(this.reveal_interval);
117       this.broadcast_event("character-reveal", '{"character":""}');
118       return;
119     }
120     const character = this.characters_to_reveal[this.reveal_index];
121     this.reveal_index++;
122     const character_data = JSON.stringify({"character":character});
123     this.broadcast_event("character-reveal", character_data);
124   }
125
126   reveal() {
127     this.change_state(GameState.REVEAL);
128
129     if (this.characters_to_reveal === null) {
130       this.characters_to_reveal = [];
131       this.characters_to_reveal = this._players.reduce((characters, player) => {
132         characters.push(player.character);
133         return characters;
134       }, []);
135       shuffle(this.characters_to_reveal);
136     }
137
138     this.reveal_index = 0;
139
140     this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
141   }
142
143   start() {
144     this.change_state(GameState.CAPTURE);
145   }
146
147   capture(captor_id, captee_id) {
148     /* TODO: Fix to fail on already-captured players (or to move the
149      * captured player from an old captor to a new—need to clarify in
150      * the API specification which we want here. */
151     let captor = this._players.find(player => player.id === captor_id);
152     captor.captures.push(captee_id);
153
154     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
155   }
156
157   liberate(captee_id) {
158     let captor = this._players.find(player => player.captures.includes(captee_id));
159     captor.captures.splice(captor.captures.indexOf(captee_id), 1);
160   }
161
162   restart() {
163     for (const player of this._players) {
164       player.captures = [];
165     }
166   }
167
168   get characters() {
169     return this._players.map(player => player.character);
170   }
171
172   get empires() {
173     return this._players.map(player => ({id: player.id, captures: player.captures}));
174   }
175
176   get spectators() {
177     /* We return only "id" and "name" here (specifically not session_id!). */
178     return this._spectators.map(spectator => ({
179       id: spectator.id,
180       name: spectator.name
181     }));
182   }
183
184   get players() {
185     return this._players.map(player => ({id: player.id, name: player.name }));
186   }
187
188   game_state_event_data(old_state, new_state) {
189     var old_state_name;
190     if (old_state)
191       old_state_name = GameState.properties[old_state].name;
192     else
193       old_state_name = "none";
194     const new_state_name = GameState.properties[new_state].name;
195
196     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
197   }
198
199   /* Inform clients about a state change. */
200   broadcast_state_change() {
201     const event_data = this.game_state_event_data(this.old_state, this.state);
202     this.broadcast_event("game-state", event_data);
203   }
204
205   /* Change game state and broadcast the change to all clients. */
206   change_state(state) {
207     /* Do nothing if there is no actual change happening. */
208     if (state === this.state)
209       return;
210
211     this.old_state = this.state;
212     this.state = state;
213
214     this.broadcast_state_change();
215   }
216 }
217
218 function handle_events(request, response) {
219   const game = request.game;
220   /* These headers will keep the connection open so we can stream events. */
221   const headers = {
222     "Content-type": "text/event-stream",
223     "Connection": "keep-alive",
224     "Cache-Control": "no-cache"
225   };
226   response.writeHead(200, headers);
227
228   /* Now that a client has connected, first we need to stream all of
229    * the existing spectators and players (if any). */
230   if (game._spectators.length > 0) {
231     const spectators_json = JSON.stringify(game.spectators);
232     const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
233     response.write(spectators_data);
234   }
235
236   if (game._players.length > 0) {
237     const players_json = JSON.stringify(game.players);
238     const players_data = `event: players\ndata: ${players_json}\n\n`;
239     response.write(players_data);
240   }
241
242   /* And we need to inform the client of the current game state.
243    *
244    * In fact, we need to cycle through each state transition from the
245    * beginning so the client can see each.
246    */
247   var old_state = null;
248   for (var state = GameState.JOIN; state <= game.state; state++) {
249     var event_data = game.game_state_event_data(old_state, state);
250     response.write("event: game-state\n" + "data: " + event_data + "\n\n");
251     old_state = state;
252   }
253
254   /* Add this new client to our list of clients. */
255   const id = game.add_client(response);
256
257   /* And queue up cleanup to be triggered on client close. */
258   request.on('close', () => {
259     game.remove_client(id);
260   });
261 }
262
263 router.get('/', (request, response) => {
264   if (! request.session.nickname)
265     response.render('choose-nickname.html', { game_name: "Empires" });
266   else
267     response.render('empires-game.html');
268 });
269
270 router.post('/spectator', (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 id = game.add_spectator(name, request.session.id);
279   response.send(JSON.stringify(id));
280 });
281
282 router.delete('/spectator/:id', (request, response) => {
283   const game = request.game;
284   game.remove_spectator(parseInt(request.params.id));
285   response.send();
286 });
287
288 router.post('/register', (request, response) => {
289   const game = request.game;
290   var name = request.session.nickname;;
291
292   /* If the request includes a name, that overrides the session nickname. */
293   if (request.body.name)
294     name = request.body.name;
295
296   game.add_player(name, request.body.character);
297   response.send();
298 });
299
300 router.post('/deregister/:id', (request, response) => {
301   const game = request.game;
302   game.remove_player(parseInt(request.params.id));
303   response.send();
304 });
305
306 router.post('/reveal', (request, response) => {
307   const game = request.game;
308   game.reveal();
309   response.send();
310 });
311
312 router.post('/start', (request, response) => {
313   const game = request.game;
314   game.start();
315   response.send();
316 });
317
318 router.post('/reset', (request, response) => {
319   const game = request.game;
320   game.reset();
321   response.send();
322 });
323
324 router.post('/capture/:captor/:captee', (request, response) => {
325   const game = request.game;
326   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
327   response.send();
328 });
329
330 router.post('/liberate/:id', (request, response) => {
331   const game = request.game;
332   game.liberate(parseInt(request.params.id));
333   response.send();
334 });
335
336 router.post('/restart', (request, response) => {
337   const game = request.game;
338   game.restart(parseInt(request.params.id));
339     response.send();
340 });
341
342 router.get('/characters', (request, response) => {
343   const game = request.game;
344   response.send(game.characters);
345 });
346
347 router.get('/empires', (request, response) => {
348   const game = request.game;
349   response.send(game.empires);
350 });
351
352 router.get('/spectators', (request, response) => {
353   const game = request.game;
354   response.send(game.spectators);
355 });
356
357 router.get('/players', (request, response) => {
358   const game = request.game;
359   response.send(game.players);
360 });
361
362 router.get('/events', handle_events);
363
364 exports.router = router;
365 exports.name = engine_name;
366 exports.Game = Empires;