-
Notifications
You must be signed in to change notification settings - Fork 0
/
rooms.js
102 lines (86 loc) · 2.12 KB
/
rooms.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const Room = require("./room");
class Rooms {
constructor() {
this.rooms = [];
}
handleMeesage(message, connection) {
if (typeof message === "string") {
const { event, data } = JSON.parse(message);
const eventListener = `on${
event.charAt(0).toUpperCase() + event.slice(1)
}`;
if (typeof this[eventListener] === "function") {
this[eventListener](data, connection);
}
// Also call event if it exists in room.
this.rooms.forEach((r) => {
if (
data.room &&
data.room.id === r.id &&
typeof r[eventListener] === "function"
) {
r[eventListener]({ eventListener, data }, connection);
}
});
}
}
handleClose(connection) {
this.onDisconnect(connection);
}
handleError(connection) {
console.log("error");
}
onCreateRoom({ name }, connection) {
if (this.rooms.find((r) => r.name === name)) {
throw new Error(`Room with name ${name} is exists!`);
}
const room = new Room({ name });
// Init Games State Machine
room.initStateMachine();
room.joinRoom(connection);
this.rooms = [...this.rooms, room];
const event = {
event: "roomsList",
data: {
rooms: this.rooms.map((r) => ({
id: r.id,
name: r.name,
})),
},
};
connection.broadcastAll(JSON.stringify(event));
}
onJoinRoom({ id }, connection) {
this.isRoomExists({ id });
this.rooms = this.rooms.map((r) => {
if (r.id === id) {
r.joinRoom(connection);
}
return r;
});
}
onDisconnect(connection) {
console.log({
status: "disconnected",
id: connection.id,
});
this.rooms = this.rooms.map((r) => {
r.players = r.players.map((p) => {
if (p.connection && p.connection.id === connection.id) {
p.connection = null;
}
return p;
});
return r;
});
}
isRoomExists({ id }) {
if (!this.rooms.find((r) => r.id === id)) {
throw new Error("Room not found!");
}
}
list() {
return this.rooms;
}
}
module.exports = Rooms;