forked from sirDonovan/Cassius
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrooms.js
139 lines (124 loc) · 2.52 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/**
* Rooms
* Cassius - https://github.com/sirDonovan/Cassius
*
* This file tracks information about the rooms that the bot joins.
*
* @license MIT license
*/
'use strict';
const Game = require('./games').Game; // eslint-disable-line no-unused-vars
const User = require('./users').User; // eslint-disable-line no-unused-vars
class Room {
/**
* @param {string} id
*/
constructor(id) {
this.id = id;
this.clientId = id === 'lobby' ? '' : id;
/**@type {Map<User, string>} */
this.users = new Map();
/**@type {{[k: string]: Function}} */
this.listeners = {};
/**@type {?Game} */
this.game = null;
}
/**
* @param {User} user
* @param {string} rank
*/
onJoin(user, rank) {
this.users.set(user, rank);
user.rooms.set(this, rank);
}
/**
* @param {User} user
*/
onLeave(user) {
this.users.delete(user);
user.rooms.delete(this);
}
/**
* @param {User} user
* @param {string} newName
*/
onRename(user, newName) {
let rank = newName.charAt(0);
newName = Tools.toName(newName);
let id = Tools.toId(newName);
let oldName = user.name;
if (id === user.id) {
user.name = newName;
} else {
delete Users.users[user.id];
if (Users.users[id]) {
user = Users.users[id];
user.name = newName;
} else {
user.name = newName;
user.id = id;
Users.users[id] = user;
}
}
this.users.set(user, rank);
user.rooms.set(this, rank);
if (this.game) this.game.renamePlayer(user, oldName);
}
/**
* @param {string} message
*/
say(message) {
message = Tools.normalizeMessage(message, this);
if (!message) return;
Client.send(this.clientId + '|' + message);
}
/**
* @param {string} message
* @param {Function} listener
*/
on(message, listener) {
message = Tools.normalizeMessage(message, this);
if (!message) return;
this.listeners[Tools.toId(message)] = listener;
}
}
exports.Room = Room;
class Rooms {
constructor() {
this.rooms = {};
this.Room = Room;
this.globalRoom = this.add('global');
}
/**
* @param {Room | string} id
* @return {Room}
*/
get(id) {
if (id instanceof Room) return id;
return this.rooms[id];
}
/**
* @param {string} id
* @return {Room}
*/
add(id) {
let room = this.get(id);
if (!room) {
room = new Room(id);
this.rooms[id] = room;
}
return room;
}
/**
* @param {Room | string} id
*/
destroy(id) {
let room = this.get(id);
if (!room) return;
room.users.forEach(function (value, user) {
user.rooms.delete(room);
});
delete this.rooms[room.id];
}
}
exports.Rooms = new Rooms();