```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.high = Number(localStorage.getItem(HIGH_KEY)) || 0; this.resetState(); this.updateScoreDom(); this.render(); } /** Begin the game on first Space press: started=true, paused=false, start the tick interval. No-op if already started. */ start(): void { if (this.started) return; this.started = true; this.paused = false; this.timer = setInterval(() => this.step(), this.tickMs); } /** Toggle pause on/off during a running game. If not yet started, behave like start(). When unpausing, re-arm the interval. When pausing, clear it. */ togglePause(): void { if (!this.started) { this.start(); return; } if (this.paused) { this.paused = false; this.timer = setInterval(() => this.step(), this.tickMs); } else { this.paused = true; if (this.timer !== null) { clearInterval(this.timer); this.timer = null; } } } /** Full reset to the initial paused-before-start state, then render. Clears the tick interval if running. */ restart(): void { if (this.timer !== null) { clearInterval(this.timer); this.timer = null; } this.resetState(); this.updateScoreDom(); this.render(); } /** Apply pendingDir if it is not the opposite of the current dir, then move the snake one cell, detect wall/self collisions, handle food, and render. Called once per tick interval. */ private step(): void { if (this.pendingDir && !(this.pendingDir.x === -this.dir.x && this.pendingDir.y === -this.dir.y)) { this.dir = this.pendingDir; this.pendingDir = null; } const newHead: Cell = { x: this.snake[0].x + this.dir.x, y: this.snake[0].y + this.dir.y }; if (this.wouldCollide(newHead, false)) { this.alive = false; if (this.timer !== null) { clearInterval(this.timer); this.timer = null; } this.render(); return; } this.snake.unshift(newHead); if (newHead.x === this.food.x && newHead.y === this.food.y) { this.score++; if (this.score > this.high) { this.high = this.score; localStorage.setItem(HIGH_KEY, this.high.toString()); } this.updateScoreDom(); this.spawnFood(); if (this.score % SPEEDUP_EVERY === 0) { this.tickMs = Math.max(MIN_TICK_MS, this.tickMs - SPEEDUP_DELTA); if (this.timer !== null) { clearInterval(this.timer); } this.timer = setInterval(() => this.step(), this.tickMs); } } else { this.snake.pop(); } this.render(); } /** Set snake (length 3 at (10,10), (9,10), (8,10) moving right), reset dir/pendingDir/score/tickMs/alive/started/paused, spawn food. */ 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.spawnFood(); } /** Pick a random Cell that is not currently occupied by the snake. If no empty cell, treat as win (alive=false, render). */ private spawnFood(): void { const totalCells = GRID * GRID; if (this.snake.length >= totalCells) { this.alive = false; this.render(); return; } let x: number, y: number; do { x = Math.floor(Math.random() * GRID); y = Math.floor(Math.random() * GRID); } while (this.snake.some(cell => cell.x === x && cell.y === y)); this.food = { x, y }; } /** Update the score and high DOM elements with "Score: N" / "High: N". */ private updateScoreDom(): void { this.scoreEl.textContent = `Score: ${this.score}`; this.highEl.textContent = `High: ${this.high}`; } /** Clear and redraw the board: black bg, food, snake body, snake head (distinct color). On not-yet-started, draw centered "Press Space to start". On paused (after first start), draw centered "Paused". On game-over, draw centered "Game Over — press R to restart". Text 20px sans-serif white, centered. */ private render(): void { this.ctx.fillStyle = COLOR_BG; this.ctx.fillRect(0, 0, GRID * CELL, GRID * CELL); this.ctx.fillStyle = COLOR_FOOD; this.ctx.fillRect(this.food.x * CELL, this.food.y * CELL, CELL, CELL); this.snake.forEach((cell, index) => { this.ctx.fillStyle = index === 0 ? COLOR_HEAD : COLOR_BODY; this.ctx.fillRect(cell.x * CELL, cell.y * CELL, CELL, CELL); }); this.ctx.fillStyle = COLOR_TEXT; this.ctx.font = "20px sans-serif"; this.ctx.textAlign = "center"; let text = ""; if (!this.started) { text = "Press Space to start"; } else if (this.paused) { text = "Paused"; } else if (!this.alive) { text = "Game Over — press R to restart"; } if (text) { this.ctx.fillText(text, (GRID * CELL) / 2, (GRID * CELL) / 2); } } /** True iff `cell` lies inside the grid AND is not occupied by `snake` (excluding the soon-to-vacate tail when not growing). */ 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 = 0; i < this.snake.length; i++) { if (willGrow || i !== this.snake.length - 1) { if (this.snake[i].x === cell.x && this.snake[i].y === cell.y) return true; } } return false; } public setPendingDir(dir: Direction): void { this.pendingDir = dir; } } // ---- top-level wiring (fill in) ---- 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": case "W": game.setPendingDir({ x: 0, y: -1 }); break; case "ArrowDown": case "s": case "S": game.setPendingDir({ x: 0, y: 1 }); break; case "ArrowLeft": case "a": case "A": game.setPendingDir({ x: -1, y: 0 }); break; case "ArrowRight": case "d": case "D": game.setPendingDir({ x: 1, y: 0 }); break; case " ": game.togglePause(); break; case "r": case "R": game.restart(); break; default: return; } e.preventDefault(); }); ```