-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspectator.html
More file actions
89 lines (83 loc) · 2.41 KB
/
Copy pathspectator.html
File metadata and controls
89 lines (83 loc) · 2.41 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Snake Spectator</title>
<style>
body {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
background: #1e1e1e;
color: #e0e0e0;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
#wrap {
display: flex;
flex-direction: column;
gap: 8px;
align-items: center;
}
canvas {
background: #6f6f6f;
image-rendering: pixelated;
border: 2px solid #111;
}
#status {
font-size: 14px;
opacity: 0.8;
}
</style>
</head>
<body>
<div id="wrap">
<canvas id="view" width="450" height="450"></canvas>
<div id="status">Connecting…</div>
</div>
<script>
const canvas = document.getElementById("view");
const ctx = canvas.getContext("2d");
const status = document.getElementById("status");
function draw(snapshot) {
const { width, height, snake, food, score, state, tick } = snapshot;
const cell = Math.floor(Math.min(canvas.width / width, canvas.height / height));
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#6f6f6f";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#0f0";
for (const [x, y] of snake) {
ctx.fillRect(x * cell, y * cell, cell, cell);
}
if (food) {
ctx.fillStyle = "#d40000";
ctx.fillRect(food[0] * cell, food[1] * cell, cell, cell);
}
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, cell);
ctx.fillStyle = "#fff";
ctx.font = "12px monospace";
ctx.fillText(`score: ${score} state: ${state} tick: ${tick}`, 6, 14);
}
const ws = new WebSocket(`ws://${location.hostname}:9001`);
ws.onopen = () => {
status.textContent = "Connected";
};
ws.onclose = () => {
status.textContent = "Disconnected";
};
ws.onerror = () => {
status.textContent = "Error";
};
ws.onmessage = (evt) => {
try {
const snapshot = JSON.parse(evt.data);
draw(snapshot);
} catch (err) {
console.error(err);
}
};
</script>
</body>
</html>