-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLifeSimulator.cpp
More file actions
109 lines (96 loc) · 2.65 KB
/
LifeSimulator.cpp
File metadata and controls
109 lines (96 loc) · 2.65 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
102
103
104
105
106
107
108
109
#include "LifeSimulator.hpp"
LifeSimulator::LifeSimulator(std::uint8_t width, std::uint8_t height)
{
this->width = width;
this->height = height;
grid.resize(this->height, std::vector<bool>(this->width, false));
}
std::uint8_t LifeSimulator::getSizeX() const
{
return width;
}
std::uint8_t LifeSimulator::getSizeY() const
{
return height;
}
bool LifeSimulator::getCell(std::uint8_t x, std::uint8_t y) const
{
if (x >= width || y >= height)
{
return false;
}
return grid[y][x];
}
void LifeSimulator::insertPattern(const Pattern& pattern, std::uint8_t x, std::uint8_t y)
{
for (std::uint8_t i = 0; i < pattern.getSizeX(); i++)
{
for (std::uint8_t j = 0; j < pattern.getSizeY(); j++)
{
std::uint8_t xPos = x + i;
std::uint8_t yPos = y + j;
if (xPos < width && yPos < height)
{
grid[yPos][xPos] = pattern.getCell(i, j);
}
}
}
}
std::uint8_t LifeSimulator::numLiveNeighbors(std::uint8_t x, std::uint8_t y)
{
std::uint8_t numAlive = 0;
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
if (i == 1 && j == 1)
{
continue; // Skip the current cell
}
int nx = static_cast<int>(x) + (i - 1);
int ny = static_cast<int>(y) + (j - 1);
if (nx >= 0 && nx < static_cast<int>(width) && ny >= 0 && ny < static_cast<int>(height))
{
if (getCell(static_cast<std::uint8_t>(nx), static_cast<std::uint8_t>(ny)))
{
numAlive++;
}
}
}
}
return numAlive;
}
bool LifeSimulator::cellLives(std::uint8_t x, std::uint8_t y, std::uint8_t numNeighborsAlive)
{
if (!getCell(x, y) && numNeighborsAlive == 3)
{
// Dead cell with exactly three live neighbors becomes alive
return true;
}
else if (getCell(x, y) && (numNeighborsAlive == 2 || numNeighborsAlive == 3))
{
// Live cell with two or three live neighbors stays alive
return true;
}
return false; // Cell dies or remains dead
}
void LifeSimulator::update()
{
std::vector<std::vector<bool>> newGrid = grid;
for (std::uint8_t y = 0; y < height; y++)
{
for (std::uint8_t x = 0; x < width; x++)
{
std::uint8_t numNeighborsAlive = numLiveNeighbors(x, y);
if (cellLives(x, y, numNeighborsAlive))
{
newGrid[y][x] = true;
}
else
{
newGrid[y][x] = false;
}
}
}
grid = newGrid;
}