# Memory Match

Flip cards to find the pairs. Cards flip in 3D, matches wobble, and a dialog scores you with stars.

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 { useEffect, 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { Barn, Coin, Fish, Grain, Pumpkin, Sprout, Sun, Tools, Tree } from "@/docs/art";

/** Memory Match: flip two cards, find the pairs. */

const ICONS = [Coin, Grain, Sprout, Tree, Barn, Tools, Sun, Fish, Pumpkin];
const NAMES = ["coin", "grain", "sprout", "tree", "barn", "tools", "sun", "fish", "pumpkin"];
type Card = { id: number; kind: number; open: boolean; done: boolean };

function deal(pairs: number, seed = Date.now()): Card[] {
  let s = seed % 2147483647 || 1;
  const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
  const kinds = [...Array(pairs).keys()].flatMap((k) => [k, k]);
  for (let i = kinds.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [kinds[i], kinds[j]] = [kinds[j], kinds[i]]; }
  return kinds.map((kind, id) => ({ id, kind, open: false, done: false }));
}

export default function MemoryMatch() {
  const [pairs, setPairs] = useState(6);
  const [cards, setCards] = useState<Card[]>(() => deal(6, 7));
  const [picked, setPicked] = useState<number[]>([]);
  const [moves, setMoves] = useState(0);
  const [secs, setSecs] = useState(0);
  const [started, setStarted] = useState(false);
  const [best, setBest] = useState<number | null>(null);
  const won = cards.length > 0 && cards.every((c) => c.done);

  useEffect(() => {
    try { const b = localStorage.getItem(`cz-memory-${pairs}`); setBest(b ? Number(b) : null); } catch { /* no storage */ }
  }, [pairs]);
  useEffect(() => {
    if (!started || won) return;
    const id = setInterval(() => setSecs((s) => s + 1), 1000);
    return () => clearInterval(id);
  }, [started, won]);
  useEffect(() => {
    if (!won) return;
    if (best === null || moves < best) {
      setBest(moves);
      try { localStorage.setItem(`cz-memory-${pairs}`, String(moves)); } catch { /* no storage */ }
    }
  }, [won]); // eslint-disable-line react-hooks/exhaustive-deps

  const restart = (n = pairs) => { setPairs(n); setCards(deal(n)); setPicked([]); setMoves(0); setSecs(0); setStarted(false); };

  const flip = (c: Card) => {
    if (c.open || c.done || picked.length === 2) return;
    setStarted(true);
    const next = [...picked, c.id];
    setCards((cs) => cs.map((x) => (x.id === c.id ? { ...x, open: true } : x)));
    setPicked(next);
    if (next.length === 2) {
      setMoves((m) => m + 1);
      const [a, b] = next.map((id) => cards.find((x) => x.id === id)!.kind);
      setTimeout(() => {
        setCards((cs) => cs.map((x) => (next.includes(x.id) ? (a === b ? { ...x, done: true } : { ...x, open: false }) : x)));
        setPicked([]);
      }, a === b ? 350 : 800);
    }
  };

  const stars = moves <= pairs + 2 ? 3 : moves <= pairs * 2 ? 2 : 1;

  return (
    <div className="grid w-full gap-4">
      <div className="flex flex-wrap items-center gap-2">
        <Badge variant="outline">Moves {moves}</Badge>
        <Badge variant="outline">{Math.floor(secs / 60)}:{String(secs % 60).padStart(2, "0")}</Badge>
        {best !== null && <Badge variant="secondary">Best {best} moves</Badge>}
        <div className="ml-auto flex items-start gap-2">
          <div className="w-32">
            <Select value={String(pairs)} onValueChange={(v) => restart(Number(v))}>
              <SelectTrigger aria-label="Board size" className="!min-h-9 text-sm"><SelectValue /></SelectTrigger>
              <SelectContent><SelectItem value="4">8 cards</SelectItem><SelectItem value="6">12 cards</SelectItem><SelectItem value="8">16 cards</SelectItem></SelectContent>
            </Select>
          </div>
          <Button size="sm" variant="outline" onClick={() => restart()}>Restart</Button>
        </div>
      </div>
      <div className={"mx-auto grid w-full max-w-lg grid-cols-4 gap-3"} style={{ perspective: 800 }}>
        {cards.map((c) => {
          const Icon = ICONS[c.kind];
          const up = c.open || c.done;
          return (
            <button
              key={c.id}
              type="button"
              onClick={() => flip(c)}
              aria-label={up ? `Card ${c.id + 1}: ${NAMES[c.kind]}` : `Card ${c.id + 1}: face down`}
              aria-pressed={up}
              className="relative aspect-[3/4] border-0 bg-transparent p-0"
              style={{ transformStyle: "preserve-3d", transition: "transform 380ms var(--cz-motion-ease-bounce)", transform: up ? "rotateY(180deg)" : "none", cursor: up ? "default" : "pointer" }}
            >
              <span className="cz-card absolute inset-0 items-center justify-center p-0" style={{ backfaceVisibility: "hidden", background: "var(--cz-shadow-plastic), var(--cz-primary)" }}>
                <Sun className="size-1/2 opacity-40" />
              </span>
              <span className={cn("cz-card absolute inset-0 items-center justify-center p-0", c.done && "cz-motion-jelly")} style={{ backfaceVisibility: "hidden", transform: "rotateY(180deg)", background: c.done ? "var(--cz-tint-success)" : undefined }}>
                <Icon className="size-3/5" />
              </span>
            </button>
          );
        })}
      </div>
      <Dialog open={won} onOpenChange={(o) => !o && restart()}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>All pairs found!</DialogTitle>
            <DialogDescription>{moves} moves in {secs} seconds.</DialogDescription>
          </DialogHeader>
          <div className="flex justify-center gap-2 text-4xl" aria-label={`${stars} of 3 stars`}>
            {[0, 1, 2].map((i) => <Sun key={i} className={cn("size-14 cz-motion-pop", i >= stars && "opacity-25 grayscale")} style={{ animationDelay: `${i * 120}ms` }} />)}
          </div>
          <DialogFooter><Button onClick={() => restart()}>Play again</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
```

Docs: https://cozy-ui.solo.engineer/demos/memory-match/
