-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
95 lines (83 loc) · 2.73 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
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Game on WASM</title>
</head>
<body style="text-align: center">
<h3>Snake on
<a href="https://en.wikipedia.org/wiki/C_(programming_language)" target="_blank">C</a> language,
<a href="https://en.wikipedia.org/wiki/WebAssembly" target="_blank">WebAssembly</a> and
<a href="https://en.wikipedia.org/wiki/Canvas_element">Canvas</a>
</h3>
<canvas id="canvas" width="600" height="600"></canvas>
<p>Use <strong>Up / Down / Left / Right</strong> key on keyboard for move snake</p>
</body>
<script>
(async () => {
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext("2d");
let env = {
print: function(m) {
console.log(m);
},
jsSetInterval: function (f, n) {
return setInterval(function () {
instance.exports.runCallback(f);
}, n);
},
jsClearInterval: function (index) {
clearInterval(index);
},
jsFillRect: function (x, y, w, h, color) {
ctx.fillStyle = '#' + color.toString(16).padStart(6, 0);
ctx.fillRect(x, y, w, h);
},
jsClearRect: function (x, y, w, h) {
ctx.clearRect(x, y, w, h);
},
alert: function (code) {
switch (code) {
case 1: alert('Game over'); break;
}
},
random(min, max) {
return Math.floor(min + Math.random() * (max + 1 - min));
}
};
let wasm = fetch('app.wasm');
let result;
if (WebAssembly.instantiateStreaming) {
result = await WebAssembly.instantiateStreaming(wasm, {env: env});
} else {
let response = await wasm;
let buffer = await response.arrayBuffer();
result = await WebAssembly.instantiate(buffer, {env: env});
}
const instance = result.instance
instance.exports.main();
canvas.addEventListener('mouseup', function (event) {
let mouseX = event.pageX - canvas.offsetLeft;
let mouseY = event.pageY - canvas.offsetTop;
instance.exports.handleClick(mouseX, mouseY)
});
document.addEventListener('keyup', function (event) {
switch (event.key) {
case "ArrowRight":
instance.exports.handleKeyPress(0);
break;
case "ArrowDown":
instance.exports.handleKeyPress(1);
break;
case "ArrowLeft":
instance.exports.handleKeyPress(2);
break;
case "ArrowUp":
instance.exports.handleKeyPress(3);
break;
}
})
})();
</script>
</html>