-
Notifications
You must be signed in to change notification settings - Fork 0
/
Room.cpp
106 lines (101 loc) · 2.32 KB
/
Room.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
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
#include "Room.h"
#include "User.h"
#include "Helper.h"
#include "Protocol.h"
using namespace std;
Room::Room(int id, User* admin, string name, int max_users, int question_num, int question_time){
_admin = admin;
_name = name;
_id = id;
_max_users = max_users;
_time_for_question = question_time;
_num_of_question = question_num;
}
string Room::get_users_as_string(vector<User*> user_list, User* excluded_user){
string str;
for (vector<User*>::iterator it = _users.begin(); it != _users.end(); ++it){
if (excluded_user != *it){
str.append((*it)->get_user_name());
}
}
return str;
}
bool Room::join_room(User* user){
string str;
string str2;
if (_users.size < _max_users){
_users.push_back(user);
str.append(RES_JOIN_ROOM);
str.append(Helper::getPaddedNumber(_num_of_question, 2));
str.append(Helper::getPaddedNumber(_time_for_question, 2));
(*user).send(str);
str2 = get_users_messages_list();
sendMessage(str2);
}
else{
(*user).send(RES_JOIN_ROOM_FAIL);
return false;
}
}
void Room::leave_room(User* user){
string str;
for (vector<User*>::iterator it = _users.begin(),int i =0; it != _users.end(); ++it,i++){
if (user == *it){
_users.erase(_users.begin() + i);
}
}
str = get_users_messages_list();
sendMessage(user, str);
}
int Room::close_room(User* user){
if (user != _admin){
return -1;
}
sendMessage(RES_CLOSE_ROOM);
for (vector<User*>::iterator it = _users.begin(); it != _users.end(); ++it) {
if(*it != _admin)
(*it)->clear_room();
}
}
vector<User*> Room::get_users(){
return _users;
}
string Room::get_users_messages_list(){
string str;
string name;
int value;
string value_;
if (_users.size() > 0){
str.append(RES_USERS_LIST);
for (vector<User*>::iterator it = _users.begin(); it != _users.end(); ++it){
name = (*it)->get_user_name();
value = name.length();
value_ = Helper::getPaddedNumber(value, 2);
str.append(value_);
str.append(name);
}
return str;
}
else{
return RES_USERS_LIST_FAIL;
}
}
int Room::get_id(){
return _id;
}
string Room::get_name(){
return _name;
}
int Room::get_question_no(){
return _num_of_question;
}
void Room::sendMessage(string str){
sendMessage(NULL, str);
}
void Room::sendMessage(User* user, string str){
for (vector<User*>::iterator it = _users.begin(); it != _users.end(); ++it){
if (user != *it){
(*it)->send(str);
}
}
}