-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtilemap.cpp
95 lines (75 loc) · 2.45 KB
/
tilemap.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
#include "tilemap.hpp"
#include <algorithm>
#include <iostream>
using namespace std;
Tilemap::Tilemap(int height, int width, int size) {
vector<vector<Quad>> newGrid;
for(int x=0; x<width; x+=size) {
vector<Quad> row;
for(int y=0; y<height; y+=size) {
Quad quad(x,y);
row.push_back(quad);
}
newGrid.push_back(row);
}
this->grid = newGrid;
}
vector<vector<Quad>> Tilemap::getGrid() {
return this->grid;
}
void Tilemap::setGrid(vector<vector<Quad>> grid) {
this->grid = grid;
}
void Tilemap::iterate() {
vector<vector<Quad>> updatedGrid = this->grid;
// cout << "Here" << endl;
for(int i=0; i<this->grid.size(); i++) {
for(int j=0; j<this->grid[0].size(); j++) {
// cout << "Here at (" << i << "," << j << ")" << endl;
if(this->grid[i][j].isAlive() && !survive(i,j)){
//kills cell
updatedGrid[i][j].switchState();
}
if(!this->grid[i][j].isAlive() && revive(i,j)) {
//revives cell
updatedGrid[i][j].switchState();
}
}
}
this->grid = updatedGrid;
return;
}
bool Tilemap::survive(int row, int col) {
// Function only returns true if cell is alive
Quad cell = this->grid[row][col];
int aliveNeighbors = 0;
if(!cell.isAlive())
return false;
for(int x = max(0, row-1); x <= min(row+1, (int) this->grid.size()-1); x++) {
for(int y = max(0, col-1); y <= min(col+1, (int) this->grid[row].size()-1); y++) {
if(x != row || y != col) {
if(this->grid[x][y].isAlive())
aliveNeighbors++;
}
}
}
return aliveNeighbors == 2 || aliveNeighbors == 3;
}
bool Tilemap::revive(int row, int col) {
// Function only returns true if cell is dead
Quad cell = this->grid[row][col];
int aliveNeighbors = 0;
// cout << "Here" << endl;
if(cell.isAlive())
return false;
for(int x = max(0, row-1); x <= min(row+1, (int) this->grid.size()-1); x++) {
for(int y = max(0, col-1); y <= min(col+1, (int) this->grid[row].size()-1); y++) {
if(x != row || y != col) {
// cout << "\tHere testing neighbor (" << x << "," << y << ")" << endl;
if(this->grid[x][y].isAlive())
aliveNeighbors++;
}
}
}
return aliveNeighbors == 3;
}