forked from JuanIrache/eloquent-javascript-exercises
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path18_3_gameOfLife.html
80 lines (73 loc) · 2.24 KB
/
18_3_gameOfLife.html
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
<div id="grid"></div>
<button id="next">Next generation</button>
<script>
class Grid {
constructor(width, height) {
this.width = width;
this.height = height;
this.cells = [];
for (let i = 0; i < width * height; i++) this.cells.push(false);
}
randomize() {
this.cells = this.cells.map(cell => (Math.random() < 0.5 ? true : false));
}
replace(cells) {
this.cells = cells;
}
update() {
let result = new Grid(this.width, this.height);
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
let cell = this.cells[y * this.width + x];
const neighbours = [];
for (let yy = Math.max(y - 1, 0); yy < Math.min(y + 2, this.height); yy++) {
for (let xx = Math.max(x - 1, 0); xx < Math.min(x + 2, this.width); xx++) {
if (xx !== x || yy !== y) neighbours.push(this.cells[yy * this.width + xx]);
}
}
const livingNei = neighbours.reduce((acc, curr) => (curr ? acc + 1 : acc), 0);
if (cell) {
if (livingNei > 3) cell = false;
if (livingNei < 2) cell = false;
} else if (livingNei === 3) cell = true;
result.cells[y * this.width + x] = cell;
}
}
return result;
}
}
function getCells() {
return (cells = Array.from(document.querySelectorAll('.cell')));
}
const height = 20;
const width = 60;
let grid = new Grid(width, height);
grid.randomize();
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let check = document.createElement('input');
check.type = 'checkbox';
check.className = 'cell';
document.querySelector('#grid').appendChild(check);
}
document.querySelector('#grid').appendChild(document.createElement('br'));
}
function updateDisplay() {
let cells = getCells();
for (let i = 0; i < cells.length; i++) {
cells[i].checked = grid.cells[i];
}
}
updateDisplay();
document.querySelector('#next').addEventListener('click', e => {
let cells = getCells().map(input => input.checked);
grid.replace(cells);
grid = grid.update();
updateDisplay();
});
</script>
<style>
.cell {
margin: 0;
}
</style>