-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grid.cpp
78 lines (69 loc) · 1.45 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
#include <SFML/Graphics.hpp>
#include <iostream>
#include <cstring>
#include "Headers/Grid.hpp"
#include "Headers/Cell.hpp"
Grid::Grid(int _size, 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, 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::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);
}
}
}