-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLifeGame.cpp
145 lines (127 loc) · 2.64 KB
/
LifeGame.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "LifeGame.hpp"
unsigned long profile_ref_count;
LifeGame::LifeGame()
: generation(0)
//, board(BOARD_SIZE + 2, std::vector<bool>(BOARD_SIZE + 2, false))
//, back_buffer(BOARD_SIZE + 2, std::vector<bool>(BOARD_SIZE + 2, false))
, mt(rand())
, around_cell_cache(0)
, first_count(false)
{
board = new bool*[BOARD_SIZE + 2];
back_buffer = new bool*[BOARD_SIZE + 2];
for (int i = 0; i < BOARD_SIZE + 2; i++)
{
board[i] = new bool[BOARD_SIZE + 2];
back_buffer[i] = new bool[BOARD_SIZE + 2];
}
for (int y = 0; y < BOARD_SIZE + 2; y++)
{
for (int x = 0; x < BOARD_SIZE + 2; x++)
{
board[y][x] = false;
back_buffer[y][x] = false;
}
}
// initByRand();
}
LifeGame::~LifeGame()
{
for (int i = 0; i < BOARD_SIZE + 2; i++)
{
delete[] board[i];
delete[] back_buffer[i];
}
delete[] board;
delete[] back_buffer;
}
void LifeGame::update()
{
generation++;
for (int y = 1; y < BOARD_SIZE + 1; y++)
{
first_count = true;
for (int x = 1; x < BOARD_SIZE + 1; x++)
{
back_buffer[y][x] = false;
int around_cell_count = countAroundCell(x, y);
if (around_cell_count == 2)
{
back_buffer[y][x] = board[y][x];
}
else if (around_cell_count == 3)
{
back_buffer[y][x] = true;
}
}
}
std::swap(board, back_buffer);
}
void LifeGame::initByRand()
{
for (int y = 1; y < BOARD_SIZE - 1; y++)
{
for (int x = 1; x < BOARD_SIZE - 1; x++)
{
board[y][x] = static_cast<bool>(mt() & 0x01);
}
}
}
bool LifeGame::at(size_t x, size_t y) const
{
return board[y + 1][x + 1];
}
void LifeGame::set(size_t x, size_t y)
{
board[y + 1][x + 1] = true;
}
int LifeGame::countAroundCell(int x, int y)
{
int c = 0;
for (int j = y - 1; j <= y + 1; j++)
{
for (int i = x - 1; i <= x + 1; i++)
{
profile_ref_count++;
if (x == i && y == j)
{
continue;
}
if (board[j][i])
c++;
}
}
return c;
}
/*int LifeGame::countAroundCell(int x, int y)
{
if (first_count)
{
int c = 0;
for (int j = y - 1; j <= y + 1; j++)
{
for (int i = x - 1; i <= x + 1; i++)
{
profile_ref_count++;
if (x == i && y == j)
{
continue;
}
c += static_cast<int>(board[j][i]);
}
}
around_cell_cache = c;
first_count = false;
}
else
{
for (int j = y - 1; j <= y + 1; j++)
{
around_cell_cache += static_cast<int>(board[j][x + 1]) - static_cast<int>(board[j][x - 2]);
profile_ref_count++;
}
around_cell_cache += static_cast<int>(board[y][x - 1]);
around_cell_cache -= static_cast<int>(board[y][x]);
}
return around_cell_cache;
}*/