Snake is the project everyone builds once — I wanted to actually finish mine end to end instead of leaving it half-done like the first two attempts.
0. the idea
1. how it works
Under the hood:
- HTML canvas for rendering
- A game loop driven by requestAnimationFrame
- Grid-based movement and collision detection
- Vanilla JavaScript, no framework, no build step
2. features
What it does:
- Keyboard-controlled movement
- Score tracking with a persisted high score
- Speed increases as the snake grows
- Game-over screen with instant retry
3. a challenge — the 180° turn bug
Tap the opposite direction key twice fast enough and the snake would reverse directly into its own neck and 'die' instantly — a bug caused by reading two keypresses in the same frame before the snake had actually moved.
Buffer the next direction and only apply it on the next tick of the game loop, and reject any direction that's the exact opposite of the current one. That one guard fixes the instant-death bug completely.
4. the code
function setDirection(next) {
const isOpposite =
next.x === -direction.x && next.y === -direction.y;
if (!isOpposite) {
pendingDirection = next;
}
}
function tick() {
direction = pendingDirection;
moveSnake(direction);
}5. what i learned
Even a project this small has a real lesson in it: input handling and game state updates need to be on the same clock, or you get exactly this kind of 'technically correct, feels broken' bug.