Snake

TypeScriptCanvasGame loopKeyboard controls

Guide the snake through a tile grid, collect food, and avoid collisions with the walls or your own body. This version is a compact TypeScript and canvas implementation: React mounts the canvas, while refs hold snake, direction, and apple state for frame-by-frame updates.

Built in TypeScript. Explore more projects on Projects

How it works

A compact grid-based Snake implementation rendered on HTML canvas. Direction and positions live outside React render state, while the shared game hook owns the canvas, game loop, keyboard input, and touch controls.

Implementation notes

The shared canvas hook initializes the drawing context, runs the default 20 FPS loop, and wires keyboard plus touch input.

Snake segments, direction, and apple position live in refs so each frame can update without triggering React renders.

The next head tile is checked against the board bounds and every current segment; a collision restarts the round.

Apple spawning retries random tile positions so food does not appear inside the snake body.

Controls

MoveArrow keysWASD
TouchOn-screen arrows