Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
94 lines (81 loc) · 2.4 KB
/
Copy pathmain.js
File metadata and controls
94 lines (81 loc) · 2.4 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
import { CanvasRenderer } from './web/canvas-renderer.js';
import { formatGrid } from './lib/util.js';
import { Grid } from './lib/grid.js';
import { Game } from './lib/game.js';
// Prepare renderer stage and grid layout
const renderer = new CanvasRenderer(document);
const [xLen, yLen] = renderer.drawGrid();
console.log(`Rendered grid with cell layout ${xLen},${yLen}`);
// Setup buttons
/** @type {HTMLButtonElement} */
const btnStart = document.getElementById('btnStart');
btnStart.addEventListener('pointerup', startButtonListener);
/** @type {HTMLButtonElement} */
const btnTick = document.getElementById('btnTick');
btnTick.addEventListener('pointerdown', doTick);
/** @type {HTMLOutputElement} */
const intervalLabel = document.getElementById('lbl-ticks-sec');
/** @type {HTMLInputElement} */
const slider = document.getElementById('interval-slider');
intervalLabel.value = slider.value;
slider.addEventListener('input', updateIntervalLabel);
slider.addEventListener('change', applyInterval);
// create grid
const grid = new Grid(xLen, yLen);
// load game
const game = new Game(grid, renderer.cellToggled);
// init tick value from element
slider.dispatchEvent(new Event('change'));
// load preset
const glider = [
[0, 2],
[1, 3],
[2, 1],
[2, 2],
[2, 3],
];
grid.activateCells(glider);
renderer.activateCells(glider);
console.log(formatGrid(grid.getGrid()));
// Listen for state changes and update view as needed
grid.changeEmitter.asObservable().subscribe({
next: ([x, y, state]) => {
console.log(`Saw state change: ${x},${y}=${state}`);
renderer.setCellState(x, y, state);
},
});
/**
* @type {EventListener}
* @param event {MouseEvent}
*/
function startButtonListener(event) {
console.log('Button clicked');
console.log(event);
if (game.isRunning) {
game.stop();
event.target.textContent = 'Start';
} else {
game.start();
event.target.textContent = 'Stop';
}
}
/**
* @type {EventListener}
* @param event {MouseEvent}
*/
function doTick(event) {
console.log('Tick clicked');
console.log(event);
game.tick();
}
/** @param {InputEvent} ev */
function updateIntervalLabel(ev) {
intervalLabel.value = ev.target.value;
}
/** @param {Event} ev */
function applyInterval(ev) {
const ticksPerSecond = ev.target.valueAsNumber;
const intervalMillis = (1 / ticksPerSecond) * 1000;
console.log(`Setting interval to ${intervalMillis} ms`);
game.tickInterval = intervalMillis;
}