# Tiny Farm

A small idle farming game built only from Cozy UI: plant, wait, harvest, buy upgrades in a sheet and pick a reward card when you level up.

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, useMemo, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { Coin, Grain, Pumpkin, Sprout, Tools, Tree } from "@/docs/art";

/** Tiny Farm: plant, wait, harvest, upgrade. An idle game made only from Cozy UI parts. */

type CropId = "rice" | "corn" | "pumpkin";
const CROPS: Record<CropId, { name: string; seed: number; sell: number; secs: number; xp: number; Icon: typeof Grain }> = {
  rice: { name: "Rice", seed: 5, sell: 14, secs: 4, xp: 6, Icon: Grain },
  corn: { name: "Corn", seed: 12, sell: 34, secs: 8, xp: 12, Icon: Sprout },
  pumpkin: { name: "Pumpkin", seed: 30, sell: 95, secs: 15, xp: 25, Icon: Pumpkin },
};
type Plot = { crop: CropId; plantedAt: number } | null;

const UPGRADES = [
  { id: "soil", title: "Rich soil", text: "Crops grow 25% faster.", cost: 80, Icon: Sprout },
  { id: "basket", title: "Big basket", text: "Sell everything for 20% more.", cost: 120, Icon: Grain },
  { id: "plot", title: "New plot", text: "One more plot to plant.", cost: 60, Icon: Tools },
] as const;

const PERKS = [
  { id: "rain", title: "Good rain", text: "+40 coins now", Icon: Tree },
  { id: "seeds", title: "Free seeds", text: "Next 3 plantings cost nothing", Icon: Sprout },
  { id: "luck", title: "Lucky harvest", text: "+10% sell price", Icon: Coin },
];

