-
Notifications
You must be signed in to change notification settings - Fork 1
/
Player.cpp
143 lines (112 loc) · 2.54 KB
/
Player.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
#include<iostream>
#include<vector>
#include<string>
#include<signal.h>
#include<SimpleSemaphore.h>
#include<SharedMemory.h>
#include<Cards.h>
using namespace std;
enum { WAITING, PLAYING };
enum {WIN, LOSE, TIE};
SimpleSemaphore ready("/ready", 0);
SimpleSemaphore zync("/sync", 0);
SimpleSemaphore numPlayers("/numPlayers", 0);
SharedMemory<int> mem_status("/status");
SharedMemory<card> mem_current("/current");
SharedMemory<int> mem_last("/last");
SharedMemory<char> mem_tmp("/tmp");
SharedMemory<int> mem_score("/score");
void printUsage() {
cout << "Usage:" << endl;
cout << " ./Player [--cheat]" << endl;
cout << "Type -h or --help to show this message" << endl;
};
class Player
{
public:
Player ();
virtual ~Player ();
void play(bool cheat);
private:
string name;
deck myDeck;
bool cheat;
};
Player::Player() {
};
Player::~Player() {
};
void Player::play(bool cheat) {
name = "player_";
myDeck = generateDeck();
this->cheat = cheat;
int &status = mem_status();
card ¤t = mem_current();
char &tmp = mem_tmp();
int &last = mem_last();
int &score = mem_score();
numPlayers.Signal();
cout << "Waiting for game..." << endl;;
ready.Wait();
name.append(1, tmp);
SimpleSemaphore turn("/" + name, 0);
cout << "Semaphore is /" << name << endl;
zync.Signal();
cout << "The game has begun" << endl;
int turns = 0;
while (status == PLAYING) {
turn.Wait();
if (status != PLAYING) break;
cout << "Is my turn " << (++turns) << endl;
int index = rand() % myDeck.size();
current = myDeck[index];
if (!cheat) myDeck.erase(myDeck.begin() + index);
current.print();
ready.Signal();
turn.Wait();
switch(last) {
case(WIN):
cout << "You win!" << endl;
break;
case(LOSE):
cout << "You lose..." << endl;
break;
case(TIE):
cout << "Tie" << endl;
break;
}
zync.Signal();
cout << endl;
}
turn.Wait();
cout << "Your score is " << score << endl;
switch(last) {
case(WIN):
cout << "You have won!" << endl;
break;
case(LOSE):
cout << "You have lost" << endl;
break;
case(TIE):
cout << "It's a tie" << endl;
break;
}
zync.Signal();
cout << endl;
};
int main (int argc, char const *argv[])
{
srand(time(NULL));
Player player;
if (argc > 1) {
if (strcmp(argv[1], "--cheat") == 0) {
cout << "Begin game with cheating" << endl;
player.play(true);
} else if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
printUsage();
} else {
cout << "Begin game without cheating" << endl;
player.play(false);
}
return 0;
}