Repository navigation
Expand file tree
/
Copy pathcBrain.cpp
More file actions
113 lines (103 loc) · 2.42 KB
/
Copy pathcBrain.cpp
File metadata and controls
113 lines (103 loc) · 2.42 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
#include "cAction.h"
#include "cBrain.h"
#include "cScene.h"
#include "cGraphics.h"
#include <map>
#include <fstream>
#include <iostream>
using namespace std;
float RandValue();
struct cBrain::cConfig
{
static const cConfig* Get(const string& name);
bool loaded = false;
vector<string> possibleActions;
vector<string> possibleTargets;
};
const cBrain::cConfig* cBrain::cConfig::Get(const string& _name)
{
static map<string, cBrain::cConfig> configStorage;
cBrain::cConfig& config = configStorage[_name];
if (config.loaded) return &config;
config.loaded = true;
string path = AssetsPath() + "brains/" +_name+ ".txt";
auto file = fstream(path);
if (file.is_open())
{
auto words = string();
while (getline(file, words))
{
stringstream s(words);
string str;
s >> str;
if (str == "possibleActions")
{
while (s >> str) config.possibleActions.push_back(str);
}
else if(str == "possibleTargets")
{
while (s >> str) config.possibleTargets.push_back(str);
}
}
}
else
{
std::cout << "File not found: " << path << std::endl;
}
return &config;
}
cBrain::cBrain(cEntity* _owner, const std::string& name) : owner(_owner)
{
config = cConfig::Get(name);
//to do load config by name
}
cBrain::~cBrain()
{
if (action) delete action;
}
void cBrain::Think()
{
//std::srand(std::time({}));
//@to_do: take a string from allowed targets and search for it
if (!target)
{
int randIndx = RandValue() * config->possibleTargets.size();
target = FindClosestTarget(config->possibleTargets[randIndx]);
if (!target) return;
}
if (!action)
{
int randIndx = RandValue() * config->possibleActions.size();
action = new cAction(config->possibleActions[randIndx], owner);
}
if (action->Do(target)) //Do returns true when action is finished
{
target = NULL;
delete action;
action = NULL;
}
}
float Distance(const Vector2f& p1, const Vector2f& p2)
{
return (p2 - p1).length();
}
cEntity* cBrain::FindClosestTarget(const std::string& name) const
{
auto& myPos = owner->GetPosition();
float distMin = 100000;
cEntity* target = NULL;
for (auto* i : cScene::Get().Entities())
{
if (i->Name() == name && i->Health() > 0)
{
auto& targetPos = i->GetPosition();
float dist = Distance(targetPos, myPos);
if (dist < distMin)
{
distMin = dist;
target = i;
}
}
}
return target;
}