-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeadsTailsServer.cpp
More file actions
114 lines (90 loc) · 2.83 KB
/
HeadsTailsServer.cpp
File metadata and controls
114 lines (90 loc) · 2.83 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
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
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <iostream>
#include "HeadsTailsServer.h"
#include "ThreadContext.h"
HeadsTailsServer::HeadsTailsServer(int socket, ServerStats &serverStats)
{
this->socket = socket;
this->serverStats = serverStats;
}
HeadsTailsServer::~HeadsTailsServer() { }
string HeadsTailsServer::flipCoin()
{
srand (time(NULL));
string face = rand() % 2 == 0 ? "h" : "t";
return face;
}
void HeadsTailsServer::updateScoreboard(string guess, string face, ThreadContext &context)
{
if (guess == face) // did guess match the flipCoin face?
{
// win
context.recordLastGuess(serverStats, 1);
}
else
{
context.recordLastGuess(serverStats, 0);
}
}
int HeadsTailsServer::gameMenu(ThreadContext &context)
{
bool connected = true;
int readStatus;
while (connected)
{
memset(buffer, 0, sizeof(buffer));
readStatus = read(socket, buffer, 1024);
if (readStatus == 0)
{
// error checking: socket didn't receive message
connected = false;
}
KeyValue rpcKV;
interpreter.newRPC(buffer);
interpreter.getNextKeyValue(rpcKV);
//disconnect rpc will skip this check
if ((strcmp(rpcKV.getValue(), "flipcoin") == 0))
{
string winningFace;
KeyValue guessKV; // guess= h/t
interpreter.getNextKeyValue(guessKV); // guess= h/t
string guess = guessKV.getValue();
if (guess == "h" || guess == "t")
{
winningFace = flipCoin();
updateScoreboard(guess, winningFace, context);
}
char face[2];
face[0] = winningFace[0];
face[1] = 0;
send(socket, face, 2, 0);
}
// Exit menu
if (strcmp(rpcKV.getValue(), EXIT_MENU) == 0)
{
connected = false;
cout << "context number: " << context.getWins() << endl;
int number = context.getWins();
cout << "context number: " << context.getRounds() << endl;
int rounds = context.getRounds();
// Add context nunbers to char arrays and add those together
char winBuffer[100];
char roundBuffer[10];
sprintf(winBuffer, "%d", number);
char winsArr[7] = " Wins ";
strcat(winBuffer, winsArr);
sprintf(roundBuffer, "%d", rounds);
char roundsArr[8] = " Rounds";
strcat(roundBuffer, roundsArr);
strcat(winBuffer, roundBuffer);
//Send the context char array to the client
send(socket, winBuffer, strlen(winBuffer) , 0);
}
}
return 0;
}