```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; // apples const SPEEDUP_DELTA = 10; // ms 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 = 0; private high: number = 0; private tickMs: number = INITIAL_TICK_MS; private alive: boolean = true; private started: boolean = false; private paused: boolean = true; private timerId: number | null = null; constructor(canvas: HTMLCanvasElement, scoreEl: HTMLElement, highEl: HTMLElement) { this.canvas = canvas; this.ctx = canvas.getContext('2d')!; this.scoreEl = scoreEl; this.highEl = highEl; this.high = parseInt(localStorage.getItem('snake.high') || '0', 10); this.updateHighScoreDisplay(); this.resetState(); this.draw(); } 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.tickMs = INITIAL_TICK_MS; this.alive = true; this.started = false; this.paused = true; this.updateScoreDisplay(); this.spawnFood(); } private spawnFood(): void { while (true) { const newFood = { x: Math.floor(Math.random() * GRID), y: Math.floor(Math.random() * GRID), }; if (!this.snake.some(seg => seg.x === newFood.x && seg.y === newFood.y)) { this.food = newFood; break; } } } private updateScoreDisplay(): void { this.scoreEl.textContent = `Score: ${this.score}`; } private updateHighScoreDisplay(): void { this.highEl.textContent = `High: ${this.high}`; } private saveHighScore(): void { if (this.score > this.high) { this.high = this.score; localStorage.setItem('snake.high', this.high.toString()); this.updateHighScoreDisplay(); } } public start(): void { if (!this.started) { this.started = true; this.paused = false; this.tick(); } } public togglePause(): void { if (this.alive && this.started) { this.paused = !this.paused; if (!this.paused) { this.tick(); } else if (this.timerId) { clearTimeout(this.timerId); this.timerId = null; this.draw(); } } } public restart(): void { if (this.timerId) clearTimeout(this.timerId); this.timerId = null; this.resetState(); this.draw(); } public setDirection(nx: number, ny: number): void { // Prevent reverse-into-self if (nx === -this.dir.x && ny === -this.dir.y) return; this.pendingDir = { x: nx, y: ny }; } private tick(): void { if (!this.alive || this.paused) return; if (this.pendingDir) { this.dir = this.pendingDir; this.pendingDir = null; } const head = { x: this.snake[0].x + this.dir.x, y: this.snake[0].y + this.dir.y }; // Wall collision if (head.x < 0 || head.x >= GRID || head.y < 0 || head.y >= GRID) { this.gameOver(); return; } // Body collision (tail vacating is okay, so check from index 0 to length - 2) for (let i = 0; i < this.snake.length - 1; i++) { if (head.x === this.snake[i].x && head.y === this.snake[i].y) { this.gameOver(); return; } } this.snake.unshift(head); if (head.x === this.food.x && head.y === this.food.y) { this.score++; this.updateScoreDisplay(); this.spawnFood(); // Speed up every 5 apples if (this.score > 0 && this.score % SPEEDUP_EVERY === 0) { this.tickMs = Math.max(MIN_TICK_MS, this.tickMs - SPEEDUP_DELTA); } } else { this.snake.pop(); } this.draw(); this.timerId = window.setTimeout(() => this.tick(), this.tickMs); } private gameOver(): void { this.alive = false; this.saveHighScore(); this.draw(); if (this.timerId) clearTimeout(this.timerId); } private draw(): void { const ctx = this.ctx; ctx.fillStyle = '#000'; ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); // Apple ctx.fillStyle = '#c0392b'; ctx.fillRect(this.food.x * CELL, this.food.y * CELL, CELL, CELL); // Snake this.snake.forEach((seg, i) => { ctx.fillStyle = i === 0 ? '#7ed957'