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