-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grid.cpp
94 lines (83 loc) · 1.74 KB
/
Grid.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
#include <SFML/Graphics.hpp>
#include <iostream>
#include <cstring>
#include "Headers/Grid.hpp"
#include "Headers/Cell.hpp"
Grid::Grid(int _size, int base_x, int base_y, int _x, int _y)
{
size = _size;
x = _x;
y = _y;
cells = new Cell[x * y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cells[y * i + j] = Cell(i, j, base_x, base_y, size);
}
}
}
Cell *Grid::getCell(int xpos, int ypos)
{
if (xpos > x || ypos > y || xpos < 0 || ypos < 0)
{
return nullptr;
}
return cells + (y * xpos + ypos);
}
void Grid::setNeighbors(int xpos, int ypos)
{
int neighbors = 0;
for (int i = xpos - 1; i <= xpos + 1; i++)
{
for (int j = ypos - 1; j <= ypos + 1; j++)
{
if (!(xpos == i && ypos == j))
{
Cell *cell = getCell(i, j);
if (cell)
{
neighbors += cell->alive;
}
}
}
}
getCell(xpos, ypos)->setNeighbors(neighbors);
}
void Grid::update()
{
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
setNeighbors(i, j);
getCell(i, j)->update();
}
}
}
void Grid::clear()
{
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
getCell(i, j)->kill();
}
}
}
void Grid::toggle(int xpos, int ypos)
{
getCell(xpos / size, ypos / size)->toggle();
}
void Grid::render(sf::RenderWindow &window)
{
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
Cell *cell = getCell(i, j);
cell->render();
window.draw(cell->shape);
}
}
}