-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame-of-life.js
93 lines (70 loc) · 1.89 KB
/
game-of-life.js
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
const resolution = 5;
const width = 500;
const height = 500;
const cols = width / resolution;
const rows = height / resolution;
const interval = 50;
const canvas = document.getElementById('game');
const context = canvas.getContext('2d');
const fillStyle = '#000';
let Game = {
start: function () {
canvas.setAttribute('width', width + 1);
canvas.setAttribute('height', height + 1);
let grid = new Grid();
grid.draw();
setInterval(function () {
grid.step();
}, interval);
}
};
function Grid() {
this.cells = [];
for (let i = 0; i < cols; i++) {
this.cells[i] = [];
for (let j = 0; j < rows; j++) {
this.cells[i][j] = Math.round(Math.random());
}
}
this.draw = function () {
context.clearRect(0, 0, width, height);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
if (this.cells[i][j] == 0) continue;
context.fillStyle = fillStyle;
context.fillRect(i * resolution, j * resolution, resolution, resolution);
}
}
};
this.step = function () {
let next = JSON.parse(JSON.stringify(this.cells));
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = this.cells[i][j];
let neighbours = this.countNeighbours(i, j, this.cells);
if (state == 0 && neighbours == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbours < 2 || neighbours > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
this.cells = next;
this.draw();
};
this.countNeighbours = function (x, y, cells) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += cells[col][row];
}
}
sum -= cells[x][y];
return sum;
};
}
Game.start();