-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarsspawner.cpp
91 lines (75 loc) · 2.26 KB
/
carsspawner.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
#include "carsspawner.h"
CarsSpawner::CarsSpawner(QVector<RoadEdge> *edges, GraphicScene *graphicsScene)
: graphicsScene(graphicsScene)
, paths(new QVector<QVector<RoadPoint> *>)
, carAIs(new QVector<CarAI>)
, timer(new QTimer)
, rng(new std::mt19937(time(nullptr)))
{
QVector<RoadPoint> starts;
QVector<RoadPoint> ends;
{
std::map<RoadPoint, int> incomingCount;
std::map<RoadPoint, int> outcomingCount;
for (auto edge : *edges) {
incomingCount[edge.endPos]++;
incomingCount[edge.startPos];
outcomingCount[edge.startPos]++;
outcomingCount[edge.endPos];
}
for (auto point : outcomingCount) {
if (point.second == 0) {
ends.push_back(point.first);
}
}
for (auto point : incomingCount) {
if (point.second == 0) {
starts.push_back(point.first);
}
}
}
auto adj = PathService::FromEdgesToAdjMatrix(edges);
for (auto start : starts) {
for (auto end : ends) {
auto path = PathService::FindPath(adj, start, end);
if (path != nullptr) {
paths->push_back(path);
}
}
}
timer->setInterval(TICK_TIME);
connect(timer, &QTimer::timeout, this, &CarsSpawner::Update);
timer->start();
}
CarsSpawner::~CarsSpawner()
{
delete carAIs;
delete paths;
delete timer;
delete rng;
}
void CarsSpawner::Update()
{
if (paths->empty()) {
return;
}
if ((*rng)() % CHANCE_OF_SPAWNING_CAR == 0 && carAIs->size() < MAX_CAR_COUNT) {
auto pos = (*rng)() % paths->size();
bool isCarNear = false;
for (int iter = 0;iter<carAIs->size();++iter)
{
if (!(*carAIs)[iter].isDone() && isEqual((*carAIs)[iter].GetCar()->GetPosition().pos, paths->at(pos)->at(0).pos, CAR_LENGTH)) {
isCarNear = true;
}
}
if (!isCarNear) {
carAIs->push_back(CarAI(paths->at(pos), carAIs, graphicsScene));
}
}
for (size_t iter = 0; iter < carAIs->size(); ++iter) {
if ((*carAIs)[iter].isDone()) {
carAIs->erase(carAIs->begin() + iter);
--iter;
}
}
}