1 | var EventEmitter = require('events');
|
2 |
|
3 | var Player = function(id) {
|
4 | var that = new EventEmitter();
|
5 |
|
6 |
|
7 | var debug = require('debug')('space-dud:Player#'+id);
|
8 | var consumer_clients = [];
|
9 | var controller_client = null;
|
10 |
|
11 | debug('Created a new Player.');
|
12 |
|
13 |
|
14 | function removeConsumerClient(client) {
|
15 | debug('Removing consumer client');
|
16 |
|
17 | var index = consumer_clients.indexOf(client);
|
18 | if(index !== -1) {
|
19 | consumer_clients.splice(index, 1);
|
20 | }
|
21 | };
|
22 |
|
23 |
|
24 | that.getId = function() {
|
25 | return id;
|
26 | };
|
27 |
|
28 | that.addConsumerClient = function(client) {
|
29 | debug('Added a consumer client.');
|
30 | var client_id = consumer_clients.push(client) - 1;
|
31 |
|
32 | client.on('disconnect', function() {
|
33 | removeConsumerClient(client);
|
34 | });
|
35 |
|
36 | that.emit('consumer_added', client_id);
|
37 | return that;
|
38 | }
|
39 |
|
40 | that.numConsumerClients = function() {
|
41 | return consumer_clients.length;
|
42 | };
|
43 |
|
44 | that.clearConsumerClients = function() {
|
45 | consumer_clients = [];
|
46 | return that;
|
47 | };
|
48 |
|
49 | that.sendEventToConsumers = function(new_event) {
|
50 | for(var i=0; i<consumer_clients.length; i++) {
|
51 | consumer_clients[i].consume(new_event);
|
52 | }
|
53 |
|
54 | return that;
|
55 | };
|
56 |
|
57 | that.sendEventToConsumer = function(new_event, client_id) {
|
58 | if(client_id < consumer_clients.length) {
|
59 | consumer_clients[client_id].consume(new_event);
|
60 | }
|
61 | };
|
62 |
|
63 | that.setControllerClient = function(client) {
|
64 | debug('Connected a controller client.');
|
65 |
|
66 | controller_client = client;
|
67 |
|
68 | controller_client.on('controller_event', function(...args) {
|
69 | that.emit('controller_event', ...args);
|
70 | });
|
71 |
|
72 | controller_client.on('disconnect', function(...args) {
|
73 | that.emit('disconnect', ...args);
|
74 | });
|
75 |
|
76 | controller_client.dumpState();
|
77 |
|
78 | return that;
|
79 | }
|
80 |
|
81 | that.hasControllerClient = function() {
|
82 | return (controller_client != null);
|
83 | };
|
84 |
|
85 | return that;
|
86 | };
|
87 |
|
88 | module.exports = Player;
|