-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
75 lines (62 loc) · 1.83 KB
/
index.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
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const resolution = 10;
canvas.width = 800;
canvas.height = 800;
const COLS = canvas.width / resolution;
const ROWS = canvas.height / resolution;
function buildGrid() {
return new Array(COLS).fill(null)
.map(() => new Array(ROWS).fill(null)
.map(() => Math.floor(Math.random() * 2)));
}
let grid = buildGrid();
requestAnimationFrame(update);
function update() {
grid = nextGen(grid);
render(grid);
requestAnimationFrame(update);
}
function nextGen(grid) {
const nextGen = grid.map(arr => [...arr]);
for (let col = 0; col < grid.length; col++) {
for (let row = 0; row < grid[col].length; row++) {
const cell = grid[col][row];
let numNeighbours = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
if (i === 0 && j === 0) {
continue;
}
const x_cell = col + i;
const y_cell = row + j;
if (x_cell >= 0 && y_cell >= 0 && x_cell < COLS && y_cell < ROWS) {
const currentNeighbour = grid[col + i][row + j];
numNeighbours += currentNeighbour;
}
}
}
// rules
if (cell === 1 && numNeighbours < 2) {
nextGen[col][row] = 0;
} else if (cell === 1 && numNeighbours > 3) {
nextGen[col][row] = 0;
} else if (cell === 0 && numNeighbours === 3) {
nextGen[col][row] = 1;
}
}
}
return nextGen;
}
function render(grid) {
for (let col = 0; col < grid.length; col++) {
for (let row = 0; row < grid[col].length; row++) {
const cell = grid[col][row];
ctx.beginPath();
ctx.rect(col * resolution, row * resolution, resolution, resolution);
ctx.fillStyle = cell ? 'black' : 'white';
ctx.fill();
// ctx.stroke();
}
}
}