export default function TinyFarm() {
  const [coins, setCoins] = useState(40);
  const [xp, setXp] = useState(0);
  const [level, setLevel] = useState(1);
  const [plots, setPlots] = useState<Plot[]>(() => Array(6).fill(null));
  const [crop, setCrop] = useState<CropId>("rice");
  const [owned, setOwned] = useState<string[]>([]);
  const [freeSeeds, setFreeSeeds] = useState(0);
  const [luck, setLuck] = useState(0);
  const [levelUp, setLevelUp] = useState(false);
  const [now, setNow] = useState(() => Date.now());

  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 200);
    return () => clearInterval(id);
  }, []);

  const speed = owned.includes("soil") ? 0.75 : 1;
  const priceBoost = (owned.includes("basket") ? 1.2 : 1) * (1 + luck);
  const need = level * 60;
  const growth = (p: NonNullable<Plot>) => Math.min(1, Math.max(0, (now - p.plantedAt) / (CROPS[p.crop].secs * 1000 * speed)));
  const ripeCount = useMemo(() => plots.filter((p) => p && growth(p) >= 1).length, [plots, now]); // eslint-disable-line react-hooks/exhaustive-deps

  const gainXp = (n: number) => {
    setXp((v) => {
      const total = v + n;
      if (total >= need) { setLevel((l) => l + 1); setLevelUp(true); return total - need; }
      return total;
    });
  };

  const tapPlot = (i: number) => {
    const p = plots[i];
    if (!p) {
      const c = CROPS[crop];
      const cost = freeSeeds > 0 ? 0 : c.seed;
      if (coins < cost) { toast.warning("Not enough coins", { description: `${c.name} seeds cost ${c.seed}.` }); return; }
      setCoins((v) => v - cost);
      if (freeSeeds > 0) setFreeSeeds((v) => v - 1);
      setPlots((ps) => ps.map((x, j) => (j === i ? { crop, plantedAt: Date.now() } : x)));
      return;
    }
    if (growth(p) < 1) return;
    const c = CROPS[p.crop];
    const earned = Math.round(c.sell * priceBoost);
    setCoins((v) => v + earned);
    gainXp(c.xp);
    setPlots((ps) => ps.map((x, j) => (j === i ? null : x)));
    toast.success(`${c.name} harvested`, { description: `+${earned} coins, +${c.xp} XP` });
  };

  const harvestAll = () => plots.forEach((p, i) => p && growth(p) >= 1 && tapPlot(i));

  const buy = (u: (typeof UPGRADES)[number]) => {
    if (coins < u.cost) return;
    setCoins((v) => v - u.cost);
    if (u.id === "plot") setPlots((ps) => [...ps, null]);
    else setOwned((o) => [...o, u.id]);
    toast(`Bought ${u.title}`);
  };

  const pickPerk = (id: string) => {
    if (id === "rain") setCoins((v) => v + 40);
    if (id === "seeds") setFreeSeeds((v) => v + 3);
    if (id === "luck") setLuck((v) => v + 0.1);
    setLevelUp(false);
  };

  return (
    <div className="grid w-full gap-4">
      <div className="flex flex-wrap items-center gap-2">
        <span className="cz-badge cz-badge--outline gap-2 px-3 py-1 text-base"><Coin className="!h-6 !w-6" /><span className="tabular-nums">{coins}</span><span className="sr-only">coins</span></span>
        <span className="cz-badge cz-badge--outline gap-2 px-3 py-1"><Badge variant="secondary" className="!shadow-none">Lv {level}</Badge><Progress value={(xp / need) * 100} size="sm" className="w-24" aria-label="Experience" /></span>
        {freeSeeds > 0 && <Badge variant="success" bounce>{freeSeeds} free seeds</Badge>}
        <div className="ml-auto flex gap-2">
          <Button size="sm" variant="reward" disabled={ripeCount === 0} onClick={harvestAll}>Harvest all{ripeCount ? ` (${ripeCount})` : ""}</Button>
          <Sheet>
            <SheetTrigger asChild><Button size="sm" variant="outline">Shop</Button></SheetTrigger>
            <SheetContent>
              <SheetHeader><SheetTitle>Village shop</SheetTitle><SheetDescription>You have {coins} coins.</SheetDescription></SheetHeader>
              <div className="grid gap-3">
                {UPGRADES.map((u) => {
                  const have = u.id !== "plot" && owned.includes(u.id);
                  return (
                    <div key={u.id} className="cz-card flex-row items-center gap-3 p-3">
                      <u.Icon className="size-10 shrink-0" />
                      <div className="grid min-w-0 flex-1"><span>{u.title}</span><span className="text-sm text-text-muted">{u.text}</span></div>
                      <Button size="sm" variant={have ? "ghost" : "secondary"} disabled={have || coins < u.cost} onClick={() => buy(u)}>{have ? "Owned" : `${u.cost}`}</Button>
                    </div>
                  );
                })}
              </div>
            </SheetContent>
          </Sheet>
        </div>
      </div>

      <ToggleGroup type="single" value={crop} onValueChange={(v) => v && setCrop(v as CropId)} aria-label="Seed to plant">
        {(Object.keys(CROPS) as CropId[]).map((id) => {
          const c = CROPS[id];
          return <ToggleGroupItem key={id} value={id}><c.Icon />{c.name} · {c.seed}</ToggleGroupItem>;
        })}
      </ToggleGroup>

      <div className="grid grid-cols-3 gap-3 sm:gap-4">
        {plots.map((p, i) => {
          const g = p ? growth(p) : 0;
          const ripe = p && g >= 1;
          const C = p ? CROPS[p.crop] : null;
          return (
            <Tooltip key={i}>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  onClick={() => tapPlot(i)}
                  className={cn("cz-card cz-card--interactive aspect-square items-center justify-center gap-2 p-2", ripe && "cz-motion-float")}
                  style={{ background: p ? "linear-gradient(180deg, #A8794F, #8A5B3C)" : undefined, font: "inherit" }}
                  aria-label={!p ? `Plot ${i + 1}: empty, tap to plant ${CROPS[crop].name}` : ripe ? `Plot ${i + 1}: ${C!.name} is ripe, tap to harvest` : `Plot ${i + 1}: ${C!.name} growing, ${Math.round(g * 100)}%`}
                >
                  {!p && <span className="text-sm text-text-muted">Plant</span>}
                  {p && C && <C.Icon className={cn("transition-[scale] duration-300", ripe ? "size-16 sm:size-20 cz-motion-pop" : "size-16 sm:size-20")} style={{ scale: ripe ? 1 : 0.5 + g * 0.5 }} />}
                  {p && !ripe && <Progress value={g * 100} tone="success" size="sm" className="w-4/5" aria-hidden />}
                  {ripe && <Badge variant="default" className="text-xs">Ready</Badge>}
                </button>
              </TooltipTrigger>
              <TooltipContent>{!p ? `Plant ${CROPS[crop].name} (${freeSeeds ? "free" : `${CROPS[crop].seed} coins`})` : ripe ? `Harvest for ${Math.round(C!.sell * priceBoost)} coins` : `${C!.name}: ${Math.round(g * 100)}% grown`}</TooltipContent>
            </Tooltip>
          );
        })}
      </div>

      <Dialog open={levelUp} onOpenChange={setLevelUp}>
        <DialogContent showCloseButton={false} className="max-w-xl">
          <DialogHeader><DialogTitle>Level {level}! Pick one</DialogTitle><DialogDescription>A small gift from the village.</DialogDescription></DialogHeader>
          <div className="grid grid-cols-3 gap-3">
            {PERKS.map((k, i) => (
              <button key={k.id} type="button" onClick={() => pickPerk(k.id)} className="cz-card cz-card--interactive cz-motion-bounce-in items-center gap-1 p-3 text-center" style={{ animationDelay: `${i * 90}ms`, font: "inherit" }}>
                <k.Icon className="size-12" /><span>{k.title}</span><span className="text-xs text-text-muted">{k.text}</span>
              </button>
            ))}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
```

Docs: https://cozy-ui.solo.engineer/demos/tiny-farm/
