-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
96 lines (85 loc) · 2.37 KB
/
main.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
#include "screen.h"
const int GAME_WIDTH = 320;
const int GAME_HEIGHT = 240;
bool isAlive(std::array<std::array<int, GAME_HEIGHT>, GAME_WIDTH> &game, const int x, const int y)
{
int alive = 0;
// test left border
if (x > 0 && game[x - 1][y] == 1)
alive += 1;
// test right border
if (x < GAME_WIDTH && game[x + 1][y] == 1)
alive += 1;
// test top border
if (y > 0 && game[x][y - 1] == 1)
alive += 1;
// test bottom border
if (y < GAME_HEIGHT && game[x][y + 1] == 1)
alive += 1;
// test top left
if (x > 0 && y > 0 && game[x - 1][y - 1] == 1)
alive += 1;
// test top right
if (x < GAME_WIDTH && y > 0 && game[x + 1][y - 1] == 1)
alive += 1;
// test bottom left
if (x > 0 && y < GAME_HEIGHT && game[x - 1][y + 1] == 1)
alive += 1;
// test bottom right
if (x < GAME_WIDTH && y < GAME_HEIGHT && game[x + 1][y + 1] == 1)
alive += 1;
// alive, < 2 neighbors
if (game[x][y] == 1 && alive < 2)
return false;
// alive, 2 or 3 neighbors
if (game[x][y] == 1 && (alive == 2 || alive == 3))
return true;
// alive, >3 neighbors
if (alive > 3)
return false;
// dead, 3 neighbors
if (game[x][y] == 0 && alive == 3)
return true;
return false;
}
int main()
{
G screen;
std::array<std::array<int, GAME_HEIGHT>, GAME_WIDTH> display{};
std::array<std::array<int, GAME_HEIGHT>, GAME_WIDTH> swap{};
// create random points
for (auto &row : display)
{
std::generate(row.begin(), row.end(), []()
{ return rand() % 10 == 2 ? 1 : 0; });
}
while (true)
{
// check for alive cells
for (int i = 0; i < GAME_WIDTH; i++)
{
for (int k = 0; k < GAME_HEIGHT; k++)
{
swap[i][k] = isAlive(display, i, k) ? 1 : 0;
}
}
// draw
for (int i = 0; i < GAME_WIDTH; i++)
{
for (int k = 0; k < GAME_HEIGHT; k++)
{
if (swap[i][k])
{
screen.drawpixel(i, k);
}
}
}
// swap buffers
std::copy(swap.begin(), swap.end(), display.begin());
// Render
screen.update();
SDL_Delay(20);
screen.input();
screen.clearpixels();
}
}