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