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