-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.cpp
More file actions
91 lines (77 loc) · 2.24 KB
/
Copy pathgame.cpp
File metadata and controls
91 lines (77 loc) · 2.24 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
#include <iostream>
#include "client.h"
#include "game.h"
Client* MultithreadedGame::onJoin()
{
// std::cout << "This is debug output" << std::endl;
std::lock_guard<std::mutex> lock(playersMute);
MultithreadedClient client;
Client* newClient = &players.emplace_back(std::move(client));
return newClient;
}
void MultithreadedGame::onGetItem(Client* clientPtr, std::string_view name,
int amount)
{
// Validation checks
if (!clientPtr || name.size() == 0 || amount <= 0) return;
MultithreadedClient* client = dynamic_cast<MultithreadedClient*>(clientPtr);
if (client == nullptr) return;
// Get action
std::lock_guard<std::mutex> lock(client->bagMute);
auto itr = client->bag.find(std::string(name));
if(itr != client->bag.end())
{
itr->second += amount;
}
else
{
client->bag[std::string(name)] = amount;
}
}
void MultithreadedGame::onDropItem(Client* clientPtr, std::string_view name,
int amount)
{
// Validation checks
if (!clientPtr || name.size() == 0 || amount <= 0) return;
MultithreadedClient* client = dynamic_cast<MultithreadedClient*>(clientPtr);
if (client == nullptr) return;
// Drop action
std::lock_guard<std::mutex> lock(client->bagMute);
auto itr = client->bag.find(std::string(name));
if(itr != client->bag.end())
{
if (itr->second > amount)
{
itr->second -= amount;
}
else
{
client->bag.erase(itr);
}
}
}
void MultithreadedGame::onGiveItem(Client* fromClientPtr, Client* toClientPtr,
std::string_view name, int amount)
{
// Validation checks
if (!fromClientPtr || !toClientPtr || name.size() == 0 || amount <= 0) return;
// Actions
onDropItem(fromClientPtr, name, amount);
onGetItem(toClientPtr, name, amount);
}
void MultithreadedGame::onLeave(Client* clientPtr)
{
// Validation checks
if (!clientPtr) return;
std::lock_guard<std::mutex> lock(playersMute);
auto itr = std::find_if(players.begin(), players.end(), [&](const Client& client) { return &client == clientPtr; });
if (itr != players.end())
{
players.erase(itr);
}
}
std::size_t MultithreadedGame::getClientCount() const
{
std::lock_guard<std::mutex> lock(playersMute);
return players.size();
}