]> git.cworth.org Git - empires-server/blob - empires.js
Remove old placeholder code for sending "Hello World"
[empires-server] / empires.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   reset() {
72     this._players = [];
73     this.characters_to_reveal = null;
74     this.next_player_id = 1;
75
76     this.change_state(GameState.JOIN);
77
78     this.broadcast_event("players", "{}");
79   }
80
81   reveal_next() {
82     /* Don't try to reveal anything if we aren't in the reveal state. */
83     if (this.state != GameState.REVEAL) {
84       clearInterval(this.reveal_interval);
85       return;
86     }
87
88     if (this.reveal_index >= this.characters_to_reveal.length) {
89       clearInterval(this.reveal_interval);
90       this.broadcast_event("character-reveal", '{"character":""}');
91       return;
92     }
93     const character = this.characters_to_reveal[this.reveal_index];
94     this.reveal_index++;
95     const character_data = JSON.stringify({"character":character});
96     this.broadcast_event("character-reveal", character_data);
97   }
98
99   reveal() {
100     this.change_state(GameState.REVEAL);
101
102     if (this.characters_to_reveal === null) {
103       this.characters_to_reveal = [];
104       this.characters_to_reveal = this._players.reduce((characters, player) => {
105         characters.push(player.character);
106         return characters;
107       }, []);
108       shuffle(this.characters_to_reveal);
109     }
110
111     this.reveal_index = 0;
112
113     this.reveal_interval = setInterval(this.reveal_next.bind(this), 3000);
114   }
115
116   start() {
117     this.change_state(GameState.CAPTURE);
118   }
119
120   capture(captor_id, captee_id) {
121     /* TODO: Fix to fail on already-captured players (or to move the
122      * captured player from an old captor to a new—need to clarify in
123      * the API specification which we want here. */
124     let captor = this._players.find(player => player.id === captor_id);
125     captor.captures.push(captee_id);
126
127     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
128   }
129
130   liberate(captee_id) {
131     let captor = this._players.find(player => player.captures.includes(captee_id));
132     captor.captures.splice(captor.captures.indexOf(captee_id), 1);
133   }
134
135   restart() {
136     for (const player of this._players) {
137       player.captures = [];
138     }
139   }
140
141   get characters() {
142     return this._players.map(player => player.character);
143   }
144
145   get empires() {
146     return this._players.map(player => ({id: player.id, captures: player.captures}));
147   }
148
149   get players() {
150     return this._players.map(player => ({id: player.id, name: player.name }));
151   }
152
153   add_client(response) {
154     const id = this.next_client_id;
155     this.clients.push({id: id,
156                        response: response});
157     this.next_client_id++;
158
159     return id;
160   }
161
162   remove_client(id) {
163     this.clients = this.clients.filter(client => client.id !== id);
164   }
165
166   /* Send a string to all clients */
167   broadcast_string(str) {
168     this.clients.forEach(client => client.response.write(str + '\n'));
169   }
170
171   /* Send an event to all clients.
172    *
173    * An event has both a declared type and a separate data block.
174    * It also ends with two newlines (to mark the end of the event).
175    */
176   broadcast_event(type, data) {
177     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
178   }
179
180   game_state_event_data(old_state, new_state) {
181     var old_state_name;
182     if (old_state)
183       old_state_name = GameState.properties[old_state].name;
184     else
185       old_state_name = "none";
186     const new_state_name = GameState.properties[new_state].name;
187
188     return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`;
189   }
190
191   /* Inform clients about a state change. */
192   broadcast_state_change() {
193     const event_data = this.game_state_event_data(this.old_state, this.state);
194     this.broadcast_event("game-state", event_data);
195   }
196
197   /* Change game state and broadcast the change to all clients. */
198   change_state(state) {
199     /* Do nothing if there is no actual change happening. */
200     if (state === this.state)
201       return;
202
203     this.old_state = this.state;
204     this.state = state;
205
206     this.broadcast_state_change();
207   }
208 }
209
210 const game = new Game();
211
212 app.use(body_parser.urlencoded({ extended: false }));
213 app.use(body_parser.json());
214
215 function handle_events(request, response) {
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.post('/register', (request, response) => {
254   game.add_player(request.body.name, request.body.character);
255   response.send();
256 });
257
258 app.post('/deregister/:id', (request, response) => {
259   game.remove_player(parseInt(request.params.id));
260   response.send();
261 });
262
263 app.post('/reveal', (request, response) => {
264   game.reveal();
265   response.send();
266 });
267
268 app.post('/start', (request, response) => {
269   game.start();
270   response.send();
271 });
272
273 app.post('/reset', (request, response) => {
274   game.reset();
275   response.send();
276 });
277
278 app.post('/capture/:captor/:captee', (request, response) => {
279   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
280   response.send();
281 });
282
283 app.post('/liberate/:id', (request, response) => {
284   game.liberate(parseInt(request.params.id));
285   response.send();
286 });
287
288 app.post('/restart', (request, response) => {
289   game.restart(parseInt(request.params.id));
290     response.send();
291 });
292
293 app.get('/characters', (request, response) => {
294   response.send(game.characters);
295 });
296
297 app.get('/empires', (request, response) => {
298   response.send(game.empires);
299 });
300
301 app.get('/players', (request, response) => {
302   response.send(game.players);
303 });
304
305 app.get('/events', handle_events);
306
307 app.listen(3000, function () {
308   console.log('Empires server listening on localhost:3000');
309 });