{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dino-runner-game",
  "title": "Dino Runner Game",
  "description": "A canvas endless-runner in the style of the offline dino game, pixel-drawn running dino, procedurally spawned cactus obstacles, three difficulty speeds, tap/space/arrow-up to jump, and a high-score tracker.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/dino-runner-game/dino-runner-game.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nconst btnClass = \"cursor-pointer rounded-lg border px-4 py-1.5 text-[13px] font-medium transition-colors\";\n\nexport type DinoDifficulty = \"easy\" | \"medium\" | \"hard\";\nexport type DinoTrigger = \"manual\" | \"delay\" | \"scroll\";\nexport type DinoWidgetPosition = \"bottom-right\" | \"bottom-left\";\ntype GameState = \"menu\" | \"playing\" | \"gameover\";\n\ninterface Obstacle {\n  x: number;\n  width: number;\n  height: number;\n  passed?: boolean;\n}\n\nconst SPEED_MAP: Record<DinoDifficulty, number> = { easy: 5, medium: 7, hard: 9.5 };\nconst CANVAS_H = 320;\n\nfunction drawDino(ctx: CanvasRenderingContext2D, x: number, y: number, frame: number) {\n  ctx.fillStyle = \"#333\";\n  ctx.fillRect(x + 8, y + 12, 28, 24);\n  ctx.fillRect(x + 28, y + 4, 18, 16);\n  ctx.fillStyle = \"#fafafa\";\n  ctx.fillRect(x + 38, y + 8, 4, 4);\n  ctx.fillStyle = \"#333\";\n  const legOffset = Math.floor(frame / 6) % 2 === 0 ? 0 : 4;\n  ctx.fillRect(x + 10, y + 36, 6, 12 - legOffset);\n  ctx.fillRect(x + 24, y + 36, 6, 12 + legOffset - 4);\n  ctx.fillRect(x, y + 18, 10, 6);\n}\n\nfunction drawCactus(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number) {\n  ctx.fillStyle = \"#2d5a27\";\n  ctx.fillRect(x + w * 0.3, y, w * 0.4, h);\n  ctx.fillRect(x, y + h * 0.3, w * 0.35, w * 0.35);\n  ctx.fillRect(x + w * 0.65, y + h * 0.5, w * 0.35, w * 0.3);\n}\n\nfunction DinoIcon() {\n  return (\n    <svg width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\" aria-hidden=\"true\">\n      <rect x=\"4\" y=\"10\" width=\"12\" height=\"8\" fill=\"#fff\" />\n      <rect x=\"14\" y=\"6\" width=\"7\" height=\"7\" fill=\"#fff\" />\n      <rect x=\"18\" y=\"8\" width=\"2\" height=\"2\" fill=\"#111\" />\n      <rect x=\"2\" y=\"12\" width=\"4\" height=\"3\" fill=\"#fff\" />\n    </svg>\n  );\n}\n\nfunction CloseIcon() {\n  return (\n    <svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\" aria-hidden=\"true\">\n      <path d=\"M2 2l10 10M12 2L2 12\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nexport interface DinoRunnerGameProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  defaultDifficulty?: DinoDifficulty;\n  storageKey?: string;\n  asPopup?: boolean;\n  trigger?: DinoTrigger;\n  delaySeconds?: number;\n  widgetPosition?: DinoWidgetPosition;\n  widgetIcon?: string;\n}\n\nexport function DinoRunnerGame({\n  defaultDifficulty = \"medium\",\n  storageKey = \"\",\n  asPopup = false,\n  trigger = \"manual\",\n  delaySeconds = 4,\n  widgetPosition = \"bottom-right\",\n  widgetIcon,\n  className,\n  style,\n  ...props\n}: DinoRunnerGameProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const focusRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const canvasWrapRef = React.useRef<HTMLDivElement>(null);\n  const widgetTriggerRef = React.useRef<HTMLButtonElement>(null);\n  const isVisibleRef = React.useRef(true);\n  const mountedRef = React.useRef(true);\n  const wasPopupOpenRef = React.useRef(false);\n  const delayTimerRef = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n  const suffix = storageKey.trim() ? `-${storageKey.trim()}` : \"\";\n  const highScoreKey = `dino-highscore${suffix}`;\n\n  const [score, setScore] = React.useState(0);\n  const [highScore, setHighScore] = React.useState(() => {\n    if (typeof window === \"undefined\") return 0;\n    try {\n      const saved = localStorage.getItem(highScoreKey);\n      return saved ? parseInt(saved, 10) || 0 : 0;\n    } catch {\n      return 0;\n    }\n  });\n  const [gameState, setGameState] = React.useState<GameState>(\"menu\");\n  const [difficulty, setDifficulty] = React.useState<DinoDifficulty>(defaultDifficulty);\n  const [isVisible, setIsVisible] = React.useState(true);\n  const [popupOpen, setPopupOpen] = React.useState(!asPopup);\n  const [scrollTriggered, setScrollTriggered] = React.useState(false);\n  const [prevAsPopup, setPrevAsPopup] = React.useState(asPopup);\n\n  if (asPopup !== prevAsPopup) {\n    setPrevAsPopup(asPopup);\n    setPopupOpen(!asPopup);\n  }\n\n  const widgetOnRight = widgetPosition !== \"bottom-left\";\n\n  const gameRef = React.useRef({\n    dinoY: 0,\n    dinoVY: 0,\n    isJumping: false,\n    obstacles: [] as Obstacle[],\n    speed: SPEED_MAP[defaultDifficulty],\n    frame: 0,\n    score: 0,\n    animationId: 0,\n    groundY: CANVAS_H - 48,\n    width: 640,\n    height: CANVAS_H,\n  });\n\n  const focusGame = React.useCallback(() => {\n    focusRef.current?.focus({ preventScroll: true });\n  }, []);\n\n  const sizeCanvas = React.useCallback(() => {\n    const wrap = canvasWrapRef.current;\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const g = gameRef.current;\n    // Layout width (offsetWidth ignores CSS transforms, so a scaled container can't squash the\n    // course), and a backing store at the device pixel ratio so the pixel art stays sharp on\n    // high-density screens. The game itself keeps drawing in CSS px.\n    const w = Math.max(320, Math.floor(wrap?.offsetWidth || 640));\n    const dpr = Math.min(window.devicePixelRatio || 1, 2);\n    canvas.width = Math.round(w * dpr);\n    canvas.height = Math.round(CANVAS_H * dpr);\n    canvas.getContext(\"2d\")?.setTransform(dpr, 0, 0, dpr, 0, 0);\n    g.width = w;\n    g.height = CANVAS_H;\n    g.groundY = CANVAS_H - 48;\n    if (!g.isJumping) g.dinoY = g.groundY - 48;\n  }, []);\n\n  const paintIdle = React.useCallback(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n    const g = gameRef.current;\n    const w = g.width || 640;\n    const h = g.height || CANVAS_H;\n    ctx.fillStyle = \"#ffffff\";\n    ctx.fillRect(0, 0, w, h);\n    ctx.strokeStyle = \"#e0e0e0\";\n    ctx.lineWidth = 2;\n    ctx.beginPath();\n    ctx.moveTo(0, g.groundY + 2);\n    ctx.lineTo(w, g.groundY + 2);\n    ctx.stroke();\n    drawDino(ctx, 60, g.groundY - 48, 0);\n    drawCactus(ctx, Math.max(180, w * 0.62), g.groundY - 44, 22, 44);\n  }, []);\n\n  React.useEffect(() => {\n    mountedRef.current = true;\n    return () => {\n      mountedRef.current = false;\n    };\n  }, []);\n\n  React.useEffect(() => () => clearTimeout(delayTimerRef.current), []);\n\n  React.useEffect(() => {\n    if (!asPopup || trigger !== \"delay\") return;\n    clearTimeout(delayTimerRef.current);\n    delayTimerRef.current = setTimeout(() => setPopupOpen(true), delaySeconds * 1000);\n    return () => clearTimeout(delayTimerRef.current);\n  }, [asPopup, trigger, delaySeconds]);\n\n  React.useEffect(() => {\n    if (!asPopup || trigger !== \"scroll\" || !rootRef.current) return;\n    const el = rootRef.current;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting && !scrollTriggered) {\n          setScrollTriggered(true);\n          setPopupOpen(true);\n        }\n      },\n      { threshold: 0.4 },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [asPopup, trigger, scrollTriggered]);\n\n  React.useEffect(() => {\n    if (asPopup && !popupOpen && wasPopupOpenRef.current) widgetTriggerRef.current?.focus();\n    wasPopupOpenRef.current = popupOpen;\n  }, [asPopup, popupOpen]);\n\n  React.useEffect(() => {\n    if (asPopup && !popupOpen) return;\n    let id1 = 0;\n    let id2 = 0;\n    id1 = requestAnimationFrame(() => {\n      sizeCanvas();\n      paintIdle();\n      focusGame();\n      id2 = requestAnimationFrame(() => {\n        sizeCanvas();\n        if (gameState !== \"playing\") paintIdle();\n        focusGame();\n      });\n    });\n    return () => {\n      cancelAnimationFrame(id1);\n      cancelAnimationFrame(id2);\n    };\n  }, [popupOpen, asPopup, sizeCanvas, paintIdle, gameState, focusGame]);\n\n  React.useEffect(() => {\n    const el = focusRef.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => {\n      isVisibleRef.current = entry.isIntersecting;\n      setIsVisible(entry.isIntersecting);\n    }, { threshold: 0 });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [popupOpen]);\n\n  React.useEffect(() => {\n    const wrap = canvasWrapRef.current;\n    if (!wrap) return;\n    sizeCanvas();\n    paintIdle();\n    const ro = new ResizeObserver(() => {\n      sizeCanvas();\n      if (gameRef.current.animationId === 0 || gameState !== \"playing\") paintIdle();\n    });\n    ro.observe(wrap);\n    return () => ro.disconnect();\n  }, [sizeCanvas, paintIdle, popupOpen, asPopup, gameState]);\n\n  React.useEffect(() => {\n    sizeCanvas();\n    if (gameState !== \"playing\" || !isVisible) {\n      paintIdle();\n      return;\n    }\n\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    const g = gameRef.current;\n    g.speed = SPEED_MAP[difficulty];\n    g.obstacles = [];\n    g.score = 0;\n    g.frame = 0;\n    g.dinoY = g.groundY - 48;\n    g.dinoVY = 0;\n    g.isJumping = false;\n    setScore(0);\n\n    const spawnObstacle = () => {\n      g.obstacles.push({ x: g.width + 20, width: 18 + Math.random() * 12, height: 30 + Math.random() * 25 });\n    };\n    spawnObstacle();\n\n    const loop = () => {\n      if (!mountedRef.current || !isVisibleRef.current) return;\n      g.frame++;\n      ctx.fillStyle = \"#ffffff\";\n      ctx.fillRect(0, 0, g.width, g.height);\n      ctx.strokeStyle = \"#e0e0e0\";\n      ctx.lineWidth = 2;\n      ctx.beginPath();\n      ctx.moveTo(0, g.groundY + 2);\n      ctx.lineTo(g.width, g.groundY + 2);\n      ctx.stroke();\n\n      if (g.isJumping) {\n        g.dinoVY += 0.85;\n        g.dinoY += g.dinoVY;\n        if (g.dinoY >= g.groundY - 48) {\n          g.dinoY = g.groundY - 48;\n          g.dinoVY = 0;\n          g.isJumping = false;\n        }\n      }\n\n      drawDino(ctx, 60, g.dinoY, g.frame);\n\n      for (let i = g.obstacles.length - 1; i >= 0; i--) {\n        const obs = g.obstacles[i];\n        obs.x -= g.speed;\n        drawCactus(ctx, obs.x, g.groundY - obs.height, obs.width, obs.height);\n\n        if (60 + 36 > obs.x && 60 < obs.x + obs.width && g.dinoY + 48 > g.groundY - obs.height) {\n          setGameState(\"gameover\");\n          if (g.score > highScore) {\n            setHighScore(g.score);\n            try {\n              localStorage.setItem(highScoreKey, String(g.score));\n            } catch {\n              /* ignore */\n            }\n          }\n          return;\n        }\n\n        if (obs.x + obs.width < 60 && !obs.passed) {\n          obs.passed = true;\n          g.score += 1;\n          setScore(g.score);\n        }\n        if (obs.x + obs.width < 0) g.obstacles.splice(i, 1);\n      }\n\n      if (g.obstacles.length === 0 || g.obstacles[g.obstacles.length - 1].x < g.width - 280 - Math.random() * 200) spawnObstacle();\n      if (g.frame % 400 === 0) g.speed += 0.25;\n\n      g.animationId = requestAnimationFrame(loop);\n    };\n\n    g.animationId = requestAnimationFrame(loop);\n    return () => {\n      cancelAnimationFrame(g.animationId);\n      g.animationId = 0;\n    };\n  }, [gameState, difficulty, isVisible, highScore, highScoreKey, sizeCanvas, paintIdle]);\n\n  const jump = React.useCallback(() => {\n    if (gameState === \"menu\") {\n      setGameState(\"playing\");\n      return;\n    }\n    if (gameState !== \"playing\") return;\n    const g = gameRef.current;\n    if (!g.isJumping) {\n      g.isJumping = true;\n      g.dinoVY = -14.5;\n    }\n  }, [gameState]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (e.key === \"Escape\" && asPopup) {\n      e.preventDefault();\n      setPopupOpen(false);\n      return;\n    }\n    if (e.code === \"Space\" || e.key === \" \" || e.key === \"ArrowUp\") {\n      e.preventDefault();\n      e.stopPropagation();\n      jump();\n    }\n    if (e.key === \"Enter\" && gameState !== \"playing\") {\n      e.preventDefault();\n      jump();\n    }\n  };\n\n  const gameCard = (\n    <div\n      ref={focusRef}\n      role=\"application\"\n      aria-label=\"Dino Runner Game\"\n      tabIndex={0}\n      onKeyDown={onKeyDown}\n      onClick={focusGame}\n      className=\"box-border flex w-full flex-col items-center rounded-[22px] bg-[#fafafa] px-4 pt-6 pb-4 font-sans outline-none select-none\"\n    >\n      <header className=\"mb-4 w-full max-w-[640px] text-center\">\n        <h2 className=\"m-0 text-[22px] font-semibold text-[#111]\">Dino Runner Game</h2>\n        <p className=\"mt-1.5 text-[13px] text-[#888]\">Space / Arrow Up / tap to jump</p>\n        <p className=\"mx-auto mt-2 max-w-[520px] text-[13px] leading-[1.45] text-[#888]\">Endless runner. Jump over cacti and beat your high score.</p>\n        <div aria-live=\"polite\" className=\"mt-3 flex justify-center gap-6 text-sm text-[#888]\">\n          <span>\n            Score: <b className=\"text-[#111]\">{score}</b>\n          </span>\n          <span>\n            Best: <b className=\"text-[#111]\">{highScore}</b>\n          </span>\n        </div>\n        <div role=\"radiogroup\" aria-label=\"Difficulty\" className=\"mt-3.5 flex flex-wrap justify-center gap-2\">\n          {([\"easy\", \"medium\", \"hard\"] as DinoDifficulty[]).map((level) => {\n            const selected = difficulty === level;\n            return (\n              <button\n                key={level}\n                type=\"button\"\n                role=\"radio\"\n                aria-checked={selected}\n                onClick={() => {\n                  setDifficulty(level);\n                  if (gameState === \"playing\") setGameState(\"menu\");\n                }}\n                className={btnClass}\n                style={{ background: selected ? \"#111\" : \"white\", color: selected ? \"white\" : \"#333\", borderColor: selected ? \"#111\" : \"#e0e0e0\", transitionTimingFunction: \"ease\" }}\n              >\n                {level.charAt(0).toUpperCase() + level.slice(1)}\n              </button>\n            );\n          })}\n        </div>\n      </header>\n\n      <div\n        ref={canvasWrapRef}\n        onPointerDown={(e) => {\n          e.preventDefault();\n          focusGame();\n          jump();\n        }}\n        className=\"relative w-full max-w-[900px] shrink-0 cursor-pointer overflow-hidden rounded-2xl bg-white shadow-[0_4px_24px_rgba(0,0,0,0.06)]\"\n        style={{ height: CANVAS_H, minHeight: CANVAS_H }}\n      >\n        <canvas ref={canvasRef} role=\"img\" aria-label=\"Dino Runner Game. Press Space to jump.\" className=\"block h-[320px] w-full bg-white\" />\n\n        {gameState === \"menu\" && (\n          <div className=\"absolute inset-0 flex flex-col items-center justify-center bg-[rgba(250,250,250,0.92)] p-4 text-center\">\n            <div className=\"mb-2 text-[28px] font-semibold text-[#111]\">Ready?</div>\n            <div className=\"mb-5 text-sm text-[#888]\">Press Space or tap to start</div>\n            <button\n              type=\"button\"\n              onPointerDown={(e) => {\n                e.stopPropagation();\n                jump();\n              }}\n              className={cn(btnClass, \"bg-[#111] px-7 py-2.5 text-white\")}\n              style={{ borderColor: \"#111\", transitionTimingFunction: \"ease\" }}\n            >\n              Start Game\n            </button>\n          </div>\n        )}\n\n        {gameState === \"gameover\" && (\n          <div role=\"alert\" className=\"absolute inset-0 flex flex-col items-center justify-center bg-[rgba(250,250,250,0.92)] p-4 text-center\">\n            <div className=\"mb-2 text-[28px] font-semibold text-[#111]\">Game Over</div>\n            <div className=\"mb-1.5 text-[15px] text-[#888]\">Score: {score}</div>\n            <button\n              type=\"button\"\n              onPointerDown={(e) => {\n                e.stopPropagation();\n                setGameState(\"playing\");\n              }}\n              className={cn(btnClass, \"mt-3 bg-[#111] px-7 py-2.5 text-white\")}\n              style={{ borderColor: \"#111\", transitionTimingFunction: \"ease\" }}\n            >\n              Play Again\n            </button>\n          </div>\n        )}\n      </div>\n\n      <p className=\"mt-4 text-center text-xs text-[#aaa]\">Space, Arrow Up or tap to jump</p>\n    </div>\n  );\n\n  if (!asPopup) {\n    return (\n      <div ref={rootRef} className={cn(\"w-full\", className)} style={style} {...props}>\n        {gameCard}\n      </div>\n    );\n  }\n\n  return (\n    <div ref={rootRef} className={cn(\"relative w-full\", className)} style={style} {...props}>\n      {!popupOpen && (\n        <div className={cn(\"flex\", widgetOnRight ? \"justify-end\" : \"justify-start\")}>\n          <motion.button\n            ref={widgetTriggerRef}\n            type=\"button\"\n            onClick={() => {\n              setPopupOpen(true);\n              setGameState(\"menu\");\n            }}\n            whileHover={{ scale: 1.04 }}\n            whileTap={{ scale: 0.97 }}\n            aria-label=\"Play Dino\"\n            className=\"flex items-center gap-3 rounded-full border border-[rgba(23,26,33,0.08)] bg-white py-1.5 pr-5 pl-1.5 shadow-[0_8px_30px_rgba(0,0,0,0.18)]\"\n          >\n            <span className=\"flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[#121212]\">\n              {widgetIcon ? (\n                // eslint-disable-next-line @next/next/no-img-element\n                <img src={widgetIcon} alt=\"\" className=\"h-6 w-6 rounded-full object-cover\" />\n              ) : (\n                <DinoIcon />\n              )}\n            </span>\n            <span className=\"flex flex-col gap-0.5 text-left\">\n              <span className=\"text-[9px] font-bold tracking-[0.1em] whitespace-nowrap text-[rgba(23,26,33,0.4)] uppercase\">Mini game</span>\n              <span className=\"text-[13px] font-bold tracking-[0.02em] whitespace-nowrap text-[#171a21] uppercase\">Play Dino</span>\n            </span>\n          </motion.button>\n        </div>\n      )}\n\n      <AnimatePresence>\n        {popupOpen && (\n          <motion.div\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            exit={{ opacity: 0 }}\n            onClick={(e) => {\n              if (e.target === e.currentTarget) setPopupOpen(false);\n            }}\n            className=\"fixed inset-0 z-[10001] flex items-center justify-center p-6\"\n            style={{ background: \"rgba(0,0,0,0.72)\" }}\n          >\n            <motion.div\n              initial={{ scale: 0.94, y: 16 }}\n              animate={{ scale: 1, y: 0 }}\n              exit={{ scale: 0.96, opacity: 0 }}\n              transition={{ duration: 0.35, ease: [0.16, 1, 0.3, 1] }}\n              role=\"dialog\"\n              aria-modal=\"true\"\n              aria-label=\"Dino Runner Game\"\n              onKeyDown={onKeyDown}\n              className=\"relative w-full rounded-[22px]\"\n              style={{ maxWidth: 640 }}\n            >\n              <button\n                type=\"button\"\n                onClick={() => setPopupOpen(false)}\n                aria-label=\"Close\"\n                className=\"absolute top-3 right-3 z-20 flex h-9 w-9 items-center justify-center rounded-full border border-[rgba(0,0,0,0.12)] bg-[#111] p-0 text-white\"\n              >\n                <CloseIcon />\n              </button>\n              {gameCard}\n            </motion.div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}