forked from jirfag/PREP-labyrinth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathField.cpp
130 lines (102 loc) · 2.69 KB
/
Field.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//
// Created by tsv on 09.05.16.
//
#include "Field.hpp"
#include <iostream>
std::istream& operator>>(std::istream& is, Field& field)
{
size_t rows = 0;
size_t cols = 0;
is >> rows >> cols;
field.field.resize(rows);
for (auto& row: field.field) {
row.resize(cols);
}
BlockType block_type;
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < cols; ++j) {
is >> block_type;
field.field[i][j] = block_type;
if (block_type == BlockType::ENTER) {
field.current_position = {i, j};
}
}
}
field.set_runner_current_status();
return is;
}
std::istream& operator>>(std::istream& is, BlockType& block_type)
{
int val = 0;
is >> val;
block_type = static_cast<BlockType>(val);
return is;
}
bool Field::tic()
{
const auto MAX_EXECUTION_TIME_SEC = 60;
const auto elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(get_time_elapsed_mcs()).count();
if (elapsed_seconds > MAX_EXECUTION_TIME_SEC) {
std::cerr << "solution got too much time: " << elapsed_seconds << " sec" << std::endl;
return false;
}
++tic_count;
Direction direction = runner.step();
auto i = current_position.x;
auto j = current_position.y;
switch (direction) {
case Direction::UP: {
--i;
break;
}
case Direction::DOWN: {
++i;
break;
}
case Direction::LEFT: {
--j;
break;
}
case Direction::RIGHT: {
++j;
break;
}
}
auto next_block_type = field[i][j];
if (next_block_type != BlockType::WALL) {
current_position = {i, j};
set_runner_current_status();
if (next_block_type == BlockType::EXIT) {
done = true;
}
}
return true;
}
void Field::set_runner_current_status()
{
auto i = current_position.x;
auto j = current_position.y;
Status status;
status.up = field[i - 1][j];
status.down = field[i + 1][j];
status.left = field[i][j - 1];
status.right = field[i][j + 1];
runner.set_current_status(status);
}
bool Field::is_done()
{
return done;
}
void Field::result(std::ostream& os)
{
const auto elapsed_time_mcs = get_time_elapsed_mcs().count();
os << "Total steps: " << tic_count << ", time: " << elapsed_time_mcs << " mcs" << std::endl;
}
void Field::start()
{
start_time = std::chrono::steady_clock::now();
}
std::chrono::microseconds Field::get_time_elapsed_mcs() const
{
return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time);
}