-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
89 lines (69 loc) · 2.27 KB
/
main.cpp
File metadata and controls
89 lines (69 loc) · 2.27 KB
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
#include <cstdio>
#include <raylib.h>
#include "server/Game.h"
#include "client/Client.h"
#include <pthread.h>
const int PORT = 1234;
typedef struct Data {
int numberOfPlayers;
std::string serverAddress;
pthread_mutex_t *mutex;
bool serverStarted;
pthread_cond_t *serverStartedCond;
} Data;
void *serverThread(void *arg) {
auto *data = static_cast<Data *>(arg);
SetRandomSeed(time(nullptr));
Game game(PORT);
game.startListening();
pthread_mutex_lock(data->mutex);
data->serverStarted = true;
pthread_mutex_unlock(data->mutex);
pthread_cond_broadcast(data->serverStartedCond);
game.startGame(data->numberOfPlayers);
return nullptr;
}
int main(int argn, char *argv[]) {
if (argn < 3) {
fprintf(stderr, "incorrect number of arguments\n");
return 1;
}
SetTraceLogLevel(LOG_WARNING);
if (std::string(argv[1]) == "start") {
int numberOfPlayers = std::stoi(argv[2]);
if(numberOfPlayers < 1 || numberOfPlayers > 4) {
fprintf(stderr, "incorrect number of players\n");
return 1;
}
pthread_t server;
pthread_mutex_t mutex;
pthread_cond_t serverStartedCond;
pthread_mutex_init(&mutex, nullptr);
pthread_cond_init(&serverStartedCond, nullptr);
Data data{
.numberOfPlayers = std::stoi(argv[2]),
.serverAddress = "localhost",
.mutex = &mutex,
.serverStarted = false,
.serverStartedCond = &serverStartedCond
};
pthread_create(&server, nullptr, &serverThread, &data);
pthread_mutex_lock(data.mutex);
while (!data.serverStarted) {
pthread_cond_wait(data.serverStartedCond, data.mutex);
}
Client client(data.serverAddress, PORT);
pthread_mutex_unlock(data.mutex);
client.start();
pthread_join(server, nullptr);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&serverStartedCond);
} else if (std::string(argv[1]) == "connect") {
Client client(std::string(argv[2]), PORT);
client.start();
} else {
fprintf(stderr,"Invalid first argument. Only valid options are start/connect.\n");
return 1;
}
return 0;
}