-
Notifications
You must be signed in to change notification settings - Fork 0
/
AntManager.cpp
84 lines (65 loc) · 2.18 KB
/
AntManager.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
//
// Created by Balajanovski on 12/11/2017.
//
#include <iostream>
#include <cmath>
#include <thread>
#include "Util/Tile.h"
#include "Util/RandomNumberGen.h"
#include "AntManager.h"
#include "ConfigManager.h"
std::mutex AntManager::m_mutex;
AntManager::AntManager(std::shared_ptr<Field> field) : m_field(field)
{
m_thread_num = ConfigManager::instance().get_thread_number();
}
void AntManager::iterate() {
std::vector<std::thread> threads;
size_t partition_size = static_cast<size_t>(std::ceil(static_cast<float>(m_ants.size()) / m_thread_num));
size_t num_ants = m_ants.size();
for (int i = 0; i < num_ants; i += partition_size) {
threads.push_back(std::thread(&AntManager::move_ants, this, i,
((i + partition_size) > num_ants) ? num_ants : (i + partition_size)));
}
for (auto& thread : threads) {
thread.join();
}
}
void AntManager::generate_ants(int number) {
m_ants.reserve(number);
for (int i = 0; i < number; ++i) {
m_ants.push_back(Ant({RandomNumberGen::rng(0, m_field->get_field_width() - 1),
RandomNumberGen::rng(0, m_field->get_field_height() - 1)}));
}
}
TileDirection AntManager::get_block_on(const Ant& ant) {
return m_field->get_tile(ant.get_coords());
}
void AntManager::move_ant(Ant &ant) {
auto block_on = get_block_on(ant);
switch(block_on) {
case TileDirection::TURN_RIGHT:
{
ant.rotate_right();
m_mutex.lock();
m_field->flip_tile(Tile{ant.get_coords(), ant.get_color()});
m_mutex.unlock();
ant.move(m_field->get_field_width(), m_field->get_field_height());
}
break;
case TileDirection::TURN_LEFT:
{
ant.rotate_left();
m_mutex.lock();
m_field->flip_tile(Tile{ant.get_coords(), ant.get_color()});
m_mutex.unlock();
ant.move(m_field->get_field_width(), m_field->get_field_height());
}
break;
}
}
void AntManager::move_ants(int start_index, int end_index) {
for (int i = start_index; i < end_index; ++i) {
move_ant(m_ants[i]);
}
}