Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ac-unefm/snake-game/llms.txt

Use this file to discover all available pages before exploring further.

Snake Classic Game is a self-contained browser Snake game and a didactic reference for modern web fundamentals — all living inside a single index.html file (~50 KB). The entire experience is written in HTML5, CSS3, and vanilla JavaScript ES2020 with zero frameworks, zero npm dependencies, and zero build steps. Open the file in any modern browser and the game runs instantly. The source is intentionally structured to demonstrate that complete, accessible, and production-quality web applications can be built using only the platform’s native capabilities.

Key Features

Zero Dependencies

No npm, no webpack, no React, no external libraries. One file — index.html — contains everything: markup, styles, and logic.

Progressive Difficulty

Speed increases automatically every 5 points. The game loop tightens from a 130 ms base tick down to a 45 ms floor as the player levels up.

Session System

Each session groups 5 consecutive attempts. A dot indicator tracks progress, and a results panel displays per-attempt and aggregate statistics at the end.

localStorage Persistence

The all-time best score is saved to localStorage with a try/catch guard so the game degrades gracefully in restricted environments.

Responsive & Touch Support

Scales to desktop, tablet, and mobile. Supports swipe gestures on the canvas, a dynamic D-pad shown on touch screens, and landscape-mode layout adjustments.

Native Dark Mode

Colors are defined as CSS custom properties and the UI adapts automatically to the OS dark-mode preference — no toggle required.

Full Keyboard Accessibility

Every interaction is reachable by keyboard: arrow keys to steer, Enter/Space to start, H/? to open help, Escape to close modals, and a skip-link to jump straight to the game.

WAI-ARIA 1.2

Live regions (aria-live), modal dialogs (aria-modal, focus trap), semantic roles, aria-describedby wiring, and a visually-hidden alert node for screen-reader announcements.

Content Security Policy

A <meta http-equiv="Content-Security-Policy"> tag restricts resource loading to inline styles and scripts only — no external network calls permitted.

Canvas 2D Rendering

The game board is drawn entirely with the Canvas 2D API: grid lines, rounded-rectangle snake segments using arcTo, and a pulsing food particle with shadowBlur glow.

Reduced Motion Support

A window.matchMedia('(prefers-reduced-motion: reduce)') check disables the food-pulse animation and holds shadowBlur at a fixed value, respecting the OS accessibility setting.

What It Demonstrates

The source code is a practical tour of browser-native APIs and engineering practices:
1

Dynamic Game Loop with setTimeout

The loop is driven by a recursive setTimeout rather than requestAnimationFrame, which lets the tick interval change in real time to implement progressive difficulty. scheduleNext() recomputes the delay from the current score on every frame.
2

Canvas 2D — save/restore, shadowBlur, arcTo

draw() clears the canvas, paints the grid, then calls drawFood() and drawSegment(). Each draw call wraps side-effect styles (shadowBlur, fillStyle) in ctx.save() / ctx.restore(). Snake head segments use arcTo to produce rounded corners. The food particle animates radius and shadow intensity using Math.sin(Date.now()), with the animation disabled when prefers-reduced-motion is set.
3

CSS Custom Properties + clamp()

All palette values are declared as --color-* variables on :root, making it trivial to retheme. Spacing in the HUD uses clamp(12px, 5vw, 40px) so the layout is fluid between breakpoints without media query overrides.
4

Touch Events API — Swipe Detection

touchstart records clientX/Y; touchend computes deltaX and deltaY. If the displacement exceeds SWIPE_MIN_PX (20 px), the dominant axis determines direction. Sub-threshold touches are treated as taps to start or continue the game. touch-action: none on the canvas prevents the browser from claiming the gesture for scrolling.
5

WAI-ARIA 1.2 — aria-live, aria-modal, Focus Trap

The score and level counters carry aria-live="polite" and aria-atomic="true". A hidden role="alert" node is emptied and re-filled with a 50 ms delay to force screen readers to re-announce it. Dialogs set aria-modal="true", aria-hidden is toggled on open/close, and focus is programmatically moved to the first interactive element inside the panel.
6

localStorage with try/catch

readBestScore() and saveBestScore() each wrap their localStorage calls in try/catch, returning a safe fallback value (0) when storage is unavailable (private browsing, quota exceeded, sandboxed iframe).
7

Content Security Policy via Meta Tag

The <meta http-equiv="Content-Security-Policy"> header applies default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline' — blocking all external network requests without requiring server-side header configuration.
8

Anti-XSS DOM Construction with createElement

The session results panel builds every <tr> and <td> imperatively with document.createElement and textContent assignment, never via innerHTML string concatenation, eliminating XSS injection vectors.
9

JSDoc Documentation

Every function carries a full JSDoc block — @param types, @returns, @typedef for AttemptRecord — making the source navigable in any IDE with TypeScript-powered IntelliSense without a build step.

Project Structure

Snake Classic Game ships as a single index.html file with four logical sections that are easy to navigate by searching for the inline section comments:
<!DOCTYPE html>
<html lang="es">
<head>
  <!-- ① CSS Variables & Reset
       :root custom properties (--color-bg, --color-primary, etc.)
       box-sizing reset, body flex layout                          -->

  <!-- ② Layout & UI Styles
       Header, HUD, session-bar, canvas, D-pad, modals (help +
       results), footer, skip-link, .sr-only, responsive
       @media queries (< 480 px, landscape, 481–768 px)           -->
  <style>…</style>
</head>
<body>

  <!-- ③ HTML Markup
       <a class="skip-link">     — keyboard skip navigation
       <header> / <h1>          — game title
       <section id="hud">       — SCORE / LVL / BEST with aria-live
       <div id="session-bar">   — five dot indicators + label
       <section id="game-region">
         <canvas id="canvas">   — 400 × 400 game board
       <div id="message">       — status / prompt text
       <div id="dpad">          — touch D-pad (▲ ◄ ► ▼)
       <div id="help-overlay">  — help dialog (role="dialog")
       <div id="results-overlay"> — session results dialog
       <footer>                 — version, license, author        -->

  <!-- ④ JavaScript Engine
       DOM references & constants (GRID_SIZE, COLS, ROWS,
                                   BASE_TICK, MIN_TICK, STEP_MS)
       Global state (snake, dir, score, best, running, gameOver)
       Session state (sessionAttempts, currentAttempt, metrics)
       localStorage helpers (readBestScore, saveBestScore)
       Level / speed helpers (getLevel, getTick)
       Game-loop (scheduleNext → tick → update → draw)
       Rendering (drawGrid, drawFood, drawSegment, draw)
       Message helpers (flashMessage, showMessage, hideMessage,
                        announceAlert)
       Session logic (captureAttempt, endGame, showSessionResults,
                      startNewSession)
       Help modal (openHelp, closeHelp)
       Input — keyboard (keydown → keyMap)
       Input — touch (swipe on canvas, D-pad touchstart/click)
       Boot (init + draw)                                         -->
  <script>…</script>
</body>
</html>
The file has no external imports, no module bundler output, and no generated code — every line is human-authored and readable in a plain text editor.

Version & License

FieldValue
Version0.2.0
LicenseMIT
AuthorAdolfo J. Cardozo S.
Snake Classic Game is distributed under the MIT License. You are free to use, modify, and redistribute the code with attribution. See LICENSE.txt in the repository for the full license text.

Build docs developers (and LLMs) love