-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroom.js
64 lines (53 loc) · 1.57 KB
/
room.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const sanitizer = require('sanitizer');
class Room {
constructor (id, game, options) {
this.id = id;
this.game = game;
this.options = options;
this.sockets = [];
}
join (socket) {
this.setUniqueName(socket.player);
this.sockets.push(socket);
this.status(socket.player, 'joined');
};
leave (socket) {
const index = this.sockets.indexOf(socket);
if (index !== -1) {
this.sockets.splice(index, 1);
this.status(socket.player, 'left');
}
};
chat (player, msg) {
this.broadcast('chat-message', { player: player, message: sanitizer.sanitize(msg).substr(0, 255) });
};
status (player, msg) {
this.broadcast('chat-status', { player: player, message: msg });
};
sync () {
let state = this.game.getState();
state.connected = this.sockets.length;
this.broadcast('state', state);
};
broadcast (key, data) {
this.sockets.forEach(function (socket) {
socket.emit(key, data);
});
};
setUniqueName (player) {
let suggestedName = player.name;
let unique = false;
let index = 2;
do {
this.sockets.forEach(function (socket) {
if (socket.player.name === suggestedName) {
suggestedName = player.name + ' (' + index + ')';
index++;
}
});
unique = true;
} while (!unique);
player.name = suggestedName;
};
}
module.exports = Room;