# Bop the Mole

Tap the moles before they hide: 30 seconds a round, three difficulties, a timer bar and a score dialog.

Every piece of this game is a Cozy UI component plus a few lines of state. Open the Code tab to copy it.

## Source

```tsx
import { useCallback, useEffect, useRef, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { cn } from "@/lib/utils";
import { Mole } from "@/docs/art";

/** Bop the Mole: tap the moles before they hide. 30 seconds a round. */

const ROUND = 30;
const SPEED = { easy: 1100, normal: 800, hard: 560 } as const;
type Level = keyof typeof SPEED;

export default function BopTheMole() {
  const [level, setLevel] = useState<Level>("normal");
  const [playing, setPlaying] = useState(false);
  const [left, setLeft] = useState(ROUND);
  const [score, setScore] = useState(0);
  const [misses, setMisses] = useState(0);
  const [up, setUp] = useState<number[]>([]);
  const [bopped, setBopped] = useState<number | null>(null);
  const [over, setOver] = useState(false);
  const upRef = useRef<number[]>([]);
  upRef.current = up;

  const start = () => { setScore(0); setMisses(0); setLeft(ROUND); setUp([]); setOver(false); setPlaying(true); };

  useEffect(() => {
    if (!playing) return;
    const clock = setInterval(() => setLeft((s) => {
      if (s <= 1) { setPlaying(false); setUp([]); setOver(true); return 0; }
      return s - 1;
    }), 1000);
    const spawn = setInterval(() => {
      const free = [...Array(9).keys()].filter((i) => !upRef.current.includes(i));
      const hole = free[Math.floor(Math.random() * free.length)];
      setUp((u) => [...u, hole]);
      setTimeout(() => setUp((u) => u.filter((x) => x !== hole)), SPEED[level] * 1.4);
    }, SPEED[level]);
    return () => { clearInterval(clock); clearInterval(spawn); };
  }, [playing, level]);

  const bop = useCallback((i: number) => {
    if (!playing) return;
    if (upRef.current.includes(i)) {
      setScore((s) => s + 1);
      setUp((u) => u.filter((x) => x !== i));
      setBopped(i);
      setTimeout(() => setBopped((b) => (b === i ? null : b)), 250);
    } else setMisses((m) => m + 1);
  }, [playing]);

  return (
    <div className="grid w-full gap-4">
      <div className="flex flex-wrap items-center gap-2">
        <Badge variant="outline">Score {score}</Badge>
        <Badge variant="outline">Misses {misses}</Badge>
        <ToggleGroup type="single" value={level} onValueChange={(v) => v && !playing && setLevel(v as Level)} aria-label="Difficulty" className="ml-auto">
          {(Object.keys(SPEED) as Level[]).map((l) => <ToggleGroupItem key={l} value={l} disabled={playing} className="capitalize">{l}</ToggleGroupItem>)}
        </ToggleGroup>
      </div>
      <div className="grid gap-1">
        <span className="text-sm text-text-muted tabular-nums">{playing ? `${left}s left` : "30 seconds a round"}</span>
        <Progress value={(left / ROUND) * 100} tone={left <= 5 ? "primary" : "success"} aria-label="Time left" />
      </div>
      <div className="mx-auto grid w-full max-w-md grid-cols-3 gap-3 sm:gap-4">
        {[...Array(9).keys()].map((i) => {
          const out = up.includes(i);
          return (
            <button
              key={i}
              type="button"
              onPointerDown={(e) => { e.preventDefault(); bop(i); }}
              onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && bop(i)}
              aria-label={out ? `Hole ${i + 1}: mole! Bop it` : `Hole ${i + 1}: empty`}
              className={cn("relative aspect-square overflow-hidden rounded-[22px] border-3 border-outline p-0", bopped === i && "cz-motion-shake")}
              style={{ background: "radial-gradient(ellipse at 50% 78%, #3B2618 0 30%, #6E4A33 31% 40%, #8DB84A 41%)", boxShadow: "inset 0 4px 0 rgb(255 255 255 / .3), 0 5px 0 var(--cz-outline)", cursor: playing ? "pointer" : "default" }}
            >
              <Mole
                className="absolute bottom-[-6%] left-1/2 w-3/4 -translate-x-1/2"
                style={{ translate: `0 ${out ? "0%" : "110%"}`, transition: "translate 180ms var(--cz-motion-ease-bounce)" }}
              />
              {bopped === i && <span className="cz-motion-pop absolute left-1/2 top-2 -translate-x-1/2 cz-badge">+1</span>}
            </button>
          );
        })}
      </div>
      <div className="flex justify-center">
        <Button variant={playing ? "secondary" : "reward"} size="lg" onClick={() => (playing ? (setPlaying(false), setUp([])) : start())}>{playing ? "Stop" : "Start"}</Button>
      </div>
      <Dialog open={over} onOpenChange={setOver}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{score >= 25 ? "Mole master!" : score >= 15 ? "Nice bopping!" : "Time’s up!"}</DialogTitle>
            <DialogDescription>You bopped {score} moles on {level}, with {misses} misses.</DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="secondary" onClick={() => setOver(false)}>Close</Button>
            <Button onClick={start}>Play again</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
```

Docs: https://cozy-ui.solo.engineer/demos/bop-the-mole/
