-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameSimulation.js
More file actions
101 lines (76 loc) · 2.17 KB
/
gameSimulation.js
File metadata and controls
101 lines (76 loc) · 2.17 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class GameSimulation {
// INITIALIZATION
constructor(size) {
this.size = size;
this.entities = this.initEntities(this.size);
}
// FUNCTIONS
// Update: Simulate a round
update() {
const updateRelatives = [[-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]];
const updateStates = [];
for (var row = 0; row < this.size; row++) {
const rowStates = [];
for (var col = 0; col < this.size; col++) {
const neighborStates = [];
for (const neighbor of updateRelatives) {
const neighborRow = row + neighbor[0];
const neighborCol = col + neighbor[1];
if (neighborRow < 0 || neighborRow >= this.size || neighborCol < 0 || neighborCol >= this.size) {
neighborStates.push(0);
} else {
neighborStates.push(this.entities[neighborRow][neighborCol]);
}
}
let neighborSum = 0;
for (var i = 0; i < neighborStates.length; i++) {
neighborSum += neighborStates[i];
}
if (this.entities[row][col] && (neighborSum < 2 || neighborSum > 3)) {
rowStates.push(0);
} else if (neighborSum == 3) {
rowStates.push(1);
} else {
rowStates.push(this.entities[row][col]);
}
}
updateStates.push(rowStates);
}
this.setEntities(updateStates);
}
// Set Entities
setEntitiesSafe(entityArray) {
for (var row = 0; row < this.size; row++) {
for (var col = 0; col < this.size; col++) {
this.entities[row][col] = entityArray[row][col];
}
}
}
setEntities(entityArray) {
this.entities = entityArray;
}
// Get Entities
getEntities() {
return this.entities;
}
// Bear a new Enitity
bearEntity(row, col) {
this.entities[row][col] = 1;
}
// Kill an Entity
killEntity(row, col) {
this.entities[row][col] = 0;
}
// Initialize Entities
initEntities() {
const entitiesArray = [];
for (var i = 0; i < this.size; i++) {
const rowArray = [];
for (var j = 0; j < this.size; j++) {
rowArray.push(0);
}
entitiesArray.push(rowArray);
}
return entitiesArray;
}
}