{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "snake",
  "type": "registry:ui",
  "title": "Snake",
  "description": "A monochrome snake game on a dot-lattice field. Steer with the arrow keys, WASD, or a swipe, eat to grow by one segment, and wrap around the edges.",
  "author": "Aditya Ojha <https://akoder.xyz>",
  "categories": [
    "game",
    "canvas",
    "interactive"
  ],
  "dependencies": [
    "lucide-react",
    "motion",
    "react-icons"
  ],
  "registryDependencies": [
    "button"
  ],
  "meta": {
    "docs": "https://akoder.xyz/components/snake",
    "source": "https://github.com/AdityaKodez/adityaojha/blob/main/components/ui/snake.tsx"
  },
  "files": [
    {
      "path": "components/ui/snake.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport { PlayCircleIcon } from \"lucide-react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport {\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n  type PointerEvent as ReactPointerEvent,\n} from \"react\";\nimport { VscSnake } from \"react-icons/vsc\";\nimport { Button } from \"./button\";\n\n/*\n * Theme tokens with the literals a consumer project without them falls back\n * to. Canvas cannot parse `var(--token)`, so these are resolved against the\n * computed style of the field at runtime; see `resolveColor`.\n */\nconst DEFAULT_FIELD_COLOR = \"var(--background, #000000)\";\nconst DEFAULT_DOT_COLOR = \"var(--muted-foreground, #525252)\";\nconst DEFAULT_SNAKE_COLOR = \"var(--primary, #2563eb)\";\n\n/** Corner-dot radius, in CSS pixels, independent of cell size. */\nconst DOT_RADIUS = 1.5;\n/**\n * The lattice is inset from the canvas edge by this fraction of the field so\n * the outermost dots are not half-clipped by the boundary.\n */\nconst LATTICE_INSET = 0.02;\n/** Head and tail disc radii as a fraction of one cell; segments ramp between. */\nconst HEAD_RADIUS = 0.4;\nconst TAIL_RADIUS = 0.26;\nconst FOOD_RADIUS = 0.3;\nconst HEAD_OPACITY = 1;\nconst TAIL_OPACITY = 0.35;\n/** Pointer travel, in pixels, before a drag counts as a swipe. */\nconst SWIPE_THRESHOLD = 24;\n/** Caps how far one frame can advance the simulation after a stall. */\nconst MAX_STEP_MS = 150;\n/** devicePixelRatio ceiling; two is indistinguishable for discs this small. */\nconst MAX_DPR = 2;\n\ntype Point = { x: number; y: number };\ntype Direction = \"up\" | \"down\" | \"left\" | \"right\";\n\nconst DELTA: Record<Direction, Point> = {\n  up: { x: 0, y: -1 },\n  down: { x: 0, y: 1 },\n  left: { x: -1, y: 0 },\n  right: { x: 1, y: 0 },\n};\n\nconst KEY_DIRECTIONS: Record<string, Direction> = {\n  ArrowUp: \"up\",\n  ArrowDown: \"down\",\n  ArrowLeft: \"left\",\n  ArrowRight: \"right\",\n  w: \"up\",\n  a: \"left\",\n  s: \"down\",\n  d: \"right\",\n};\n\nconst VAR_TOKEN = /^var\\(\\s*(--[\\w-]+)\\s*(?:,\\s*(.+?))?\\)$/;\n\n/**\n * Resolves a color prop to something canvas can paint.\n *\n * Canvas parses `fillStyle` as a CSS color and knows nothing about custom\n * properties, so a raw `var(--primary)` is silently dropped and the previous\n * color stays. A prop that is a var() reference is looked up in the computed\n * style of the field element, which inherits whichever theme is active;\n * anything else is already concrete and passes through. A token the project\n * does not define falls back to the inline literal, then to `fallback`.\n */\nfunction resolveColor(\n  element: Element,\n  color: string,\n  fallback: string,\n): string {\n  const match = VAR_TOKEN.exec(color.trim());\n  if (!match) return color;\n  const token = match[1];\n  const inlineFallback = match[2]?.trim();\n  const resolved = getComputedStyle(element).getPropertyValue(token).trim();\n  return resolved || inlineFallback || fallback;\n}\n\nexport interface SnakeProps {\n  /** Cells per side. The field is square, so 20 means 20x20. */\n  gridSize?: number;\n  /** Milliseconds per step. */\n  speed?: number;\n  /** Segments the snake starts with. */\n  initialLength?: number;\n  /** Play field background. */\n  fieldColor?: string;\n  /** Lattice dots at the cell corners. */\n  dotColor?: string;\n  /** Snake and food. */\n  snakeColor?: string;\n  className?: string;\n}\n\n/** Picks a uniformly random cell the snake does not occupy. */\nfunction spawnFood(snake: Point[], gridSize: number): Point {\n  const taken = new Set(\n    snake.map((segment) => segment.y * gridSize + segment.x),\n  );\n  const free: number[] = [];\n  for (let cell = 0; cell < gridSize * gridSize; cell += 1) {\n    if (!taken.has(cell)) free.push(cell);\n  }\n  // Only reachable once the snake fills every cell.\n  if (free.length === 0) return { x: -1, y: -1 };\n  const cell = free[Math.floor(Math.random() * free.length)];\n  return { x: cell % gridSize, y: Math.floor(cell / gridSize) };\n}\n\n/** Starts the snake mid-field, running to the right. */\nfunction initialSnake(gridSize: number, initialLength: number): Point[] {\n  const row = Math.floor(gridSize / 2);\n  const headX = Math.max(initialLength - 1, Math.min(row, gridSize - 1));\n  return Array.from({ length: initialLength }, (_, index) => ({\n    x: headX - index,\n    y: row,\n  }));\n}\n\n/**\n * A snake game on a dot-lattice field. Steer with the arrow keys, WASD, or a\n * swipe; eat a disc to grow by one segment; wrap around the edges. The run\n * ends when the snake bites itself, and the overlay restarts it.\n *\n * Keys are captured while the field is on screen, hovered, or focused, so the\n * game is playable without clicking into it, and the page keeps its normal\n * arrow-key scrolling once the field is neither of those.\n */\nexport function Snake({\n  gridSize = 20,\n  speed = 80,\n  initialLength = 3,\n  fieldColor = DEFAULT_FIELD_COLOR,\n  dotColor = DEFAULT_DOT_COLOR,\n  snakeColor = DEFAULT_SNAKE_COLOR,\n  className,\n}: SnakeProps) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const fieldRef = useRef<HTMLDivElement>(null);\n  const swipeStartRef = useRef<Point | null>(null);\n  const directionRef = useRef<Direction>(\"right\");\n  const turnQueueRef = useRef<Direction[]>([]);\n  const accumulatorRef = useRef(0);\n  // Whether at least half the field is on screen. Gates both the keyboard\n  // listener and the simulation, so an off-screen game neither steals keys\n  // nor runs unattended.\n  const inViewRef = useRef(true);\n  // Hover and focus are input events, so they arrive even when the\n  // intersection observer has not reported yet.\n  const hoverRef = useRef(false);\n  const focusRef = useRef(false);\n\n  const [score, setScore] = useState(0);\n  const [gameOver, setGameOver] = useState(false);\n  // Bumped when the theme class on <html> changes, which re-resolves the\n  // color props and repaints the lattice in the new palette.\n  const [colorVersion, setColorVersion] = useState(0);\n  const reduceMotion = useReducedMotion();\n\n  const grid = Math.max(2, Math.floor(gridSize));\n  const length = Math.max(1, Math.floor(initialLength));\n\n  // The opening board is built during the first render, so the draw loop\n  // always has a valid snake and food from its very first frame.\n  const [openingBoard] = useState(() => {\n    const snake = initialSnake(grid, length);\n    return { snake, food: spawnFood(snake, grid) };\n  });\n  const snakeRef = useRef<Point[]>(openingBoard.snake);\n  const foodRef = useRef<Point>(openingBoard.food);\n\n  const restart = useCallback(() => {\n    snakeRef.current = initialSnake(grid, length);\n    foodRef.current = spawnFood(snakeRef.current, grid);\n    directionRef.current = \"right\";\n    turnQueueRef.current = [];\n    accumulatorRef.current = 0;\n    setScore(0);\n    setGameOver(false);\n  }, [grid, length]);\n\n  // Prop changes start a new board. The restart is scheduled from a frame\n  // callback rather than run inline: restart sets state, and a synchronous\n  // setState inside the effect would cascade a second render.\n  useEffect(() => {\n    const frame = requestAnimationFrame(restart);\n    return () => cancelAnimationFrame(frame);\n  }, [restart]);\n\n  // Dark mode is class-based, so a theme swap arrives as an attribute change\n  // on the document element and the resolved colors have to be rebuilt.\n  useEffect(() => {\n    const observer = new MutationObserver(() =>\n      setColorVersion((version) => version + 1),\n    );\n    observer.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\", \"style\"],\n    });\n    return () => observer.disconnect();\n  }, []);\n\n  // Half the field on screen counts as \"the player is here\". The observer\n  // corrects the optimistic initial value on its first callback.\n  useEffect(() => {\n    const field = fieldRef.current;\n    if (!field || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver(\n      (entries) => {\n        inViewRef.current = entries.some((entry) => entry.isIntersecting);\n      },\n      { threshold: 0.5 },\n    );\n    observer.observe(field);\n    return () => observer.disconnect();\n  }, []);\n\n  const turn = useCallback(\n    (direction: Direction) => {\n      if (gameOver) return;\n      const queue = turnQueueRef.current;\n      const last =\n        queue.length > 0 ? queue[queue.length - 1] : directionRef.current;\n      const reverses =\n        DELTA[last].x + DELTA[direction].x === 0 &&\n        DELTA[last].y + DELTA[direction].y === 0;\n      // Two buffered turns are enough to plan a corner without letting a fast\n      // player queue a move that outlives the board state it was meant for.\n      if (!reverses && last !== direction && queue.length < 2) {\n        queue.push(direction);\n      }\n    },\n    [gameOver],\n  );\n\n  /*\n   * Steering lives on `window` rather than the field so the game needs no\n   * click to become playable. Keys are captured while the field is on screen,\n   * hovered, or focused, and never while the user is typing in another\n   * field. Once none of those hold the listener detaches, which hands\n   * arrow-key scrolling back to the page.\n   */\n  useEffect(() => {\n    if (gameOver) return;\n\n    const handleWindowKeyDown = (event: KeyboardEvent) => {\n      if (!inViewRef.current && !hoverRef.current && !focusRef.current) return;\n      const target = event.target as HTMLElement | null;\n      if (\n        target &&\n        (target.isContentEditable ||\n          target.tagName === \"INPUT\" ||\n          target.tagName === \"TEXTAREA\" ||\n          target.tagName === \"SELECT\")\n      ) {\n        return;\n      }\n      const direction = KEY_DIRECTIONS[event.key];\n      if (!direction) return;\n      event.preventDefault();\n      turn(direction);\n    };\n\n    window.addEventListener(\"keydown\", handleWindowKeyDown);\n    return () => window.removeEventListener(\"keydown\", handleWindowKeyDown);\n  }, [gameOver, turn]);\n\n  const handlePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n    swipeStartRef.current = { x: event.clientX, y: event.clientY };\n  };\n\n  const handlePointerEnter = () => {\n    hoverRef.current = true;\n  };\n\n  const handlePointerLeave = () => {\n    hoverRef.current = false;\n  };\n\n  const handleFocus = () => {\n    focusRef.current = true;\n  };\n\n  const handleBlur = () => {\n    focusRef.current = false;\n  };\n\n  const handlePointerUp = (event: ReactPointerEvent<HTMLDivElement>) => {\n    const start = swipeStartRef.current;\n    swipeStartRef.current = null;\n    if (!start) return;\n    const dx = event.clientX - start.x;\n    const dy = event.clientY - start.y;\n    if (Math.max(Math.abs(dx), Math.abs(dy)) < SWIPE_THRESHOLD) return;\n    if (Math.abs(dx) > Math.abs(dy)) {\n      turn(dx > 0 ? \"right\" : \"left\");\n    } else {\n      turn(dy > 0 ? \"down\" : \"up\");\n    }\n  };\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    const field = fieldRef.current;\n    if (!canvas || !field) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    // Canvas paints concrete colors only, so every var() prop is resolved\n    // against the field's computed style once per setup.\n    const resolvedField = resolveColor(field, fieldColor, \"#000000\");\n    const resolvedDot = resolveColor(field, dotColor, \"#525252\");\n    const resolvedSnake = resolveColor(field, snakeColor, \"#2563eb\");\n\n    // The lattice never changes, so it is painted once per resize into an\n    // offscreen canvas and blitted each frame.\n    const lattice = document.createElement(\"canvas\");\n    const latticeCtx = lattice.getContext(\"2d\");\n\n    let cell = 0;\n    let inset = 0;\n    let dpr = 1;\n\n    const resize = () => {\n      const size = field.clientWidth;\n      if (size === 0) return;\n      dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR);\n      canvas.width = Math.round(size * dpr);\n      canvas.height = Math.round(size * dpr);\n      lattice.width = canvas.width;\n      lattice.height = canvas.height;\n      inset = size * LATTICE_INSET;\n      cell = (size - inset * 2) / grid;\n\n      if (latticeCtx) {\n        latticeCtx.setTransform(dpr, 0, 0, dpr, 0, 0);\n        latticeCtx.clearRect(0, 0, size, size);\n        latticeCtx.fillStyle = resolvedDot;\n        for (let row = 0; row <= grid; row += 1) {\n          for (let column = 0; column <= grid; column += 1) {\n            latticeCtx.beginPath();\n            latticeCtx.arc(\n              inset + column * cell,\n              inset + row * cell,\n              DOT_RADIUS,\n              0,\n              Math.PI * 2,\n            );\n            latticeCtx.fill();\n          }\n        }\n      }\n    };\n\n    const disc = (x: number, y: number, radius: number, alpha: number) => {\n      ctx.globalAlpha = alpha;\n      ctx.fillStyle = resolvedSnake;\n      ctx.beginPath();\n      ctx.arc(x, y, radius, 0, Math.PI * 2);\n      ctx.fill();\n      ctx.globalAlpha = 1;\n    };\n\n    const draw = () => {\n      const size = canvas.width / dpr;\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      ctx.fillStyle = resolvedField;\n      ctx.fillRect(0, 0, size, size);\n      ctx.drawImage(lattice, 0, 0, size, size);\n\n      const food = foodRef.current;\n      if (food.x >= 0) {\n        disc(\n          inset + (food.x + 0.5) * cell,\n          inset + (food.y + 0.5) * cell,\n          cell * FOOD_RADIUS,\n          1,\n        );\n      }\n\n      const snake = snakeRef.current;\n      // Tail first so the head paints on top. The ramp runs from the largest,\n      // brightest disc at the head down to the faintest at the tail.\n      for (let index = snake.length - 1; index >= 0; index -= 1) {\n        const t = snake.length <= 1 ? 0 : index / (snake.length - 1);\n        disc(\n          inset + (snake[index].x + 0.5) * cell,\n          inset + (snake[index].y + 0.5) * cell,\n          cell * (HEAD_RADIUS + (TAIL_RADIUS - HEAD_RADIUS) * t),\n          HEAD_OPACITY + (TAIL_OPACITY - HEAD_OPACITY) * t,\n        );\n      }\n      const head = snake[0];\n      const hx = inset + (head.x + 0.5) * cell;\n      const hy = inset + (head.y + 0.5) * cell;\n      const headRadius = cell * HEAD_RADIUS;\n      const forward = DELTA[directionRef.current];\n      const side = { x: -forward.y, y: forward.x };\n      const offset = headRadius * 0.32;\n      const eyeRadius = Math.max(1, headRadius * 0.2);\n\n      ctx.globalAlpha = 1;\n      ctx.fillStyle = resolvedDot;\n      for (const sign of [1, -1]) {\n        ctx.beginPath();\n        ctx.arc(\n          hx + forward.x * offset + side.x * offset * sign,\n          hy + forward.y * offset + side.y * offset * sign,\n          eyeRadius,\n          0,\n          Math.PI * 2,\n        );\n        ctx.fill();\n      }\n    };\n\n\n    const step = () => {\n      const direction = turnQueueRef.current.shift() ?? directionRef.current;\n      directionRef.current = direction;\n      const delta = DELTA[direction];\n      const snake = snakeRef.current;\n      const next: Point = {\n        x: (snake[0].x + delta.x + grid) % grid,\n        y: (snake[0].y + delta.y + grid) % grid,\n      };\n\n      const eats = foodRef.current.x === next.x && foodRef.current.y === next.y;\n      // The tail cell frees up on a normal step, so biting it is safe; while\n      // growing it is not.\n      const limit = eats ? snake.length : snake.length - 1;\n      for (let index = 0; index < limit; index += 1) {\n        if (snake[index].x === next.x && snake[index].y === next.y) {\n          setGameOver(true);\n          return;\n        }\n      }\n\n      const grown = [next, ...snake];\n      if (eats) {\n        foodRef.current = spawnFood(grown, grid);\n        setScore((current) => current + 10);\n        if (foodRef.current.x < 0) {\n          // The board is full, so the run ends through the same overlay.\n          snakeRef.current = grown;\n          setGameOver(true);\n          return;\n        }\n      } else {\n        grown.pop();\n      }\n      snakeRef.current = grown;\n    };\n\n    const stepMs = Math.max(16, speed);\n    let frame = 0;\n    let last = performance.now();\n\n    const loop = (now: number) => {\n      frame = requestAnimationFrame(loop);\n      const elapsed = Math.min(now - last, MAX_STEP_MS);\n      last = now;\n      // Off screen the field keeps its last frame and the snake holds still,\n      // so scrolling away never kills a run.\n      if (!inViewRef.current) return;\n      if (!gameOver) {\n        accumulatorRef.current += elapsed;\n        while (accumulatorRef.current >= stepMs) {\n          accumulatorRef.current -= stepMs;\n          step();\n        }\n      }\n      draw();\n    };\n\n    resize();\n    const observer = new ResizeObserver(resize);\n    observer.observe(field);\n    frame = requestAnimationFrame(loop);\n\n    // A backgrounded tab stops firing frames, so the next frame after it\n    // returns would arrive with one enormous delta.\n    const handleVisibilityChange = () => {\n      last = performance.now();\n      accumulatorRef.current = 0;\n    };\n    document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n    return () => {\n      cancelAnimationFrame(frame);\n      observer.disconnect();\n      document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n    };\n  }, [colorVersion, dotColor, fieldColor, gameOver, grid, snakeColor, speed]);\n\n  return (\n    <div className=\"w-full\">\n      <div className=\"mb-2 flex items-baseline justify-between font-mono text-xs text-muted-foreground\">\n        <span>\n          Score{\" \"}\n          {/* Keyed on the score so every change remounts the number and\n              replays the pop. */}\n          <motion.span\n            key={score}\n            initial={{ scale: 1.6, opacity: 0.4 }}\n            animate={{ scale: 1, opacity: 1 }}\n            transition={\n              reduceMotion\n                ? { duration: 0 }\n                : { duration: 0.28, ease: [0.22, 1, 0.36, 1] }\n            }\n            className=\"inline-block origin-left tabular-nums\"\n          >\n            {score}\n          </motion.span>\n        </span>\n      </div>\n      <div\n        ref={fieldRef}\n        tabIndex={0}\n        aria-label=\"Snake game field. Steer with the arrow keys, WASD, or a swipe.\"\n        onPointerEnter={handlePointerEnter}\n        onPointerLeave={handlePointerLeave}\n        onFocus={handleFocus}\n        onBlur={handleBlur}\n        onPointerDown={handlePointerDown}\n        onPointerUp={handlePointerUp}\n        className={cn(\n          \"relative block aspect-square w-full touch-none overflow-hidden rounded-md outline-none\",\n\n          className,\n        )}\n      >\n        <canvas\n          ref={canvasRef}\n          className=\"pointer-events-none absolute inset-0 block h-full w-full\"\n        />\n        {gameOver ? (\n          <div className=\"absolute inset-0 grid place-items-center\">\n            {/*\n              The overlay takes the popover token pair rather than the field\n              colors: the field now follows the theme, and white text would\n              disappear over a light field. The pair always contrasts, with\n              literal fallbacks for projects without the tokens.\n            */}\n            <div\n              className=\"absolute inset-0\"\n              style={{\n                backgroundColor: \"var(--popover, #ffffff)\",\n                opacity: 0.78,\n                filter:\"blur(8px)\"\n              }}\n            />\n            <div\n              className=\"relative flex flex-col items-center gap-2 px-4 text-center\"\n\n            >\n              <VscSnake className=\"size-6\"/>\n              <p className=\"text-sm font-medium font-serif\">Game over</p>\n              <Button\n                type=\"button\"\n                onClick={restart}\nsize={\"sm\"}\n              >\n                Play again <PlayCircleIcon className=\"size-4\"/>\n              </Button>\n            </div>\n          </div>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "docs": "## Installation\n\n```bash\nnpx shadcn@latest add @akoder/snake\n```\n\n## Usage\n\n```tsx\nimport { Snake } from \"@/components/ui/snake\";\n\nexport function Game() {\n  return <Snake />;\n}\n```\n\nSteer with the arrow keys, WASD, or a swipe. `gridSize` sets the cells per side (20 means 20x20), `speed` is the milliseconds per step, and `initialLength` is the starting segment count. The colors are `var(--token, literal)` references resolved at runtime, so the field follows your theme and falls back to the literal in projects without the tokens; pass a literal color to `fieldColor`, `dotColor`, or `snakeColor` to opt out."
}