This repository has been archived by the owner on Feb 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
game.js
88 lines (71 loc) · 2.29 KB
/
game.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
var mainElement = document.getElementById('main');
if (mainElement) {
var game = Life(mainElement);
document.getElementById('step_btn')
.addEventListener('click', () => game.step());
document.getElementById('clear_btn')
.addEventListener('click', game.clear);
document.getElementById('play_btn')
.addEventListener('click', game.togglePlaying);
document.getElementById('reset_btn')
.addEventListener('click', game.random);
}
function Life(container, width=12, height=12) {
var present = new Board(width, height);
var future = new Board(width, height);
const cells = [];
var table = createTable();
container.appendChild(table);
table.addEventListener('mousedown', toggleCellFromEvent);
function createTable() {
var table = document.createElement('table'); // <table
table.classList.add('board'); // class='board'>
for (var r = 0; r < height; r++) {
var tr = document.createElement('tr'); // <tr>
for (var c = 0; c < width; c++) { // For instance, at r=2, c=3:
var td = document.createElement('td'); // <td
td.id = `${r}-${c}`; // id="2-3">
td.coord = [r, c];
tr.appendChild(td);
cells.push(td); // </td>
}
table.appendChild(tr); // </tr>
} // </table>
return table;
}
function toggleCellFromEvent(event) {
present.toggle(event.target.coord);
paint();
}
function paint() {
let i = cells.length; while (--i >= 0) {
const td = cells[i]
if (present.get(td.coord))
td.classList.add('alive')
else
td.classList.remove('alive')
}
}
function step(rules) {
;[present, future] = tick(present, future, rules);
paint();
}
let interval = null;
function play() {
interval = setInterval(step, 113);
}
function stop() {
clearInterval(interval);
interval = null;
}
function togglePlaying() {
interval ? stop() : play();
}
function clear() {
step(() => 0);
}
function random() {
step(() => Math.round(Math.random()));
}
return {play, step, stop, togglePlaying, random, clear};
}