Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/14-gamification.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ Amounts are data in `shared/gamification/xp.ts`:
| Open answer approved by a mentor | 15 | `answer:<blockId>` |
| Course completed | 100 | `course:<courseId>` |
| Weekly goal met | 25 | `weekly_goal:<learner-local Monday>` |
| Daily game round solved (first time that day) | 3, 9 a day at most | `game_round:<day>:<game>:<round>` |
| All three rounds of one daily game in a day | +2 | `game_set:<day>:<game>` |

Logging in and raw time never earn XP.

Expand Down
17 changes: 4 additions & 13 deletions docs/16-learning-areas.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ area section is written so one work session can pick it up on its own.
| Audiobooks | `/audiobooks`, `/audiobooks/[course]` | Open | Every narrated course as an audiobook, with a player that follows you across pages. |
| Labs | `/labs` | Partly open | Visual and guided labs open; shell labs planned. |
| Bite-sized practice | `/practice` | Coming soon | One topic a few minutes a day, led by questions. |
| Puzzles | `/puzzles` | Coming soon | Several kinds of daily puzzle. |
| Puzzles | `/puzzles` | Live | Three daily games: System Design Runner, Linux Command Explorer, Docker Commands ([`17-daily-games.mdx`](17-daily-games.mdx)). |
| On-call tutors | `/voice` | Coming soon | A voice tutor per topic that tracks progress across its modules. |

