```html
Snake
Snake
Score: 0
High: 0
Arrow keys or WASD to move · Space to start/pause · R to restart
```
```typescript
type Cell = { x: number; y: number };
type Direction = { x: number; y: number };
const GRID = 20;
const CELL = 20;
const INITIAL_TICK_MS = 150;
const MIN_TICK_MS = 60;
const SPEEDUP_EVERY = 5;
const SPEEDUP_DELTA = 10;
const COLOR_BG = "#000";
const COLOR_BODY = "#3aa635";
const COLOR_HEAD = "#7ed957";
const COLOR_FOOD = "#c0392b";
const COLOR_TEXT = "#fff";
const HIGH_KEY = "snake.high";
class Game {
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
private scoreEl: HTMLElement;
private highEl: HTMLElement;
private snake!: Cell[];
private dir!: Direction;
private pendingDir: Direction | null = null;
private food!: Cell;
private score!: number;
private high!: number;
private tickMs!: number;
private alive!: boolean;
private started!: boolean;
private paused!: boolean;
private timer: number | null = null;
constructor(canvas: HTMLCanvasElement, scoreEl: HTMLElement, highEl: HTMLElement) {
this.canvas = canvas;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("no 2d context");
this.ctx = ctx;
this.scoreEl = scoreEl;
this.highEl = highEl;
this.loadHighScore();
this.resetState();
this.render();
}
private loadHighScore(): void {
const storedHigh = localStorage.getItem(HIGH_KEY);
this.high = storedHigh ? Number(storedHigh) : 0;
}
start(): void {
if (!this.started) {
this.started = true;
this.paused = false;
this.resetState();
this.spawnFood();
this.tickMs = INITIAL_TICK_MS;
this.timer = setInterval(() => this.step(), this.tickMs);
}
}
togglePause(): void {
if (this.started && !this.paused) {
this.paused = true;
clearInterval(this.timer);
} else if (this.paused) {
this.paused = false;
this.timer = setInterval(() => this.step(), this.tickMs);
}
}
restart(): void {
this.resetState();
this.spawnFood();
this.score = 0;
this.high = Math.max(this.high, this.score);
this.updateScoreDom();
this.render();
}
private step(): void {
if (this.pendingDir && !this.wouldCollide({ x: this.snake[0].x + this.pendingDir.x, y: this.snake[0].y + this.pendingDir.y }, false)) {
this.dir = this.pendingDir;
this.pendingDir = null;
}
const head: Cell = { x: this.snake[0].x + this.dir.x, y: this.snake[0].y + this.dir.y };
if (this.wouldCollide(head, true)) {
this.alive = false;
clearInterval(this.timer);
this.render();
return;
}
this.snake.unshift(head);
if (head.x === this.food.x && head.y === this.food.y) {
this.score++;
this.high = Math.max(this.high, this.score);
localStorage.setItem(HIGH_KEY, String(this.high));
this.updateScoreDom();
this.spawnFood();
} else {
this.snake.pop();
}
if (this.score % SPEEDUP_EVERY === 0 && this.tickMs > MIN_TICK_MS) {
this.tickMs -= SPEEDUP_DELTA;
clearInterval(this.timer);
this.timer = setInterval(() => this.step(), this.tickMs);
}
this.render();
}
private resetState(): void {
this.snake = [{ x: 10, y: 10 }, { x: 9, y: 10 }, { x: 8, y: 10 }];
this.dir = { x: 1, y: 0 };
this.pendingDir = null;
this.score = 0;
this.alive = true;
this.started = false;
this.paused = true;
}
private spawnFood(): void {
let food: Cell;
do {
food = { x: Math.floor(Math.random() * GRID), y: Math.floor(Math.random() * GRID) };
} while (this.snake.some(segment => segment.x === food.x && segment.y === food.y));
this.food = food;
}
private updateScoreDom(): void {
this.scoreEl.textContent = `Score: ${this.score}`;
this.highEl.textContent = `High: ${this.high}`;
}
private render(): void {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = COLOR_BG;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
if (!this.started) {
this.ctx.font = "20px sans-serif";
this.ctx.textAlign = "center";
this.ctx.fillStyle = COLOR_TEXT;
this.ctx.fillText("Press Space to start", this.canvas.width / 2, this.canvas.height / 2);
} else if (this.paused) {
this.ctx.font = "20px sans-serif";
this.ctx.textAlign = "center";
this.ctx.fillStyle = COLOR_TEXT;
this.ctx.fillText("Paused", this.canvas.width / 2, this.canvas.height / 2);
} else if (!this.alive) {
this.ctx.font = "20px sans-serif";
this.ctx.textAlign = "center";
this.ctx.fillStyle = COLOR_TEXT;
this.ctx.fillText("Game Over — press R to restart", this.canvas.width / 2, this.canvas.height / 2);
} else {
this.ctx.fillStyle = COLOR_FOOD;
this.ctx.fillRect(this.food.x * CELL, this.food.y * CELL, CELL, CELL);
for (let i = 0; i < this.snake.length; i++) {
const segment = this.snake[i];
if (i === 0) {
this.ctx.fillStyle = COLOR_HEAD;
} else {
this.ctx.fillStyle = COLOR_BODY;
}
this.ctx.fillRect(segment.x * CELL, segment.y * CELL, CELL, CELL);
}
}
}
private wouldCollide(cell: Cell, willGrow: boolean): boolean {
if (cell.x < 0 || cell.x >= GRID || cell.y < 0 || cell.y >= GRID) return true;
for (let i = 1; i < this.snake.length - (willGrow ? 0 : 1); i++) {
if (this.snake[i].x === cell.x && this.snake[i].y === cell.y) return true;
}
return false;
}
public setPendingDir(d: Direction): void {
this.pendingDir = d;
}
}
// ---- top-level wiring ----
const canvas = document.getElementById("game") as HTMLCanvasElement;
const scoreEl = document.getElementById("score") as HTMLElement;
const highEl = document.getElementById("high") as HTMLElement;
const game = new Game(canvas, scoreEl, highEl);
window.addEventListener("keydown", (e) => {
switch (e.key) {
case "ArrowUp":
case "w":
game.setPendingDir({ x: 0, y: -1 });
break;
case "ArrowDown":
case "s":
game.setPendingDir({ x: 0, y: 1 });
break;
case "ArrowLeft":
case "a":
game.setPendingDir({ x: -1, y: 0 });
break;
case "ArrowRight":
case "d":
game.setPendingDir({ x: 1, y: 0 });
break;
case " ":
game.togglePause();
break;
case "r":
game.restart();
break;
}
e.preventDefault();
});
```