-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoomManager.cpp
69 lines (63 loc) · 1.94 KB
/
RoomManager.cpp
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
#include"RoomManager.h"
#include <unistd.h>
RoomManager::RoomManager() : RoomId(1) {}
Room* RoomManager::createRoom(std::string name) {
Room* newRoom=new Room("Room" + to_string(++RoomId)+"-"+name );
rooms.push_back(newRoom);
return newRoom;
}
Room* RoomManager::getRoomByName(std::string name) {
for (auto room : rooms) {
if (room->getName() == name) {
return room;
}
}
return nullptr;
}
void RoomManager::joinRoom(Room* room, User* user) {
room->addUser(user);
// 当玩家加入房间时通知房间内其他玩家刷新房间
for (auto otherUser : room->getUsers())
{
if (otherUser->getId() != user->getId())
{
string temp = showRooms();
write(otherUser->getId(),
temp.c_str(), temp.size() + 4);
}
}
}
void RoomManager::leaveRoom(User* user) {
Room* room = user->getRoom();
if (room) {
room->removeUser(user);
// 当玩家离开房间时通知房间内其他玩家刷新房间
for (auto otherUser : room->getUsers())
{
if (otherUser->getId() != user->getId())
{
string temp = showRooms();
write(otherUser->getId(),
temp.c_str(), temp.size() + 4);
}
}
}
}
std::string RoomManager::showRooms() {
std::string result;
for (auto it = rooms.begin(); it != rooms.end(); it++) {
// 房间名被标记为空时,证明这个房间不再需要
if ((*it)->getName() == "")
{
delete* it;
rooms.erase(it);
// bugfix:如果删除的是最后一个房间,就会跳转到非法区域
if (it == rooms.end()) break;
}
}
// 删除和遍历不要放到一起
for (auto it = rooms.begin(); it != rooms.end(); it++) {
result += (*it)->getName() + ": " + (*it)->showUsers() + "\n";
}
return result;
}