]> git.cworth.org Git - empires-server/blob - empires.js
Add new game.js with a new parent class 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.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_spectator(name, session_id) {
53     /* Don't add another spectator that matches an existing session. */
54     const existing = this._spectators.findIndex(
55       spectator => spectator.session_id === session_id);
56     if (existing >= 0)
57       return existing.id;
58
59     const new_spectator = {id: this.next_spectator_id,
60                            name: name,
61                            session_id: session_id
62                           };
63     this._spectators.push(new_spectator);
64     this.next_spectator_id++;
65     this.broadcast_event("spectator-join", JSON.stringify(new_spectator));
66
67     return new_spectator.id;
68   }
69
70   remove_spectator(id) {
71     const index = this._spectators.findIndex(spectator => spectator.id === id);
72     this._spectators.splice(index, 1);
73
74     this.broadcast_event("spectator-leave", `{"id": ${id}}`);
75   }
76
77   add_player(name, character) {
78     const new_player = {id: this.next_player_id,
79                        name: name,
80                        character: character,
81                        captures: [],
82                        };
83     this._players.push(new_player);
84     this.next_player_id++;
85     /* The syntax here is using an anonymous function to create a new
86       object from new_player with just the subset of fields that we
87       want. */
88     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
89     this.broadcast_event("player-join", player_data);
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   add_client(response) {
191     const id = this.next_client_id;
192     this.clients.push({id: id,
193                        response: response});
194     this.next_client_id++;
195
196     return id;
197   }
198
199   remove_client(id) {
200     this.clients = this.clients.filter(client => client.id !== id);
201   }
202
203   /* Send a string to all clients */
204   broadcast_string(str) {
205     this.clients.forEach(client => client.response.write(str + '\n'));
206   }
207
208   /* Send an event to all clients.
209    *
210    * An event has both a declared type and a separate data block.
211    * It also ends with two newlines (to mark the end of the event).
212    */
213   broadcast_event(type, data) {
214     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
215   }
216
217   game_state_event_data(old_state, new_state) {
218     var old_state_name;
219     if (old_state)
220       old_state_name = GameState.properties[old_state].name;
221     else
222       old_state_name = "none";
223     const new_state_name = GameState.properties[new_state].name;
224
225     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
226   }
227
228   /* Inform clients about a state change. */
229   broadcast_state_change() {
230     const event_data = this.game_state_event_data(this.old_state, this.state);
231     this.broadcast_event("game-state", event_data);
232   }
233
234   /* Change game state and broadcast the change to all clients. */
235   change_state(state) {
236     /* Do nothing if there is no actual change happening. */
237     if (state === this.state)
238       return;
239
240     this.old_state = this.state;
241     this.state = state;
242
243     this.broadcast_state_change();
244   }
245 }
246
247 function handle_events(request, response) {
248   const game = request.game;
249   /* These headers will keep the connection open so we can stream events. */
250   const headers = {
251     "Content-type": "text/event-stream",
252     "Connection": "keep-alive",
253     "Cache-Control": "no-cache"
254   };
255   response.writeHead(200, headers);
256
257   /* Now that a client has connected, first we need to stream all of
258    * the existing spectators and players (if any). */
259   if (game._spectators.length > 0) {
260     const spectators_json = JSON.stringify(game.spectators);
261     const spectators_data = `event: spectators\ndata: ${spectators_json}\n\n`;
262     response.write(spectators_data);
263   }
264
265   if (game._players.length > 0) {
266     const players_json = JSON.stringify(game.players);
267     const players_data = `event: players\ndata: ${players_json}\n\n`;
268     response.write(players_data);
269   }
270
271   /* And we need to inform the client of the current game state.
272    *
273    * In fact, we need to cycle through each state transition from the
274    * beginning so the client can see each.
275    */
276   var old_state = null;
277   for (var state = GameState.JOIN; state <= game.state; state++) {
278     var event_data = game.game_state_event_data(old_state, state);
279     response.write("event: game-state\n" + "data: " + event_data + "\n\n");
280     old_state = state;
281   }
282
283   /* Add this new client to our list of clients. */
284   const id = game.add_client(response);
285
286   /* And queue up cleanup to be triggered on client close. */
287   request.on('close', () => {
288     game.remove_client(id);
289   });
290 }
291
292 router.get('/', (request, response) => {
293   if (! request.session.nickname)
294     response.render('choose-nickname.html', { game_name: "Empires" });
295   else
296     response.render('empires-game.html');
297 });
298
299 router.post('/spectator', (request, response) => {
300   const game = request.game;
301   var name = request.session.nickname;
302
303   /* If the request includes a name, that overrides the session nickname. */
304   if (request.body.name)
305     name = request.body.name;
306
307   const id = game.add_spectator(name, request.session.id);
308   response.send(JSON.stringify(id));
309 });
310
311 router.delete('/spectator/:id', (request, response) => {
312   const game = request.game;
313   game.remove_spectator(parseInt(request.params.id));
314   response.send();
315 });
316
317 router.post('/register', (request, response) => {
318   const game = request.game;
319   var name = request.session.nickname;;
320
321   /* If the request includes a name, that overrides the session nickname. */
322   if (request.body.name)
323     name = request.body.name;
324
325   game.add_player(name, request.body.character);
326   response.send();
327 });
328
329 router.post('/deregister/:id', (request, response) => {
330   const game = request.game;
331   game.remove_player(parseInt(request.params.id));
332   response.send();
333 });
334
335 router.post('/reveal', (request, response) => {
336   const game = request.game;
337   game.reveal();
338   response.send();
339 });
340
341 router.post('/start', (request, response) => {
342   const game = request.game;
343   game.start();
344   response.send();
345 });
346
347 router.post('/reset', (request, response) => {
348   const game = request.game;
349   game.reset();
350   response.send();
351 });
352
353 router.post('/capture/:captor/:captee', (request, response) => {
354   const game = request.game;
355   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
356   response.send();
357 });
358
359 router.post('/liberate/:id', (request, response) => {
360   const game = request.game;
361   game.liberate(parseInt(request.params.id));
362   response.send();
363 });
364
365 router.post('/restart', (request, response) => {
366   const game = request.game;
367   game.restart(parseInt(request.params.id));
368     response.send();
369 });
370
371 router.get('/characters', (request, response) => {
372   const game = request.game;
373   response.send(game.characters);
374 });
375
376 router.get('/empires', (request, response) => {
377   const game = request.game;
378   response.send(game.empires);
379 });
380
381 router.get('/spectators', (request, response) => {
382   const game = request.game;
383   response.send(game.spectators);
384 });
385
386 router.get('/players', (request, response) => {
387   const game = request.game;
388   response.send(game.players);
389 });
390
391 router.get('/events', handle_events);
392
393 exports.router = router;
394 exports.name = engine_name;
395 exports.Game = Empires;