]> git.cworth.org Git - lmno-server/blob - game.js
Stream player-enter events for existing players to a new player
[lmno-server] / game.js
1 /* A single player can have multiple connections, (think, multiple
2  * browser windows with a common session cookie). */
3 class Player {
4   constructor(id, session_id, name, connection) {
5     this.id = id;
6     this.session_id = session_id;
7     this.name = name;
8     this.connections = [connection];
9     this.team = "";
10   }
11
12   add_connection(connection) {
13     /* Don't add a duplicate connection if this player already has it. */
14     for (let c of this.connections) {
15       if (c === connection)
16         return;
17     }
18
19     this.connections.push(connection);
20   }
21
22   /* Returns the number of remaining connections after this one is removed. */
23   remove_connection(connection) {
24     this.connections.filter(c => c !== connection);
25     return this.connections.length;
26   }
27
28   /* Send a string to all connections for this player. */
29   send(data) {
30     this.connections.forEach(connection => connection.write(data));
31   }
32
33   info_json() {
34     return JSON.stringify({
35       id: this.id,
36       name: this.name,
37       team: this.team
38     });
39   }
40 }
41
42 /* Base class providing common code for game engine implementations. */
43 class Game {
44   constructor(id) {
45     this.id = id;
46     this.players = [];
47     this.players_by_session = {};
48     this.next_player_id = 1;
49     this.teams = [];
50     this.state = {
51       team_to_play: ""
52     };
53     this.first_move = true;
54
55     /* Send a comment to every connected client every 15 seconds. */
56     setInterval(() => {this.broadcast_string(":");}, 15000);
57   }
58
59   /* Suport for game meta-data.
60    *
61    * What we want here is an effectively static field that is
62    * accessible through either the class name (SomeGame.meta) or an
63    * instance (some_game.meta). To pull this off we do keep two copies
64    * of the data. But the game classes can just set SomeGame.meta once
65    * and then reference it either way.
66    */
67   static set meta(data) {
68     /* This allows class access (SomeGame.meta) via the get method below. */
69     this._meta = data;
70
71     /* While this allows access via an instance (some_game.meta). */
72     this.prototype.meta = data;
73   }
74
75   static get meta() {
76     return this._meta;
77   }
78
79   /* Just performs some checks for whether a move is definitely not
80    * legal (such as not the player's turn). A child class is expected
81    * to override this (and call super.add_move early!) to implement
82    * the actual logic for a move. */
83   add_move(player, move) {
84
85     /* The checks here don't apply on the first move. */
86     if (! this.first_move) {
87
88       /* Discard any move asserting to be the first move if it's no
89        * longer the first move. This resolves the race condition if
90        * multiple players attempt to make the first move. */
91       if (move.assert_first_move) {
92         return { legal: false,
93                  message: "Your opponent beat you to the first move" };
94       }
95
96       /* Cannot move if you are not on a team. */
97       if (player.team === "")
98       {
99         return { legal: false,
100                  message: "You must be on a team to take a turn" };
101       }
102
103       /* Cannot move if it's not this player's team's turn. */
104       if (player.team !== this.state.team_to_play)
105       {
106         return { legal: false,
107                  message: "It's not your turn to move" };
108       }
109     }
110
111     return { legal: true };
112   }
113
114   /* Assign team only if player is unassigned.
115    * Return true if assignment made, false otherwise. */
116   assign_player_to_team_perhaps(player, team)
117   {
118     if (player.team !== "")
119       return false;
120
121     player.team = team;
122     this.broadcast_event("player-update", player.info_json());
123
124     return true;
125   }
126
127   /* This function is called after the child add_move has returned
128    * 'result' so that any generic processing can happen.
129    *
130    * In particular, we assign teams for a two-player game where a
131    * player assumed a team by making the first move. */
132   post_move(player, result)
133   {
134     if (this.first_move && result.legal) {
135       this.first_move = false;
136
137       this.assign_player_to_team_perhaps(player, this.teams[0]);
138
139       /* Yes, start at 1 to skip teams[0] which we just assigned. */
140       for (let i = 1; i < this.teams.length; i++) {
141         const other = this.players.find(p => p !== player && p.team === "");
142         if (!other)
143           return;
144         this.assign_player_to_team_perhaps(other, this.teams[i]);
145       }
146     }
147   }
148
149   add_player(session, connection) {
150     /* First see if we already have a player object for this session. */
151     const existing = this.players_by_session[session.id];
152     if (existing) {
153       existing.add_connection(connection);
154       return existing;
155     }
156
157     /* No existing player. Add a new one. */
158     const id = this.next_player_id;
159     const player = new Player(id, session.id, session.nickname, connection);
160
161     /* Broadcast before adding player to list (to avoid announcing the
162      * new player to itself). */
163     const player_data = JSON.stringify({ id: player.id, name: player.name });
164     this.broadcast_event("player-enter", player_data);
165
166     this.players.push(player);
167     this.players_by_session[session.id] = player;
168     this.next_player_id++;
169
170     return player;
171   }
172
173   /* Drop a connection object from a player, and if it's the last one,
174    * then drop that player from the game's list of players. */
175   remove_player_connection(player, connection) {
176     const remaining = player.remove_connection(connection);
177     if (remaining === 0) {
178       const player_data = JSON.stringify({ id: player.id });
179       this.players.filter(p => p !== player);
180       delete this.players_by_session[player.session_id];
181       this.broadcast_event("player-exit", player_data);
182     }
183   }
184
185   /* Send a string to all players */
186   broadcast_string(str) {
187     this.players.forEach(player => player.send(str + '\n'));
188   }
189
190   /* Send an event to all players.
191    *
192    * An event has both a declared type and a separate data block.
193    * It also ends with two newlines (to mark the end of the event).
194    */
195   broadcast_event(type, data) {
196     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
197   }
198
199   handle_events(request, response) {
200     /* These headers will keep the connection open so we can stream events. */
201     const headers = {
202       "Content-type": "text/event-stream",
203       "Connection": "keep-alive",
204       "Cache-Control": "no-cache"
205     };
206     response.writeHead(200, headers);
207
208     /* Add this new player. */
209     const player = this.add_player(request.session, response);
210
211     /* And queue up cleanup to be triggered on client close. */
212     request.on('close', () => {
213       this.remove_player_connection(player, response);
214     });
215
216     /* Give the client the game-info event. */
217     const game_info_json = JSON.stringify({
218       id: this.id,
219       url: `${request.protocol}://${request.hostname}/${this.id}`
220     });
221     response.write(`event: game-info\ndata: ${game_info_json}\n\n`);
222
223     /* And the player-info event. */
224     response.write(`event: player-info\ndata: ${player.info_json()}\n\n`);
225
226     /* As well as player-enter events for all existing players. */
227     this.players.filter(p => p !== player).forEach(p => {
228       response.write(`event: player-enter\ndata: ${p.info_json()}\n\n`);
229     });
230
231     /* Finally, if this game class has a "state" property, stream that
232      * current state to the client. */
233     if (this.state) {
234       const state_json = JSON.stringify(this.state);
235       response.write(`event: game-state\ndata: ${state_json}\n\n`);
236     }
237   }
238
239   handle_player(request, response) {
240     const player = this.players_by_session[request.session.id];
241     const name = request.body.name;
242     const team = request.body.team;
243     var updated = false;
244     if (! player) {
245       response.sendStatus(404);
246       return;
247     }
248
249     if (name && (player.name !== name)) {
250       player.name = name;
251
252       /* In addition to setting the name within this game's player
253        * object, also set the name in the session. */
254       request.session.nickname = name;
255       request.session.save();
256
257       updated = true;
258     }
259
260     if (team !== null && (player.team !== team) &&
261         (team === "" || this.teams.includes(team)))
262     {
263       player.team = team;
264
265       updated = true;
266     }
267
268     if (updated)
269       this.broadcast_event("player-update", player.info_json());
270
271     response.send("");
272   }
273
274   broadcast_move(move) {
275     this.broadcast_event("move", move);
276   }
277
278 }
279
280 module.exports = Game;