]> git.cworth.org Git - lmno-server/blob - game.js
Put add_client/remove_client and the various broadcast functions into Game
[lmno-server] / game.js
1 /* Base class providing common code for game engine implementations. */
2 class Game {
3   constructor(name) {
4     this.name = name;
5     this.clients = [];
6     this.next_client_id = 1;
7   }
8
9   add_client(response) {
10     const id = this.next_client_id;
11     this.clients.push({id: id,
12                        response: response});
13     this.next_client_id++;
14
15     return id;
16   }
17
18   remove_client(id) {
19     this.clients = this.clients.filter(client => client.id !== id);
20   }
21
22   /* Send a string to all clients */
23   broadcast_string(str) {
24     this.clients.forEach(client => client.response.write(str + '\n'));
25   }
26
27   /* Send an event to all clients.
28    *
29    * An event has both a declared type and a separate data block.
30    * It also ends with two newlines (to mark the end of the event).
31    */
32   broadcast_event(type, data) {
33     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
34   }
35
36 }
37
38 module.exports = Game;