-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulation.cpp
More file actions
101 lines (89 loc) · 2.51 KB
/
Simulation.cpp
File metadata and controls
101 lines (89 loc) · 2.51 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
#include "Simulation.h"
#include "Cellule.h"
#include "Steel.h"
#include "Stone.h"
#include "Acid.h"
Simulation::Simulation(int w, int h) : width(w), height(h) {
worldMap.resize(h, std::vector<Cellule*>(w, nullptr));
}
Simulation::~Simulation() {
int y = 0;
while (y < height) {
int x = 0;
while (x < width) {
delete worldMap[y][x];
x++;
}
y++;
}
}
void Simulation::add(Cellule* c) {
if (checkEmpty(c->getX(), c->getY()))
worldMap[c->getY()][c->getX()] = c;
}
void Simulation::createBlock(Cellule* c, int size)
{
int half = size / 2;
for (int vertical = -half; vertical <= half; vertical++) {
for (int horizontal = -half; horizontal <= half; horizontal++) {
int newX = c->getX() + horizontal;
int newY = c->getY() + vertical;
if (checkEmpty(newX, newY)) {
Cellule* newElement = c->clone();
newElement->setX(newX);
newElement->setY(newY);
add(newElement);
}
}
}
}
void Simulation::remove(int x, int y) {
delete worldMap[y][x];
worldMap[y][x] = nullptr;
}
Cellule* Simulation::get(int x, int y) {
if (x >= 0 && y >= 0 && x < width && y < height)
return worldMap[y][x];
return nullptr;
}
bool Simulation::checkEmpty(int x, int y) const {
return x >= 0 && x < width && y >= 0 && y < height && worldMap[y][x] == nullptr;
}
void Simulation::move(int old_x, int old_y, int new_x, int new_y) {
if (checkEmpty(new_x, new_y) && !checkEmpty(old_x, old_y)) {
worldMap[new_y][new_x] = worldMap[old_y][old_x];
worldMap[old_y][old_x] = nullptr;
worldMap[new_y][new_x]->setX(new_x);
worldMap[new_y][new_x]->setY(new_y);
}
}
void Simulation::update() {
int y = height - 1;
while (y >= 0) {
int x = 0;
while (x < width) {
Cellule* m = worldMap[y][x];
if (m)
m->update(*this);
x++;
}
y--;
}
}
void Simulation::draw(sf::RenderWindow& window, int cellSize) {
int y = 0;
while (y < height) {
int x = 0;
while (x < width) {
Cellule* m = worldMap[y][x];
if (m) {
sf::RectangleShape rect(sf::Vector2f(cellSize, cellSize));
rect.setFillColor(m->getColor());
rect.setPosition(x * cellSize, y * cellSize);
window.draw(rect);
}
x++;
}
y++;
}
}