-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grid.cpp
146 lines (128 loc) · 1.83 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
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
146
#include <iostream>
#include <cstdlib>
#include <vector>
#include "Grid.h"
using namespace std;
Grid::Grid(const int w, const int h)
{
width = w;
height = h;
real = new bool*[width];
stub = new bool*[width];
for (int i = 0; i < width; ++i)
{
real[i] = new bool[height];
stub[i] = new bool[height];
for (int k = 0; k < height; ++k)
{
real[i][k] = (bool)(rand() & 1);
stub[i][k] = real[i][k];
}
}
}
Grid::~Grid()
{
for (int x = 0; x < width; ++x)
{
delete[] real[x];
delete[] stub[x];
}
delete[] real;
delete[] stub;
}
int Grid::getWidth()
{
return width;
}
int Grid::getHeight()
{
return height;
}
void Grid::process()
{
int neighbours;
for (int i = 0; i < width; ++i)
{
for (int k = 0; k < height; ++k)
{
neighbours = adjAndAlive(i, k);
if (real[i][k])
{ // if alive
if (neighbours < 2)
{
stub[i][k] = false;
}
else if (neighbours < 4)
{
stub[i][k] = true;
}
else
{
stub[i][k] = false;
}
}
else if (neighbours == 3)
{
stub[i][k] = true;
}
}
}
copy();
}
void Grid::display()
{
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
if (real[x][y]) // if alive
{
cout << ALIVE;
}
else
{
cout << DEAD;
}
}
cout << endl;
}
}
void Grid::copy()
{
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
real[x][y] = stub[x][y];
}
}
}
bool Grid::inBounds(int x, int y)
{
return (x >= 0) && (x < width) && (y >= 0) && (y < height);
}
int Grid::adjAndAlive(int x, int y)
{
bool was_alive = real[x][y];
int count = 0;
--x;
--y;
for (int i = 0; i < 3; ++i)
{
for (int k = 0; k < 3; ++k)
{
if (inBounds(x + i, y + k) && real[x + i][y + k])
{
++count;
}
}
}
if (was_alive)
{
return count - 1;
}
else
{
return count;
}
}