Lab kinds, under `/labs`:
Expand Down Expand Up @@ -56,7 +56,7 @@ frontend/src/app/(learn)/(catalog)/
guided/ Guided labs (the Dev Weekends tracks, from `lib/guided-labs.ts`)
shell/ Shell labs and the desktop app docs (coming soon page)
practice/ Bite-sized practice (coming soon page)
puzzles/ Puzzles (coming soon page)
puzzles/ Daily games hub and one page per game
voice/ On-call tutors (coming soon page)
```

Expand Down Expand Up @@ -203,18 +203,9 @@ spaced review queue (wrong answers come back after a few days, then less often).
[`05-review-queue.mdx`](05-review-queue.mdx).
- Rewards: XP and streak credit through [`14-gamification.mdx`](14-gamification.mdx).

## Puzzles (planned)
## Puzzles (live)

Several kinds of daily puzzle that use course ideas, one a day, the same for everyone.

- Kinds to start with: find the bottleneck, trace the request (order the steps), fix the diagram,
odd one out. Each kind is a small client component with a server-checked answer.
- Model: `Puzzle { id, kind, date, data, answer (server only), clues[] }` and
`PuzzleAttempt { userId, puzzleId, tries, solvedAt }`. A wrong try reveals the next clue.
- The diagram kinds can reuse the lab board model in `packages/learning-ui/src/labs/` for drawing
and checking.
- Leaderboard: the mobile app adds a daily leaderboard later. It must be opt-in, like the weekly
leaderboards.
The puzzles area is now the daily games: three browser games with three rounds each, the same for everyone, each solved round earning a little XP. How they are built, how XP works and how to add a game is in [`17-daily-games.mdx`](17-daily-games.mdx). The earlier plan for four puzzle kinds (find the bottleneck, trace the request, fix the diagram, odd one out) can become a fourth game on the same framework. A daily leaderboard stays an opt-in later step, like the weekly ones.

## On-call tutors (planned)

Expand Down
45 changes: 45 additions & 0 deletions docs/17-daily-games.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
title: Daily games
status: framework and three games in progress (2026-11-18)
---

# Daily games

Three short browser games every day, inside `/puzzles`: **System Design Runner**, **Linux Command Explorer** and **Docker Commands**. Each game has three rounds a day (easy, medium, hard), the same for everyone. Each round solved for the first time that day gives a little XP, and finishing all three rounds of one game gives a small bonus.

## XP

Amounts live in `server/src/shared/gamification/xp.ts` (change a number there and every client agrees): `game_round` 3 XP, `game_set` 2 XP. The most the games give in a day is 33 XP. A replayed round gives nothing. Keys are `game_round:<day>:<game>:<round>` and `game_set:<day>:<game>`, so XP is paid once. Only learners (role MENTEE) earn XP; a visitor can play without an account and sees a prompt to sign in.

## How a game is built

A game is a **pure, deterministic engine** in `server/src/shared/games/<game>/engine.ts` that implements `GameEngine` (`shared/games/types.ts`):

- `roundsFor(dayKey)` returns today's three rounds (use `pickDaily` from `shared/games/daily.ts`, one scenario per difficulty, rotating through the pool).
- `parseSubmission(input)` narrows an unknown value from the network. It must be strict and never throw.
- `verify(round, submission)` replays the submission and returns `{ passed, stars, score, message }`. It must be pure, deterministic and never throw. No clock, no `Math.random` (use `seededRandom`), no DOM, no network.

The same engine runs in the browser (instant feedback, animation) and on the server (`services/games/daily.ts` replays the submission before it records the round and awards XP). Engines are in `server/src/shared`, which `pnpm sync-shared` copies into `frontend/src/shared`. Never edit the copy.

The browser part is a play component, `frontend/src/components/games/<game>/<game>-play.tsx`, default export, props `GamePlayProps<Round, Submission>` (`components/games/types.ts`). It draws the board or terminal and calls `onFinish(submission)` when the player is done. The shell (`game-host.tsx`) verifies, plays the result sound, shows stars, XP and confetti, saves the round for a signed-in learner, and offers the next round. A play component must reset itself when `attempt` changes (the shell also remounts it with a new `key`), and must ignore input while `locked`.

## System Design Runner uses the lab board

The System Design game is not a separate board. Each round is a real lab spec (`HldLabSpec`) with a broken starting board, played on the same `HldBoard` as the labs, with the same Run tests flow, results and reference solution. The lab model moved to the shared contract (`server/src/shared/lab/engine/`: `catalog`, `hld-types`, `tiered-architecture`, `challenge`) so the server can replay a submitted board with `runChallenge`. The old paths in `packages/learning-ui/src/labs/` re-export it, so every lab works as before. A round passes when every check passes; stars come from cost against the reference solution. The six incidents are in `server/src/shared/games/sysdesign/incidents.ts` (two per difficulty).

## Look and feel

These are real games, not forms. Every game must have:

- **Sound.** Use `sounds` from props (`lib/games/audio.ts`: `key`, `enter`, `ok`, `error`, `snap`, `coin`, `whoosh`, `alarm`, `boot`, `win`, `fanfare`, `lose`). Add new synthesized effects to that file if a game needs one (keep them short and quiet). Sound is off for people who ask for reduced motion, and the shell has a mute switch.
- **Motion with meaning:** packets flowing, bars filling, containers pulsing or shaking, layers stacking, counters ticking, shake on a mistake. Wrap decorative motion in `motion-safe:`; the game must still work with `motion-reduce`.
- **Feedback on every action** (sound plus a visible change), a clear goal, a visible progress or score, a hint that costs a star, and a short, friendly message when something is wrong.
- Sit inside `GameFrame` (`components/games/game-frame.tsx`): the dark header bar with the level tag and actions, three plain steps, the brief, and a `CheckList` of Wait and Pass checks. It copies the lab board so a game looks like part of the platform. One obvious primary action per screen, no decoration that does not help the player act.
- Use the Tailwind theme tokens (`bg-card`, `border-border`, `text-muted-foreground`, `bg-secondary`, `text-primary`, `brand-yellow`) so light and dark both work, and `GameTerminal` (`components/games/game-terminal.tsx`) for any terminal. Phone first: it must be playable at 375 px wide and with the keyboard alone, with labels on controls.
- No em dashes or en dashes in any text, comment or test. Plain, short English, for a learner who may read English as a second language.

## Tests

- Server: `cd server && pnpm exec vitest run tests/unit/shared/games` (pure engine tests: every scenario is solvable by its stated solution, wrong submissions fail, the daily rotation is deterministic and varies by day, `parseSubmission` rejects junk).
- Type checks: `cd server && pnpm exec tsc -p tsconfig.json --noEmit` and `cd frontend && pnpm exec tsc --noEmit -p .`.
- Look at it: `node <scratchpad>/gameshot.mjs <path> <out.png> [width]` logs in as a learner and saves a screenshot of the page (dev stack: web http://localhost:3100, API http://localhost:4100).
1 change: 1 addition & 0 deletions docs/README.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ regardless of which part of the doc set you're working from.
| [`13-engagement.mdx`](13-engagement.mdx) | Engagement events (`POST /api/v1/events`), mascot registry, roles, rules and the web player |
| [`14-gamification.mdx`](14-gamification.mdx) | XP ledger, levels and module stages, streaks in the learner's timezone, streak freezes, weekly leaderboards, feature flags |
| [`15-content-separation.mdx`](15-content-separation.mdx) | Private course source, publishing workflow, and public web/desktop compatibility |
| [`17-daily-games.mdx`](17-daily-games.mdx) | The daily games in `/puzzles`: the engine contract, XP rules, sound and animation rules, and how to add a game |
| [`16-learning-areas.mdx`](16-learning-areas.mdx) | The five learner areas (courses, labs, practice, puzzles, voice agents), their routes and nav, and the build plan for each |

## Build phases
Expand Down
27 changes: 27 additions & 0 deletions frontend/src/app/(learn)/(catalog)/puzzles/[game]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { GameHost } from "@/components/games/game-host";
import { GAME_IDS, isGameId } from "@/shared/games/types";

const TITLES = { sysdesign: "System Design Runner", linux: "Linux Command Explorer", docker: "Docker Commands" } as const;

export function generateStaticParams() {
return GAME_IDS.map((game) => ({ game }));
}

export async function generateMetadata({ params }: { params: Promise<{ game: string }> }): Promise<Metadata> {
const { game } = await params;
if (!isGameId(game)) return {};
return { title: `${TITLES[game]} - daily game`, alternates: { canonical: `/puzzles/${game}` } };
}

export default async function GamePage({ params }: { params: Promise<{ game: string }> }) {
const { game } = await params;
if (!isGameId(game)) notFound();
return (
<div className="mx-auto w-full max-w-5xl px-4 py-6 sm:px-6 sm:py-8">
<h1 className="mb-5 text-2xl font-bold tracking-tight sm:text-3xl">{TITLES[game]}</h1>
<GameHost game={game} />
</div>
);
}
86 changes: 10 additions & 76 deletions frontend/src/app/(learn)/(catalog)/puzzles/page.tsx
Original file line number Diff line number Diff line change
@@ -1,94 +1,28 @@
import type { Metadata } from "next";
import { SITE_SHARE_IMAGE } from "@/lib/site";
import { areaById } from "@/lib/learn-areas";
import { AreaHero, AreaPage, ComingSoonPanel } from "@/components/areas/area-page";
import { FilterChips, pickFilter } from "@/components/areas/filter-chips";
import { AreaHero, AreaPage } from "@/components/areas/area-page";
import { GamesHub } from "@/components/games/games-hub";

export const metadata: Metadata = {
title: "Puzzles",
description: "A new puzzle every day, built on what you learn. The same puzzle for everyone, and a daily leaderboard to climb.",
title: "Daily games",
description: "Three short games every day: fix a broken system, explore a Linux server, repair a Docker container. A little XP for each round you solve.",
alternates: { canonical: "/puzzles" },
openGraph: { title: "Daily puzzles on Edorax", url: "/puzzles", images: [SITE_SHARE_IMAGE] },
openGraph: { title: "Daily games on Edorax", url: "/puzzles", images: [SITE_SHARE_IMAGE] },
};

// The kinds take turns through the week. Each has a one-line goal and an example of the day's prompt.
const KINDS = [
{
id: "bottleneck",
label: "Find the bottleneck",
goal: "A small system is struggling. Tap the one part that gives out first.",
example: "Users → load balancer → two app servers → one database at 95% CPU. Checkout takes 9 seconds.",
},
{
id: "trace",
label: "Trace the request",
goal: "Put the steps of a request in order, from the tap on a phone to the answer on screen.",
example: "DNS lookup · TLS handshake · cache miss · database read · response rendered",
},
{
id: "fix",
label: "Fix the diagram",
goal: "One link or one part is wrong. Find it and fix it in as few moves as you can.",
example: "A queue sits between the browser and the load balancer. One move fixes it.",
},
{
id: "odd",
label: "Odd one out",
goal: "Four ideas, one does not belong. Say which, and the reason appears.",
example: "Read replica · write-ahead log · CDN edge cache · sticky session",
},
] as const;

const RULES = [
["One a day", "New at midnight in your time zone. Yesterday's stays open to practise."],
["A few tries", "Each wrong try shows a clue, so you learn something either way."],
["Daily leaderboard", "Fewer tries and a faster solve rank higher. It resets every day; joining is your choice."],
] as const;

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

export default async function PuzzlesPage({ searchParams }: { searchParams: SearchParams }) {
export default function PuzzlesPage() {
const area = areaById("puzzles");
const query = await searchParams;
const id = pickFilter(query.kind, KINDS.map((k) => k.id)) ?? KINDS[0].id;
const kind = KINDS.find((k) => k.id === id)!;

return (
<AreaPage>
<AreaHero
eyebrow="Puzzles"
title="Daily puzzles"
eyebrow="Daily games"
title="Play, fix, learn"
status={area.status}
mood="wink"
intro="One small puzzle a day, the same for everyone. Solve it, see where you landed on today's leaderboard, and come back tomorrow."
intro="Three games, three rounds each, new every day. Each round you solve earns a little XP, with a bonus for finishing a whole game."
/>

<div className="mt-8">
<FilterChips label="Kind" param="kind" current={id} basePath="/puzzles" params={{}} options={KINDS.map((k) => ({ value: k.id, label: k.label }))} />
</div>

<section aria-label={kind.label} className="mt-6 grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<div className="border border-border bg-card p-5 sm:p-6">
<span className="text-sm font-bold uppercase tracking-wider text-primary">{kind.label}</span>
<p className="mt-2 text-xl tracking-[-0.02em]">{kind.goal}</p>
<p className="mt-4 border-l-4 border-brand-yellow bg-secondary/60 px-4 py-3 text-base">
<span className="font-bold">Example: </span>
{kind.example}
</p>
</div>
<dl className="divide-y divide-border border border-border bg-card">
{RULES.map(([title, body]) => (
<div key={title} className="px-5 py-3.5">
<dt className="text-base font-bold">{title}</dt>
<dd className="text-base text-muted-foreground">{body}</dd>
</div>
))}
</dl>
</section>

<ComingSoonPanel title="Puzzles are on the way" action={{ href: "/labs?kind=visual", label: "Try a visual lab now" }}>
The visual labs are the closest thing today: a design, a set of checks, and a reason for every result.
</ComingSoonPanel>
<GamesHub />
</AreaPage>
);
}
97 changes: 97 additions & 0 deletions frontend/src/components/games/celebration.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"use client";

import { useEffect, useRef } from "react";

const COLORS = ["#1d4ed8", "#facc15", "#22c55e", "#f97316", "#ec4899", "#38bdf8"];

type Particle = { x: number; y: number; vx: number; vy: number; size: number; spin: number; angle: number; color: string; life: number };

/**
* A burst of confetti over the whole page for about 2.5 seconds. It draws on one canvas, does not
* catch clicks, and does nothing at all when the system asks for reduced motion.
*/
export function ConfettiBurst({ stars, burstKey }: { stars: number; burstKey: string }) {
const canvas = useRef<HTMLCanvasElement>(null);

useEffect(() => {
const el = canvas.current;
if (!el || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const ctx = el.getContext("2d");
if (!ctx) return;
const ratio = Math.min(window.devicePixelRatio || 1, 2);
el.width = window.innerWidth * ratio;
el.height = window.innerHeight * ratio;
ctx.scale(ratio, ratio);

const count = 70 + Math.max(1, stars) * 45;
const particles: Particle[] = Array.from({ length: count }, (_, i) => {
const side = i % 2 === 0 ? 0.2 : 0.8;
const angle = (-Math.PI / 2) + (Math.random() - 0.5) * 1.5;
const speed = 8 + Math.random() * 10;
return {
x: window.innerWidth * side, y: window.innerHeight * 0.72,
vx: Math.cos(angle) * speed * (side < 0.5 ? 1 : -1) * 0.6, vy: Math.sin(angle) * speed,
size: 5 + Math.random() * 6, spin: (Math.random() - 0.5) * 0.4, angle: Math.random() * Math.PI,
color: COLORS[i % COLORS.length]!, life: 1,
};
});

let frame = 0;
let raf = 0;
const tick = () => {
frame++;
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
for (const p of particles) {
p.vy += 0.32;
p.vx *= 0.992;
p.x += p.vx;
p.y += p.vy;
p.angle += p.spin;
p.life = Math.max(0, 1 - frame / 150);
ctx.save();
ctx.globalAlpha = p.life;
ctx.translate(p.x, p.y);
ctx.rotate(p.angle);
ctx.fillStyle = p.color;
ctx.fillRect(-p.size / 2, -p.size / 4, p.size, p.size / 2);
ctx.restore();
}
if (frame < 150) raf = requestAnimationFrame(tick);
else ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [stars, burstKey]);

return <canvas ref={canvas} aria-hidden className="pointer-events-none fixed inset-0 z-50 size-full" />;
}

/** Three stars that pop in one after another. Earned stars are filled. */
export function StarRow({ stars, size = "lg" }: { stars: number; size?: "sm" | "lg" }) {
const box = size === "lg" ? "size-10" : "size-4";
return (
<div className="flex items-center gap-1.5" role="img" aria-label={`${stars} of 3 stars`}>
{[1, 2, 3].map((n) => (
<svg
key={n}
viewBox="0 0 24 24"
className={`${box} ${n <= stars ? "fill-brand-yellow stroke-amber-500 motion-safe:animate-[bm-pop_0.45s_ease-out_both]" : "fill-transparent stroke-border"}`}
style={n <= stars ? { animationDelay: `${n * 140}ms` } : undefined}
strokeWidth={1.6}
>
<path d="M12 2.5l2.9 6.1 6.6.8-4.9 4.6 1.3 6.6L12 17.3 6.1 20.6l1.3-6.6L2.5 9.4l6.6-.8L12 2.5z" strokeLinejoin="round" />
</svg>
))}
</div>
);
}

/** "+3 XP" chip that floats up and settles. */
export function XpChip({ amount, label }: { amount: number; label?: string }) {
if (amount <= 0) return null;
return (
<span className="inline-flex items-center gap-1 rounded-sm bg-brand-yellow px-2.5 py-1 text-sm font-bold text-black motion-safe:animate-[bm-pop_0.5s_ease-out_both]">
+{amount} XP{label ? <span className="font-medium"> {label}</span> : null}
</span>
);
}
Loading
Loading