-const express = require("express")
-const cors = require("cors")
+const express = require("express");
+const cors = require("cors");
const body_parser = require("body-parser");
const app = express();
-app.use(cors())
+app.use(cors());
class Game {
constructor() {
this._players = [];
this.next_player_id = 1;
+ this.clients = [];
+ this.next_client_id = 1;
}
add_player(name, character) {
- this._players.push({id: this.next_player_id,
+ const new_player = {id: this.next_player_id,
name: name,
character: character,
captures: [],
- })
+ };
+ this._players.push(new_player);
this.next_player_id++;
+ /* The syntax here is using an anonymous function to create a new
+ object from new_player with just the subset of fields that we
+ want. */
+ const player_string = JSON.stringify((({id, name}) => ({id, name}))(new_player));
+ this.broadcast_event("player-register", player_string);
}
remove_player(id) {
const index = this._players.findIndex(player => player.id === id);
this._players.splice(index, 1);
+
+ this.broadcast_event("player-deregister", `{"id": ${id}}`);
}
remove_all_players() {
* the API specification which we want here. */
let captor = this._players.find(player => player.id === captor_id);
captor.captures.push(captee_id);
+
+ this.broadcast_event("capture", `{"captor": ${captor_id}, "captee": ${captee_id}}`);
}
liberate(captee_id) {
get players() {
return this._players.map(player => ({id: player.id, name: player.name }));
}
+
+ add_client(response) {
+ const id = this.next_client_id;
+ this.clients.push({id: id,
+ response: response});
+ this.next_client_id++;
+
+ return id;
+ }
+
+ remove_client(id) {
+ this.clients = this.clients.filter(client => client.id !== id);
+ }
+
+ /* Send a string to all clients */
+ broadcast_string(str) {
+ this.clients.forEach(client => client.response.write(str + '\n'));
+ }
+
+ /* Send an event to all clients.
+ *
+ * An event has both a declared type and a separate data block.
+ * It also ends with two newlines (to mark the end of the event).
+ */
+ broadcast_event(type, data) {
+ this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
+ }
}
-game = new Game();
+const game = new Game();
app.use(body_parser.urlencoded({ extended: false }));
app.use(body_parser.json());
+function handle_events(request, response) {
+ /* These headers will keep the connection open so we can stream events. */
+ const headers = {
+ "Content-type": "text/event-stream",
+ "Connection": "keep-alive",
+ "Cache-Control": "no-cache"
+ };
+ response.writeHead(200, headers);
+
+ /* Now that a client has connected, first we need to stream all of
+ * the existing players (if any). */
+ if (game._players.length > 0) {
+ const players_json = JSON.stringify(game.players);
+ const players_data = `event: players\ndata: ${players_json}\n\n`;
+ response.write(players_data);
+ }
+
+ /* Add this new client to our list of clients. */
+ const id = game.add_client(response);
+
+ /* And queue up cleanup to be triggered on client close. */
+ request.on('close', () => {
+ game.remove_client(id);
+ });
+}
+
app.get('/', (request, response) => {
response.send('Hello World!');
});
response.send(game.players);
});
+app.get('/events', handle_events);
+
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});