1 /* A single player can have multiple connections, (think, multiple
2 * browser windows with a common session cookie). */
4 constructor(id, name, connection) {
7 this.connections = [connection];
11 add_connection(connection) {
12 /* Don't add a duplicate connection if this player already has it. */
13 for (let c of this.connections) {
18 this.connections.push(connection);
21 /* Returns the number of remaining connections after this one is removed. */
22 remove_connection(connection) {
23 this.connections.filter(c => c !== connection);
24 return this.connections.length;
27 /* Send a string to all connections for this player. */
29 this.connections.forEach(connection => connection.write(data));
33 return JSON.stringify({
41 /* Base class providing common code for game engine implementations. */
46 this.next_player_id = 1;
52 /* Send a comment to every connected client every 15 seconds. */
53 setInterval(() => {this.broadcast_string(":");}, 15000);
56 /* Suport for game meta-data.
58 * What we want here is an effectively static field that is
59 * accessible through either the class name (SomeGame.meta) or an
60 * instance (some_game.meta). To pull this off we do keep two copies
61 * of the data. But the game classes can just set SomeGame.meta once
62 * and then reference it either way.
64 static set meta(data) {
65 /* This allows class access (SomeGame.meta) via the get method below. */
68 /* While this allows access via an instance (some_game.meta). */
69 this.prototype.meta = data;
76 /* Just performs some checks for whether a move is definitely not
77 * legal (such as not the player's turn). A child class is expected
78 * to override this (and call super.add_move early!) to implement
79 * the actual logic for a move. */
80 add_move(player, move) {
81 /* Cannot move if you are not on a team. */
82 if (player.team === "")
84 return { legal: false,
85 message: "You must be on a team to take a turn" };
88 /* Cannot move if it's not this player's team's turn. */
89 if (player.team !== this.state.team_to_play)
91 return { legal: false,
92 message: "It's not your turn to move" };
95 return { legal: true };
98 add_player(session, connection) {
99 /* First see if we already have a player object for this session. */
100 const existing = this.players[session.id];
102 existing.add_connection(connection);
106 /* No existing player. Add a new one. */
107 const id = this.next_player_id;
108 const player = new Player(id, session.nickname, connection);
110 /* Broadcast before adding player to list (to avoid announcing the
111 * new player to itself). */
112 const player_data = JSON.stringify({ id: player.id, name: player.name });
113 this.broadcast_event("player-enter", player_data);
115 this.players[session.id] = player;
116 this.next_player_id++;
121 /* Drop a connection object from a player, and if it's the last one,
122 * then drop that player from the game's list of players. */
123 remove_player_connection(player, connection) {
124 const remaining = player.remove_connection(connection);
125 if (remaining === 0) {
126 const player_data = JSON.stringify({ id: player.id });
127 this.players.filter(p => p !== player);
128 this.broadcast_event("player-exit", player_data);
132 /* Send a string to all players */
133 broadcast_string(str) {
134 for (let [session_id, player] of Object.entries(this.players))
135 player.send(str + '\n');
138 /* Send an event to all players.
140 * An event has both a declared type and a separate data block.
141 * It also ends with two newlines (to mark the end of the event).
143 broadcast_event(type, data) {
144 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
147 handle_events(request, response) {
148 /* These headers will keep the connection open so we can stream events. */
150 "Content-type": "text/event-stream",
151 "Connection": "keep-alive",
152 "Cache-Control": "no-cache"
154 response.writeHead(200, headers);
156 /* Add this new player. */
157 const player = this.add_player(request.session, response);
159 /* And queue up cleanup to be triggered on client close. */
160 request.on('close', () => {
161 this.remove_player_connection(player, response);
164 /* Give the client the game-info event. */
165 const game_info_json = JSON.stringify({
167 url: `${request.protocol}://${request.hostname}/${this.id}`
169 response.write(`event: game-info\ndata: ${game_info_json}\n\n`);
171 /* And the player-info event. */
172 response.write(`event: player-info\ndata: ${player.info_json()}\n\n`);
174 /* Finally, if this game class has a "state" property, stream that
175 * current state to the client. */
177 const state_json = JSON.stringify(this.state);
178 response.write(`event: game-state\ndata: ${state_json}\n\n`);
182 handle_player(request, response) {
183 const player = this.players[request.session.id];
184 const name = request.body.name;
185 const team = request.body.team;
188 response.sendStatus(404);
192 if (name && (player.name !== name)) {
195 /* In addition to setting the name within this game's player
196 * object, also set the name in the session. */
197 request.session.nickname = name;
198 request.session.save();
203 if (team !== null && (player.team !== team) &&
204 (team === "" || this.teams.includes(team)))
212 this.broadcast_event("player-update", player.info_json());
217 broadcast_move(move) {
218 this.broadcast_event("move", move);
223 module.exports = Game;