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 = localStorage.getItem(HIGH_KEY) ? parseInt(localStorage.getItem(HIGH_KEY)!) : 0; this.resetState(); 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) { 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.paused = !this.paused; if (this.paused) { clearInterval(this.timer!); this.timer = null; } else { this.timer = setInterval(() => this.step(), this.tickMs); } } else { this.start(); } } /** Full reset to the initial paused-before-start state, then render. Clears the tick interval if running. */ restart(): void { clearInterval(this.timer!); this.timer = null; this.resetState(); 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) { if (!(this.pendingDir.x === -this.dir.x && this.pendingDir.y === -this.dir.y)) { 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 }; this.snake.unshift(head); if (this.wouldCollide(head, false)) { this.alive = false; clearInterval(this.timer!); this.timer = null; this.render(); return; } if (this.food.x === head.x && this.food.y === head.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(this.tickMs - SPEEDUP_DELTA, MIN_TICK_MS); 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.updateScoreDom(); 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 { let emptyCells: Cell[] = []; for (let y = 0; y < GRID; y++) { for (let x = 0; x < GRID; x++) { if (!this.snake.some(cell => cell.x === x && cell.y === y)) { emptyCells.push({ x, y }); } } } if (emptyCells.length === 0) { this.alive = false; clearInterval(this.timer!); this.timer = null; this.render(); } else { this.food = emptyCells[Math.floor(Math.random() * emptyCells.length)]; } } /** 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.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.alive) { this.ctx.font = '20px sans-serif'; this.ctx.fillStyle = COLOR_TEXT; this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; if (this.started) { this.ctx.fillText('Game Over — press R to restart', this.canvas.width / 2, this.canvas.height / 2); } else { this.ctx.fillText('Press Space to start', 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 cell = this.snake[i]; this.ctx.fillStyle = i === 0 ? COLOR_HEAD : COLOR_BODY; this.ctx.fillRect(cell.x * CELL, cell.y * CELL, CELL, CELL); } if (this.paused) { this.ctx.font = '20px sans-serif'; this.ctx.fillStyle = COLOR_TEXT; this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; this.ctx.fillText('Paused', this.canvas.width / 2, this.canvas.height / 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 { return cell.x < 0 || cell.x >= GRID || cell.y < 0 || cell.y >= GRID || (!willGrow && this.snake.some(snakeCell => snakeCell.x === cell.x && snakeCell.y === cell.y)); } 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': 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; default: return; } e.preventDefault(); }); ```