Created
December 29, 2016 09:55
-
-
Save utilForever/acc5bd7381bf3ea986883dbb3a6645aa to your computer and use it in GitHub Desktop.
JRPG-style combat system using std::thread, std::future, std::promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <future> | |
#include <vector> | |
#include <sstream> | |
#include <iostream> | |
class Unit | |
{ | |
public: | |
Unit() { } | |
Unit(std::string name, int speed) : m_name(name), m_speed(speed), m_delay(0) { } | |
~Unit() { } | |
std::string GetName() { return m_name; } | |
void Delay() { m_delay += m_speed; } | |
bool IsTurn(int turn) | |
{ | |
Delay(); | |
if (m_delay >= turn) | |
{ | |
DoneTurn(turn); | |
return true; | |
} | |
return false; | |
} | |
void DoneTurn(int turn) { m_delay -= turn; } | |
void PrintData() | |
{ | |
std::stringstream stream; | |
stream << "Name : " << m_name << ", Speed : " << m_speed << ", Delay : " << m_delay << "\n"; | |
std::cout << stream.str(); | |
} | |
private: | |
std::string m_name; | |
int m_speed; | |
int m_delay; | |
}; | |
struct MyStruct | |
{ | |
std::vector<std::promise<Unit>> vP; | |
std::vector<std::future<Unit>> vF; | |
MyStruct(int size) | |
{ | |
vP.resize(size); | |
vF.resize(size); | |
for (int i = 0; i < size; ++i) | |
{ | |
vF[i] = vP[i].get_future(); | |
} | |
} | |
}; | |
void CalcTurn(std::vector<std::promise<Unit>>& p, std::vector<Unit> vec, int maxTurn, int actionPoint) | |
{ | |
int turn = 0; | |
while (turn < maxTurn) | |
{ | |
for (auto& v : vec) | |
{ | |
v.PrintData(); | |
if (v.IsTurn(actionPoint)) | |
{ | |
p[turn++].set_value(v); | |
} | |
} | |
} | |
} | |
void RunTurn(std::vector<std::future<Unit>>& f, int maxTurn) | |
{ | |
int turn = 0; | |
while (turn < maxTurn) | |
{ | |
std::stringstream stream; | |
stream << "It's " << f[turn++].get().GetName() << "'s turn!\n"; | |
std::cout << stream.str(); | |
} | |
} | |
int main() | |
{ | |
std::vector<Unit> vUnit = { Unit("A", 99), Unit("B", 88), Unit("C", 77), Unit("D", 66) }; | |
int maxTurn = 10, actionPoint = 200; | |
MyStruct PNF(maxTurn); | |
std::thread t1(&CalcTurn, std::ref(PNF.vP), std::ref(vUnit), maxTurn, actionPoint); | |
std::thread t2(&RunTurn, std::ref(PNF.vF), maxTurn); | |
t1.join(); | |
t2.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment