-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
98 lines (84 loc) · 2.55 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#game {
width: 100vw;
height: 100vh;
display: grid;
}
</style>
</head>
<body>
<div id="game">
</div>
<script type="module">
const divGame = document.getElementById('game');
const { clientWidth, clientHeight } = divGame;
const rows = 50;
const cols = Math.trunc((clientWidth * rows) / clientHeight);
const cells = cols * rows;
async function instantiate() {
let importObject = {
game: {
memory: new WebAssembly.Memory({ initial: 1, maximum: 10 }),
cols: new WebAssembly.Global({ value: "i32", mutable: false }, cols),
rows: new WebAssembly.Global({ value: "i32", mutable: false }, rows),
}
}
const { instance } = await WebAssembly.instantiateStreaming(fetch('life.wasm'), importObject);
return { instance, dataView: new DataView(importObject.game.memory.buffer) };
}
function randomizeGame(data) {
for (let i = 0; i < cols * rows; i++) {
data.setUint8(i, Math.floor(Math.random() * 2));
}
}
let colors = Array.from({ length: cols }, (_, i) => {
const hue = Math.round((i / (cols - 1)) * 360);
return `hsl(${hue}, 100%, 60%)`;
});
function drawBoard() {
let contents = '';
for (let i = 0; i < cells; i++) {
contents += `<div id="cell_${i}"></div>`
}
divGame.style = `grid-template-columns: repeat(${cols}, 1fr); grid-template-rows: repeat(${rows}, 1fr);`
divGame.innerHTML = contents;
}
let colorOffset = 0;
function renderGame(dataView) {
for (let i = 0; i < cells; i++) {
const x = i % cols;
const colorIndex = (x + colorOffset) % colors.length;
const cell = document.getElementById(`cell_${i}`);
if (dataView.getUint8(i) !== 0) {
cell.style = `background-color: ${colors[colorIndex]};`;
} else {
cell.style = 'background-color: #000;';
}
}
colorOffset++;
if (colorOffset >= colors.length) colorOffset = 0;
}
drawBoard();
const { instance, dataView } = await instantiate();
randomizeGame(dataView);
setInterval(() => {
instance.exports.tick();
renderGame(dataView);
}, 250);
</script>
</body>
</html>