]> git.cworth.org Git - lmno-server/blob - server.js
ca7b844c5296b893ca114bc68433b8dd299a0ea5
[lmno-server] / server.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 class Game {
9   constructor() {
10     this._players = [];
11     this.next_player_id = 1;
12     this.clients = [];
13     this.next_client_id = 1;
14
15     /* Send a comment to every connected client every 15 seconds. */
16     setInterval(() => {this.broadcast_string(":");}, 15000);
17   }
18
19   add_player(name, character) {
20     const new_player = {id: this.next_player_id,
21                        name: name,
22                        character: character,
23                        captures: [],
24                        };
25     this._players.push(new_player);
26     this.next_player_id++;
27     /* The syntax here is using an anonymous function to create a new
28       object from new_player with just the subset of fields that we
29       want. */
30     const player_data = JSON.stringify((({id, name}) => ({id, name}))(new_player));
31     this.broadcast_event("player-join", player_data);
32   }
33
34   remove_player(id) {
35     const index = this._players.findIndex(player => player.id === id);
36     this._players.splice(index, 1);
37
38     this.broadcast_event("player-leave", `{"id": ${id}}`);
39   }
40
41   remove_all_players() {
42     this._players = [];
43     this.next_player_id = 1;
44   }
45
46   capture(captor_id, captee_id) {
47     /* TODO: Fix to fail on already-captured players (or to move the
48      * captured player from an old captor to a new—need to clarify in
49      * the API specification which we want here. */
50     let captor = this._players.find(player => player.id === captor_id);
51     captor.captures.push(captee_id);
52
53     this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
54   }
55
56   liberate(captee_id) {
57     let captor = this._players.find(player => player.captures.includes(captee_id));
58     captor.captures.splice(captor.captures.indexOf(captee_id), 1);
59   }
60
61   restart() {
62     for (const player of this._players) {
63       player.captures = [];
64     }
65   }
66
67   get characters() {
68     return this._players.map(player => player.character);
69   }
70
71   get empires() {
72     return this._players.map(player => ({id: player.id, captures: player.captures}));
73   }
74
75   get players() {
76     return this._players.map(player => ({id: player.id, name: player.name }));
77   }
78
79   add_client(response) {
80     const id = this.next_client_id;
81     this.clients.push({id: id,
82                        response: response});
83     this.next_client_id++;
84
85     return id;
86   }
87
88   remove_client(id) {
89     this.clients = this.clients.filter(client => client.id !== id);
90   }
91
92   /* Send a string to all clients */
93   broadcast_string(str) {
94     this.clients.forEach(client => client.response.write(str + '\n'));
95   }
96
97   /* Send an event to all clients.
98    *
99    * An event has both a declared type and a separate data block.
100    * It also ends with two newlines (to mark the end of the event).
101    */
102   broadcast_event(type, data) {
103     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
104   }
105 }
106
107 const game = new Game();
108
109 app.use(body_parser.urlencoded({ extended: false }));
110 app.use(body_parser.json());
111
112 function handle_events(request, response) {
113   /* These headers will keep the connection open so we can stream events. */
114   const headers = {
115     "Content-type": "text/event-stream",
116     "Connection": "keep-alive",
117     "Cache-Control": "no-cache"
118   };
119   response.writeHead(200, headers);
120
121   /* Now that a client has connected, first we need to stream all of
122    * the existing players (if any). */
123   if (game._players.length > 0) {
124     const players_json = JSON.stringify(game.players);
125     const players_data = `event: players\ndata: ${players_json}\n\n`;
126     response.write(players_data);
127   }
128
129   /* Add this new client to our list of clients. */
130   const id = game.add_client(response);
131
132   /* And queue up cleanup to be triggered on client close. */
133   request.on('close', () => {
134     game.remove_client(id);
135   });
136 }
137
138 app.get('/', (request, response) => {
139   response.send('Hello World!');
140 });
141
142 app.post('/register', (request, response) => {
143   game.add_player(request.body.name, request.body.character);
144   response.send();
145 });
146
147 app.post('/deregister/:id', (request, response) => {
148   game.remove_player(parseInt(request.params.id));
149   response.send();
150 });
151
152 app.post('/reset', (request, response) => {
153   game.remove_all_players();
154   response.send();
155 });
156
157 app.post('/capture/:captor/:captee', (request, response) => {
158   game.capture(parseInt(request.params.captor), parseInt(request.params.captee));
159   response.send();
160 });
161
162 app.post('/liberate/:id', (request, response) => {
163   game.liberate(parseInt(request.params.id));
164   response.send();
165 });
166
167 app.post('/restart', (request, response) => {
168   game.restart(parseInt(request.params.id));
169     response.send();
170 });
171
172 app.get('/characters', (request, response) => {
173   response.send(game.characters);
174 });
175
176 app.get('/empires', (request, response) => {
177   response.send(game.empires);
178 });
179
180 app.get('/players', (request, response) => {
181   response.send(game.players);
182 });
183
184 app.get('/events', handle_events);
185
186 app.listen(3000, function () {
187   console.log('Empires server listening on localhost:3000');
188 });