-
Notifications
You must be signed in to change notification settings - Fork 0
/
conway.cpp
103 lines (96 loc) · 2.12 KB
/
conway.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
#include "conway.hpp"
void conway::allocate()
{
// allocate
matrix = new cell*[rows];
for (int i = 0; i < rows; ++i) {
matrix[i] = new cell[cols];
}
populated = true;
}
void conway::populate(std::vector<cell> points)
{
allocate();
// populate
for (auto& p : points)
matrix[p.y][p.x].alive = true;
}
void conway::populate_rand()
{
allocate();
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c)
if (distr(eng)) matrix[c][r].alive = true;
}
conway::~conway()
{
if (!populated) return;
for (int r = 0; r < rows; ++r) {
delete[] matrix[r];
}
delete[] matrix;
}
// conway's game of life rules:
// 1. any live cell with two or three n. survives
// 2. any dead cell with three live n. is born
// 3. all other live/dead cells die/remain dead
void conway::step()
{
std::vector<cell> updates;
// record updates without changing current state
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
int n = count_n(r, c);
if (matrix[r][c].alive and (n < 2 or n > 3)) {
cell t = matrix[r][c];
t.alive = false;
t.y = r;
t.x = c;
updates.push_back(t);
} else if ((!matrix[r][c].alive) and n == 3) {
cell t = matrix[r][c];
t.alive = true;
t.y = r;
t.x = c;
updates.push_back(t);
}
}
}
// update all cells that changed
for (auto& c : updates) matrix[c.y][c.x].alive = c.alive;
}
size_t conway::count_n(int r, int c)
{
size_t n = 0;
bool cmin = c - 1 > 0;
bool cmax = c + 1 < cols;
bool rmin = r - 1 > 0;
bool rmax = r + 1 < rows;
// top row
if (rmin) {
if (matrix[r - 1][c].alive) n++;
if (cmin and matrix[r - 1][c - 1].alive) n++;
if (cmax and matrix[r - 1][c + 1].alive) n++;
}
// middle row
if (cmin and matrix[r][c - 1].alive) n++;
if (cmax and matrix[r][c + 1].alive) n++;
// bot row
if (rmax) {
if (matrix[r + 1][c].alive) n++;
if (cmin and matrix[r + 1][c - 1].alive) n++;
if (cmax and matrix[r + 1][c + 1].alive) n++;
}
return n;
}
void conway::print()
{
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
int n = 0;
if (matrix[r][c].alive) n = 1;
std::cout << n << " ";
}
std::cout << std::endl;
}
}