-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrid.cpp
More file actions
82 lines (76 loc) · 2.33 KB
/
Grid.cpp
File metadata and controls
82 lines (76 loc) · 2.33 KB
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
#include "Grid.hpp"
#include <iostream>
#include <algorithm>
const int GRID_SIZE = 256; // grid size to be processed
const int VIEW_SIZE = 128; // grid size to be shown in console
Grid::Grid() {
// generate a 2d vector filled with cells according to the grid size
for (int i=0; i<GRID_SIZE; i++) {
cells.emplace_back(std::vector<Cell>());
for (int j=0; j<GRID_SIZE; j++) {
cells[i].emplace_back(Cell(i*GRID_SIZE+j));
}
}
addNeighbors(); // add all cell's neighbors to each cell
};
// generates coordinates for each cell's neighbors according to grid size
// with care to the borders
std::vector<std::vector<int>> Grid::getCoords(int x, int y) const{
std::vector<std::vector<int>> coords {
{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}
};
std::vector<std::vector<int>> results;
for (std::vector<int> coord : coords) {
int nx = coord[0] + x;
if (nx >= 0 && nx < GRID_SIZE) {
int ny = coord[1] + y;
if (ny >= 0 && ny < GRID_SIZE) {
results.push_back({nx, ny});
}
}
}
return results;
}
// add all cell's neighbors to each cell
void Grid::addNeighbors() {
for (int i=0; i<GRID_SIZE; i++) {
for (int j=0; j<GRID_SIZE; j++) {
std::vector<std::vector<int>> coords = getCoords(i, j);
for (std::vector<int> coord : coords) {
cells[i][j].addNeighbor(&cells[coord[0]][coord[1]]);
}
}
}
};
// calculate the next state of each cell in one pass
// update the state in the next pass
void Grid::nextState() {
for (int i=0; i<GRID_SIZE; i++) {
for (int j=0; j<GRID_SIZE; j++) {
cells[i][j].calcNextState();
}
}
for (int i=0; i<GRID_SIZE; i++) {
for (int j=0; j<GRID_SIZE; j++) {
cells[i][j].updateState();
}
}
}
// simple ascii display:
// "a" -> alive
// "." -> dead
void Grid::display() const {
int idx = (GRID_SIZE - VIEW_SIZE) / 2;
for (int i=idx; i<VIEW_SIZE; i++) {
for (int j=idx; j<VIEW_SIZE; j++) {
if (cells[i][j].getState()) {
std::cout << "a ";
} else {
std::cout << ". ";
}
}
std::cout << std::endl;
}
}