-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_logic.cpp
78 lines (63 loc) · 1.89 KB
/
game_logic.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
#include "game_logic.hpp"
vector<bool> getNeighborStates(vector<int> g, int pos){
vector<bool> neighbors(NEIGHBORS, false);
int ids[NEIGHBORS] = {pos-WIDTH-1,pos-WIDTH,pos-WIDTH+1,pos-1,pos+1,pos+WIDTH-1,pos+WIDTH,pos+WIDTH+1};
for (int i = 0; i < NEIGHBORS; i++){
neighbors[i] = g[ids[i]];
}
return neighbors;
}
vector<int> emptyGrid(){
vector<int> g(HEIGHT*WIDTH, false);
return g;
}
vector<int> randomGrid(){
vector<int> g = emptyGrid();
unsigned seed = time(0);
srand(seed);
int size = HEIGHT * WIDTH;
int pos = 0;
for (int i = 0; i < size/4; i++){
pos = rand() % size;
g[pos] = true;
}
return g;
}
void logic(vector<int>& prev_grid, vector<int>& grid){
int pos = 0;
int nb_alive = 0;
int nb_dead = 0;
// If time, check border; for the moment = approx
for(int i=1; i<HEIGHT-1; i++){
for(int j=1; j<WIDTH-1; j++){
pos = i*WIDTH + j;
vector<bool> states = getNeighborStates(prev_grid, pos);
nb_alive = 0;
nb_dead = 0;
for(int idv=0; idv < states.size(); idv++){
(states[idv]) ? nb_alive++ : nb_dead++;
}
if (prev_grid[pos] == true){
grid[pos] = ( (nb_alive == 2) || (nb_alive == 3) ) ? true : false;
} else {
grid[pos] = (nb_alive==3) ? true : false;
}
}
}
prev_grid = grid;
grid = emptyGrid();
}
void displayGridInTerminal(vector<int> grid){
char alive = 'X';
char dead = '.';
if (grid.empty()) std::cout << "Grid is empty" << std::endl;
else {
for(int i=0; i<HEIGHT; i++){
for(int j=0; j<WIDTH; j++){
if (grid[i*WIDTH+j]) std::cout << alive << " ";
else std::cout << dead << " ";
}
std::cout << std::endl;
}
}
}