-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconways_game_of_life.cpp
94 lines (67 loc) · 1.98 KB
/
conways_game_of_life.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
#include <iostream>
#include <vector>
#include <unordered_map>
void display(const std::vector<std::vector<int>> &board, const std::unordered_map<int, char>&symbols){
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board[i].size(); j++){
std::cout << symbols.at(board[i][j]);
}
std::cout << "\n";
}
std::cout << "\n";
}
void tick(std::vector<std::vector<int>> &board){
// ideally i want a vector with 2 types but i am using struct instead to do this
struct data_struct{ // should i be declaring this globally or something rather than initialising the struct each function call?
int* pointer {NULL};
int value {};
};
std::vector<data_struct> changes {};
int neighbours {};
data_struct data {};
for (int i = 1; i < board.size()-1; i++){
for (int j = 1; j < board[i].size()-1; j++){
neighbours = 0;
for (int k = -1; k < 2; k++){
for (int l = -1; l < 2; l++){
neighbours += board[i+k][j+l];
}
}
neighbours -= board[i][j];
if (neighbours != 2 && neighbours > 0){
if (neighbours < 2 || neighbours > 3){
data.value = 0;
}
else if (neighbours == 3){
data.value = 1;
}
int *x = &board[i][j];
data.pointer = x;
changes.push_back(data);
}
}
}
for (int i = 0; i < changes.size(); i++){ // make the changes occur!!
*changes[i].pointer = changes[i].value;
}
}
int main(){
const std::unordered_map<int, char> symbols {{0, '.'}, {1, '#'}};
std::vector<std::vector<int>> board (16, std::vector<int>(32, 0));
int generations {};
// Glider
board[3][3] = 1;
board[3][4] = 1;
board[3][5] = 1;
board[2][5] = 1;
board[1][4] = 1;
// todo add blinker
std::cout << "Enter number of generations: ";
std::cin >> generations;
display(board, symbols);
for (int i = 0; i < generations; i++){
std::cout << "\033[H\033[J";
tick(board);
display(board, symbols);
}
}