Skip to content

Instantly share code, notes, and snippets.

@MattRoelle
Created January 14, 2024 06:17
Show Gist options
  • Save MattRoelle/edb6bba685a48f8288aa7535c0ce0ae7 to your computer and use it in GitHub Desktop.
Save MattRoelle/edb6bba685a48f8288aa7535c0ce0ae7 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="root"></canvas>
<script>
window.addEventListener("DOMContentLoaded", () => {
const SZ = 256;
const TILE_SZ = SZ / 16;
const canvas = document.getElementById("root");
canvas.width = SZ;
canvas.height = SZ;
const ctx = canvas.getContext("2d");
const state = {
pos: [[8, 8]],
direction: [1, 0],
apple: [10, 10],
length: 3,
};
window.addEventListener("keydown", ev => {
if (ev.key === "ArrowUp") {
state.direction = [0, -1];
} else if (ev.key === "ArrowDown") {
state.direction = [0, 1];
} else if (ev.key === "ArrowLeft") {
state.direction = [-1, 0];
} else if (ev.key === "ArrowRight") {
state.direction = [1, 0];
}
});
setInterval(() => {
let [x, y] = state.pos[0];
x += state.direction[0];
y += state.direction[1];
if (x < 0) {
x = 16;
} else if (x > 16) {
x = 0;
}
if (y < 0) {
y = 16;
} else if (y > 16) {
y = 0;
}
if (x === state.apple[0] && y === state.apple[1]) {
state.apple = [Math.floor(Math.random() * 16), Math.floor(Math.random() * 16)];
state.length += 1;
}
for (let i = 0; i < state.pos.length; i++) {
const [px, py] = state.pos[i];
if (px === x && py === y) {
state.pos = [[8, 8]];
state.direction = [1, 0];
state.apple = [10, 10];
state.length = 3;
break;
}
}
state.pos.unshift([x, y]);
while (state.pos.length > state.length) {
state.pos.pop();
}
ctx.clearRect(0, 0, SZ, SZ);
ctx.fillStyle = "#000000";
for (let i = 0; i < state.pos.length; i++) {
const [x, y] = state.pos[i];
ctx.fillRect(x * TILE_SZ, y * TILE_SZ, TILE_SZ, TILE_SZ);
}
ctx.fillStyle = "#ff0000";
ctx.fillRect(state.apple[0] * TILE_SZ, state.apple[1] * TILE_SZ, TILE_SZ, TILE_SZ);
}, 100);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment