-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhost.cpp
328 lines (291 loc) · 11.7 KB
/
host.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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#include "host.hpp"
using namespace std;
bool isInteger(const string &str) {
if (str.empty() || !all_of(str.begin(), str.end(), ::isdigit)) {
return false;
};
return true;
}
vector<string> splitString(const string &str) {
vector<string> words;
istringstream iss(str);
string word;
while (iss >> word) {
words.push_back(word);
}
return words;
}
string blockingReceive(int sock) {
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
int bytesReceived = recv(sock, buffer, sizeof(buffer), 0);
if (bytesReceived == -1) {
cerr << "Error in recv()." << endl;
} else if (bytesReceived == 0) {
cout << "Connection closed by the server." << endl;
} else {
string message = string(buffer, bytesReceived);
cout << "Message received: " << message << endl;
return message;
}
return "";
}
pair<string, string> splitFirstTwoTerms(const string& str) {
pair<string, string> result {"", ""};
size_t pos = str.find('x');
if (pos != std::string::npos) {
result.first = str.substr(0, pos);
if (pos + 1 < str.size()) {
result.second = str.substr(pos + 1);
}
}
return result;
}
// make more efficient – can convert to hashing and O(1) switch statements, code can also look better by grouping parsing
bool handleCommand(Game* game, int player, vector<string> args, bool firstTurn) {
string command = args[0];
bool result = false;
int numArgs = args.size() - 1;
if (integerCommands.count(command) && all_of(next(args.begin()), args.end(), isInteger) && numArgs == 2) {
int arg1 = stoi(args[1]), arg2 = stoi(args[2]);
if (command == "road") {
result = game->placeRoad(player, arg1, arg2, firstTurn);
} else if (command == "settlement") {
result = game->placeSettlement(player, arg1, arg2, firstTurn);
} else if (command == "city") {
result = game->upgradeSettlement(player, arg1, arg2);
} else if (command == "robber") {
result = game->moveRobber(player, arg1, arg2, firstTurn);
} else if (command == "knight") {
result = game->useKnight(player, arg1, arg2);
}
} else if (stringCommands.count(command)) {
if (command == "buyDev" && numArgs == 0) {
result = game->buyDevelopmentCard(player);
} else if (command == "monopoly" && numArgs == 1) {
Resource res = parseResource(args[1]);
if (res != Resource::Sand) {
result = game->useMonopoly(player, res);
}
} else if (command == "yearofplenty" && numArgs == 2) {
Resource res1 = parseResource(args[1]);
Resource res2 = parseResource(args[2]);
if (res1 != Resource::Sand && res2 != Resource::Sand) {
result = game->useYearOfPlenty(player, res1, res2);
}
} else if (command == "discard") {
unordered_map<Resource, int> discards;
for (int i = 1; i < args.size(); i++) {
pair<string, string> splitTerms = splitFirstTwoTerms(args[i]);
Resource res = parseResource(splitTerms.first);
if (res != Resource::Sand && isInteger(splitTerms.second)) {
discards[res] = stoi(splitTerms.second);
}
}
result = game->discardCardsOverLimit(player, discards);
} else if (command == "trade") {
Resource res1 = parseResource(args[1]);
Resource res2 = parseResource(args[2]);
if (res1 != Resource::Sand && res2 != Resource::Sand) {
result = game->bankTrade(player, res1, res2);
}
}
}
cout << "Called handle command. Result: " << result << endl;
return result;
}
void untilValid(Game* game, blockingQueue<pair<int, string>>* moveQueue, int player, string command, bool firstTurn) {
while (true) {
pair<int, string> message = moveQueue->pop();
if (message.first == player) {
vector<string> args = splitString(message.second);
if ((command == "" || args[0] == command) && handleCommand(game, player, args, firstTurn)) {
break;
}
}
}
}
void handlePlayerThread(int sock, int playerArg, bool* waitingForPlayers, bool* isSessionActive, blockingQueue<pair<int, string>>* moveQueue) {
int player = playerArg;
while (*isSessionActive) {
string message = blockingReceive(sock);
if (!message.empty()) {
if (*waitingForPlayers && message == "start") {
cout << "Ending loading." << endl;
*waitingForPlayers = false;
cv.notify_one();
} else {
moveQueue->push(pair<int, string> {player, message});
}
} else {
return;
}
}
return;
}
void handleConnectionsThread(int server_fd, sockaddr_in* address, vector<pair<int, int>>* sockAddrs, Game* game, bool* waitingForPlayers, bool* isSessionActive, blockingQueue<pair<int, string>>* moveQueue) {
int addrlen = sizeof(*address);
while (*isSessionActive && *waitingForPlayers) {
int sock = accept(server_fd, (struct sockaddr *)address, (socklen_t*)&addrlen);
if (sock < 0) {
cerr << "Accept failed" << endl;
close(server_fd);
continue;
}
int userNum = game->addUser();
if (userNum != -1) {
cout << "Connection Accepted. Player: " << userNum << endl;
sockAddrs->push_back(pair<int, int> {userNum, sock});
thread(handlePlayerThread, sock, userNum, waitingForPlayers, isSessionActive, moveQueue).detach();
} else {
cout << "Connection Rejected." << endl;
}
}
return;
}
void broadcastNewBoards(Game* game, vector<pair<int, int>>& sockPairs, int rollNum, int playerNum) {
// Not sure if threads can be left detached
for (const auto& sockPair : sockPairs) {
int player = sockPair.first, sock = sockPair.second;
string turn = "Turn – Player " + to_string(playerNum);
string roll = rollNum == -1 ? "" : " Roll: " + to_string(rollNum);
string board = game->printGameState(player) + "\n\n" + turn + roll + "\n";
int boardSize = board.size();
thread([board,boardSize](int sock){ write(sock, board.c_str(), boardSize); return; }, sock).detach();
}
}
int main(int argc, char** argv) {
// Sanity Checks
if (argc != 2) {
cerr << "Incorrect arguments provided." << endl;
return -1;
}
string arg1 = argv[1];
if (arg1.empty() || !all_of(arg1.begin(), arg1.end(), ::isdigit)) {
cerr << "Invalid port number." << endl;
return -1;
};
int port = stoi(arg1);
// Create a Socket
int server_fd;
struct sockaddr_in address;
int opt = 1;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
cerr << "Failed to create socket." << endl;
close(server_fd);
return -1;
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
cerr << "Can't set sock opt." << endl;
return -1;
}
// Bind to Port
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (::bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
cerr << "Failed to bind socket." << endl;
close(server_fd);
return -1;
}
cout << "Binded" << endl;
// Listen For Connections
if (listen(server_fd, 4) < 0) {
cerr << "Could not listen." << endl;
close(server_fd);
return -1;
}
cout << "Listening" << endl;
// Initiate Game Logic
Game game {};
blockingQueue<pair<int, string>> moveQueue;
// Accept New Connections Thread
bool isSessionActive = true;
bool waitingForPlayers = true;
vector<pair<int, int>> sockAddrs;
// Launch New Connections Thread & Wait Until Start Message Received
thread connectionsThread(handleConnectionsThread, server_fd, &address, &sockAddrs, &game, &waitingForPlayers, &isSessionActive, &moveQueue);
unique_lock<mutex> lock(cv_m);
cv.wait(lock, [&]{ return !waitingForPlayers; });
// Start Game
game.startGame();
cout << "Game starting." << endl;
// Handle Game Turns
// First Turn
vector<int> playerOrder = game.getPlayerOrder();
vector<int> extendedPlayerOrder(playerOrder.size() * 2);
copy(playerOrder.begin(), playerOrder.end(), extendedPlayerOrder.begin());
reverse_copy(playerOrder.begin(), playerOrder.end(), extendedPlayerOrder.begin() + playerOrder.size());
for (auto player : extendedPlayerOrder) {
broadcastNewBoards(&game, sockAddrs, -1, player);
// Wait Until Valid Place Settlement
untilValid(&game, &moveQueue, player, "settlement", true);
broadcastNewBoards(&game, sockAddrs, -1, player);
// Wait Until Valid Place Road
untilValid(&game, &moveQueue, player, "road", true);
broadcastNewBoards(&game, sockAddrs, -1, player);
}
// Subsequent Turns
while (isSessionActive) {
// Get Turn Information
int currentTurn = game.getTurn();
int player = game.currentTurnPlayer();
int roll = game.rollDice();
broadcastNewBoards(&game, sockAddrs, roll, player);
// Handle Dice Roll 7 Special Case
if (roll == 7) {
// Wait Until Valid Move Robber
untilValid(&game, &moveQueue, player, "robber", true);
broadcastNewBoards(&game, sockAddrs, roll, player);
// Wait Until Valid Remove Cards from All Players
vector<bool> hasDiscarded = game.playersUnderLimit();
while (!all_of(hasDiscarded.begin(), hasDiscarded.end(), [](bool discarded) {return discarded;})) {
pair<int, string> message = moveQueue.pop();
int messagePlayer = message.first;
vector<string> args = splitString(message.second);
string command = args[0];
if (command == "discard" && handleCommand(&game, player, args, false)) {
hasDiscarded[player] = true;
}
}
broadcastNewBoards(&game, sockAddrs, roll, player);
} else {
game.updateResourceCountsFromRoll(roll);
broadcastNewBoards(&game, sockAddrs, roll, player);
}
// Handle Normal Commands
while (true) {
pair<int, string> message = moveQueue.pop();
if (message.first == player) {
vector<string> args = splitString(message.second);
if (args.size() > 0 && args[0] == "done") {
break;
}
if (handleCommand(&game, player, args, false)) {
broadcastNewBoards(&game, sockAddrs, roll, player);
};
}
}
// Check Win Condition
if (game.isPlayerWinner(player)) {
string message = "Player " + to_string(player) + " is the winner! Game over.";
int messageSize = message.size();
vector<thread> newThreads;
for (pair<int, int> sockPair : sockAddrs) {
newThreads.emplace_back(thread([message, messageSize](int sock){ write(sock, message.c_str(), messageSize);}, sockPair.second));
}
for (int i = 0; i < newThreads.size(); i++) {
newThreads[i].join();
}
break;
}
// Increment Turn
game.nextTurn();
broadcastNewBoards(&game, sockAddrs, roll, player);
}
// Close Socket & Terminate
connectionsThread.join();
close(server_fd);
return 0;
}