]> git.cworth.org Git - lmno-server/blob - game.js
Move the keepalive functionality from Empires up to Game
[lmno-server] / game.js
1 /* Base class providing common code for game engine implementations. */
2 class Game {
3   constructor(id) {
4     this.id = id;
5     this.clients = [];
6     this.next_client_id = 1;
7
8     /* Send a comment to every connected client every 15 seconds. */
9     setInterval(() => {this.broadcast_string(":");}, 15000);
10   }
11
12   /* Suport for game meta-data.
13    *
14    * What we want here is an effectively static field that is
15    * accessible through either the class name (SomeGame.meta) or an
16    * instance (some_game.meta). To pull this off we do keep two copies
17    * of the data. But the game classes can just set SomeGame.meta once
18    * and then reference it either way.
19    */
20   static set meta(data) {
21     /* This allows class access (SomeGame.meta) via the get method below. */
22     this._meta = data;
23
24     /* While this allows access via an instance (some_game.meta). */
25     this.prototype.meta = data;
26   }
27
28   static get meta() {
29     return this._meta;
30   }
31
32   add_client(response) {
33     const id = this.next_client_id;
34     this.clients.push({id: id,
35                        response: response});
36     this.next_client_id++;
37
38     return id;
39   }
40
41   remove_client(id) {
42     this.clients = this.clients.filter(client => client.id !== id);
43   }
44
45   /* Send a string to all clients */
46   broadcast_string(str) {
47     this.clients.forEach(client => client.response.write(str + '\n'));
48   }
49
50   /* Send an event to all clients.
51    *
52    * An event has both a declared type and a separate data block.
53    * It also ends with two newlines (to mark the end of the event).
54    */
55   broadcast_event(type, data) {
56     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
57   }
58
59   handle_events(request, response) {
60     /* These headers will keep the connection open so we can stream events. */
61     const headers = {
62       "Content-type": "text/event-stream",
63       "Connection": "keep-alive",
64       "Cache-Control": "no-cache"
65     };
66     response.writeHead(200, headers);
67
68     /* Add this new client to our list of clients. */
69     const id = this.add_client(response);
70
71     /* And queue up cleanup to be triggered on client close. */
72     request.on('close', () => {
73       this.remove_client(id);
74     });
75
76     /* Finally, if this game class has a "state" property, stream that
77      * current state to the client. */
78     if (this.state) {
79       const state_json = JSON.stringify(this.state);
80       response.write(`event: game-state\ndata: ${state_json}\n\n`);
81     }
82   }
83
84   broadcast_move(move) {
85     this.broadcast_event("move", move);
86   }
87
88 }
89
90 module.exports = Game;