A campaign with unlocks, synthesised sound, puzzles and the puzzle of the week

- Campaign projects start with NAND only; challenges open along a
  dependency chain, each solution becomes a usable part, and basic parts
  unlock on the way. Locked parts and challenges say what opens them.
- Sound effects made with Web Audio: place, connect, switches, buttons,
  delete, clock ticks (opt-in), solve, fail, unlock, record. Mute and
  volume in the top bar and Display settings.
- Publish any circuit as a puzzle link; only its behaviour is shared.
  The server re-runs the checks on submitted solutions, counts their
  transistors and keeps each player's best; the board shows a histogram
  and your place. A generated puzzle of the week for everyone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-20 19:54:57 +02:00
parent 9754ecc0b4
commit 2edb458372
25 changed files with 1553 additions and 52 deletions

View File

@ -7,6 +7,9 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
## What it does
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note.
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
- Sound (speaker in the top bar; volume and clock ticks under Display): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
- Cables: a bundle gathers 2 to 32 wires into one thick cable, a split fans it out again in the same order; one bundle can feed several splits. Select some wires and press "Bundle into cable" to have both ends placed for you (the cable takes the wires' colour); "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
- Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen".
@ -38,6 +41,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
- `cables.ts` bundles wires into cables and takes them apart again.
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
- `wires.ts` edits wire routes (segment and corner drags, splits, branches); `project.ts` validates project data for both the browser and the server; `storage.ts` is the browser's project library.

View File

@ -1712,3 +1712,83 @@ kbd {
.challenge .score strong {
color: var(--on);
}
/* ── Campaign and puzzles (palette) ─────────────────────────────── */
.campaign,
.weekly {
margin: 12px 12px 4px;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--panel-2);
font-size: 12px;
}
.campaign p,
.weekly p {
margin-top: 6px;
color: var(--muted);
line-height: 1.45;
}
.weekly {
border-color: rgb(76 194 255 / 0.35);
}
.campaign .bar {
height: 6px;
margin-top: 8px;
border-radius: 3px;
background: var(--bg);
overflow: hidden;
}
.campaign .bar span {
display: block;
height: 100%;
background: var(--on);
border-radius: 3px;
transition: width 0.6s cubic-bezier(0.2, 0.8, 0.2, 1);
}
.challenges li.locked {
opacity: 0.55;
}
.challenges .needs {
color: var(--lamp);
}
.btn-sm:disabled {
opacity: 0.45;
cursor: not-allowed;
}
/* Unlocks after a solve, and the puzzle's target. */
.challenge .unlock {
display: flex;
gap: 8px;
margin-top: 8px;
padding: 8px 10px;
border-radius: 6px;
font-size: 12px;
color: var(--lamp);
background: rgb(255 211 77 / 0.08);
border: 1px solid rgb(255 211 77 / 0.3);
animation: unlock-in 0.5s cubic-bezier(0.2, 0.8, 0.2, 1);
}
.challenge .unlock p + p {
margin-top: 2px;
}
@keyframes unlock-in {
from {
opacity: 0;
transform: translateY(4px) scale(0.98);
}
}
.target-table .truth {
max-height: 220px;
}

View File

@ -40,6 +40,7 @@ onMounted(() => {
Click the pin {{ link.dir === 'out' ? 'it goes to' : 'it comes from' }}, or a part to use its next free pin. <kbd>Esc</kbd> stops.
</div>
<EditorTruthTableDialog v-if="ed.dialog.value === 'table'" />
<EditorPublishDialog v-if="ed.dialog.value === 'publish'" />
<EditorHelp v-if="ed.showHelp.value" />
<EditorProjectsDialog v-if="ed.dialog.value === 'projects'" />
<EditorShareDialog v-if="ed.dialog.value === 'share'" />

View File

@ -203,6 +203,7 @@ function onDrop(e: DragEvent) {
if (!raw) return
const p = JSON.parse(raw) as { kind: CircuitNode['kind']; chip?: string }
if (p.chip && !ed.canPlace(p.chip)) return ed.notify('A component cannot contain itself', 'error')
if (!ed.canPlaceKind(p.kind)) return
const [x, y] = originFor(p, toWorld(e))
ed.addNode(p, x, y)
}
@ -656,7 +657,7 @@ function onKey(e: KeyboardEvent) {
} else if (!mod && !e.altKey && key === 'w' && ed.selection.value.length) ed.startLinking(ed.selection.value, e.shiftKey ? 'in' : undefined)
else if (!mod && !e.altKey && key === 'f') fit()
else if (!mod && !e.altKey && e.key === '?') ed.showHelp.value = !ed.showHelp.value
else if (!mod && !e.altKey && QUICK[key]) ed.placing.value = { kind: QUICK[key]! }
else if (!mod && !e.altKey && QUICK[key] && ed.canPlaceKind(QUICK[key]!)) ed.placing.value = { kind: QUICK[key]! }
}
function onKeyUp(e: KeyboardEvent) {

View File

@ -2,7 +2,7 @@
import type { ChallengeCheck } from '~/composables/useEditor'
import { tableMarkdown, type TruthTable } from '~/lib/logic/analyze'
import { cableOf } from '~/lib/logic/cables'
import { CHALLENGES } from '~/lib/logic/challenges'
import { apiId, isTable } from '~/lib/logic/puzzles'
import { chipPins } from '~/lib/logic/geometry'
import { usages } from '~/lib/logic/ops'
import { WIRE_COLORS, type CrossingStyle, type SymbolKind } from '~/lib/logic/types'
@ -58,8 +58,29 @@ function setCrossing(c: CrossingStyle) {
const pins = computed(() => chipPins(def.value))
const users = computed(() => usages(ed.project.value, def.value.id))
const groupNames = computed(() => [...new Set(ed.project.value.components.map(d => d.group).filter(Boolean))])
const challenge = computed(() => CHALLENGES.find(c => c.id === def.value.challenge))
// The challenge or puzzle this circuit is for.
const challenge = computed(() => {
const t = ed.task.value
const c = t?.challenge ?? t?.puzzle
return t && c ? { id: t.id, name: c.name, goal: c.goal, inputs: c.inputs, outputs: c.outputs, puzzle: t.puzzle } : undefined
})
const solved = computed(() => !!challenge.value && ed.project.value.solved.includes(challenge.value.id))
const board = computed(() => (challenge.value?.puzzle ? ed.boards[challenge.value.id] : undefined))
// What the puzzle asks for, as a table to read.
const target = computed<TruthTable | null>(() => {
const p = challenge.value?.puzzle
if (!p) return null
return { inputs: p.inputs, outputs: p.outputs, rows: p.steps.map(s => ({ ins: p.inputs.map(l => s.set[l] ?? 0), outs: p.outputs.map(l => s.expect[l] ?? 0), settled: true })) }
})
watch(
() => challenge.value?.puzzle,
p => {
if (p && !ed.boards[p.id]) void ed.loadBoard(p)
},
{ immediate: true },
)
const showTarget = ref(true)
const puzzleLink = computed(() => (challenge.value?.puzzle ? `${location.origin}/puzzle/${apiId(challenge.value.puzzle.id)}` : ''))
const packName = ref('')
function pack() {
@ -163,10 +184,19 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<section v-if="challenge" class="challenge" :class="{ solved }">
<h3>
<Icon :name="solved ? 'lucide:badge-check' : 'lucide:flag'" class="size-4" />
Challenge: {{ challenge.name }}
{{ challenge.puzzle ? 'Puzzle' : 'Challenge' }}: {{ challenge.name }}
</h3>
<p>{{ challenge.goal }}</p>
<p class="pins">Pins: {{ challenge.inputs.join(', ') }} → {{ challenge.outputs.join(', ') }}</p>
<template v-if="target">
<button class="section-toggle mt-2" @click="showTarget = !showTarget">
<Icon :name="showTarget ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
{{ isTable(challenge.puzzle!) ? 'Target truth table' : `Target: ${target.rows.length} steps from power-on` }}
</button>
<div v-if="showTarget" class="target-table">
<EditorTruthTable :table="target" />
</div>
</template>
<button class="btn btn-primary w-full" @click="runCheck"><Icon name="lucide:play" class="size-4" /> Check</button>
<p v-if="check" class="result" :class="check.pass ? 'pass' : 'fail'">
<Icon :name="check.pass ? 'lucide:circle-check' : 'lucide:circle-x'" class="size-4 shrink-0" />
@ -182,6 +212,21 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<Icon name="lucide:trophy" class="size-4 shrink-0" /> New record! {{ check.record - check.transistors }} fewer than before ({{ check.record }}).
</p>
<p v-else-if="check?.pass && check.best === check.transistors" class="hint">Fewer transistors is better: 4 per NAND gate. Can you make it smaller?</p>
<div v-if="check?.pass && (check.unlocked?.length || check.nextUp?.length)" class="unlock">
<Icon name="lucide:sparkles" class="size-4 shrink-0" />
<div>
<p v-if="check.unlocked?.length"><strong>Unlocked:</strong> {{ check.unlocked.join(', ') }}</p>
<p v-if="check.nextUp?.length"><strong>New challenges:</strong> {{ check.nextUp.join(', ') }}</p>
</div>
</div>
<template v-if="challenge.puzzle">
<p v-if="challenge.puzzle.author !== undefined" class="hint mt-2">The author's solution uses {{ challenge.puzzle.author.toLocaleString() }} transistors.</p>
<EditorScoreChart v-if="board?.players" :summary="board" :mine="bestHere" />
<p v-else class="hint mt-2">No one has solved it yet. Be the first.</p>
<button class="btn btn-ghost mt-2 w-full" title="Copy the link to this puzzle" @click="ed.copyText(puzzleLink, 'Puzzle link copied')">
<Icon name="lucide:link" class="size-4" /> Copy puzzle link
</button>
</template>
</section>
<!-- Circuit -->
@ -227,6 +272,14 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<p v-for="err in ed.errors.value" :key="err" class="result fail">
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" /> {{ err }}
</p>
<button
v-if="!challenge"
class="btn mt-1 mb-2 w-full"
title="Turn this circuit into a puzzle link: others build the same behaviour, your circuit stays private"
@click="ed.dialog.value = 'publish'"
>
<Icon name="lucide:puzzle" class="size-4" /> Publish as puzzle
</button>
<p v-if="users.length" class="hint">
Used in
<template v-for="(u, i) in users" :key="u.id">
@ -268,6 +321,29 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<input type="checkbox" :checked="!!settings.tidy" @change="ed.setTidy(!settings.tidy)" />
Tidy wiring: sorted parallel runs, one trunk per signal, fewer crossings
</label>
<div class="field mt-3">
<span>Sound</span>
<div class="flex items-center gap-2">
<button class="icon-btn" :title="ed.sound.value.on ? 'Turn sound off' : 'Turn sound on'" @click="ed.setSound({ on: !ed.sound.value.on })">
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
</button>
<input
type="range"
min="0"
max="1"
step="0.05"
class="grow"
:value="ed.sound.value.volume"
:disabled="!ed.sound.value.on"
aria-label="Volume"
@change="ed.setSound({ volume: Number(($event.target as HTMLInputElement).value) })"
/>
</div>
</div>
<label class="check">
<input type="checkbox" :checked="ed.sound.value.ticks" :disabled="!ed.sound.value.on" @change="ed.setSound({ ticks: !ed.sound.value.ticks })" />
Tick on every clock cycle (up to 8 Hz)
</label>
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
</button>

View File

@ -4,28 +4,12 @@ import { compile } from '~/lib/logic/compile'
import { cableOf } from '~/lib/logic/cables'
import { cableBits, chipPins, MAX_BITS, rowLabel } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
import { LAMP_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
const props = defineProps<{ node: CircuitNode }>()
const ed = useEditor()
const KIND_NAMES: Record<string, string> = {
nand: 'NAND gate',
input: 'Input switch',
output: 'Output pin',
lamp: 'Lamp',
button: 'Push button',
clock: 'Clock',
high: 'Constant 1',
low: 'Ground (0)',
hex: 'Hex display',
note: 'Note',
panel: 'Input panel',
bundle: 'Cable bundle',
split: 'Cable split',
pixel: 'Pixel',
}
const CONTROLS: { value: PanelControl; label: string }[] = [
{ value: 'switch', label: 'Switch' },
{ value: 'button', label: 'Button' },

View File

@ -1,6 +1,8 @@
<script setup lang="ts">
import { shortCount } from '~/lib/logic/analyze'
import { CHALLENGES } from '~/lib/logic/challenges'
import { campaignProgress, challengeName, challengeOpen, defUsable, isCampaign, KIND_UNLOCK, NEEDS } from '~/lib/logic/progress'
import { weekKey, weeklyId } from '~/lib/logic/puzzles'
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
const ed = useEditor()
@ -24,7 +26,7 @@ const BASICS: { kind: NodeKind; name: string; icon: string; key?: string; hint:
{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.' },
]
const GROUP_ORDER = ['', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Displays', 'Demos']
const GROUP_ORDER = ['', 'Puzzles', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Displays', 'Demos']
const groups = computed(() => {
const q = query.value.trim().toLowerCase()
@ -43,6 +45,10 @@ const groups = computed(() => {
function pick(kind: NodeKind, chip?: string) {
if (chip && !ed.canPlace(chip)) return
if (!ed.canPlaceKind(kind)) {
ed.play('error')
return ed.notify(lockedHint(kind), 'error')
}
ed.placing.value = { kind, chip }
}
@ -57,6 +63,31 @@ function onDragStart(e: DragEvent, kind: NodeKind, chip?: string) {
const solved = computed(() => new Set(ed.project.value.solved))
const best = computed(() => ed.project.value.best ?? {})
const solvedCount = computed(() => CHALLENGES.filter(c => solved.value.has(c.id)).length)
const campaign = computed(() => isCampaign(ed.project.value))
const progress = computed(() => campaignProgress(ed.project.value))
const open = (id: string) => challengeOpen(ed.project.value, id)
const needsText = (id: string) => `Solve ${(NEEDS[id] ?? []).filter(n => !solved.value.has(n)).map(challengeName).join(' and ')} first`
const puzzles = computed(() => (ed.project.value.puzzles ?? []).filter(p => !p.id.startsWith('week:') || p.id === weeklyId(weekKey())))
const weeklyStarted = computed(() => ed.project.value.components.some(d => d.challenge === weeklyId(weekKey())))
function lockedHint(kind: NodeKind) {
const by = KIND_UNLOCK[kind]
return by ? `Solve the ${challengeName(by)} challenge to unlock this part` : ''
}
function openWeekly() {
const spec = ed.project.value.puzzles?.find(p => p.id === weeklyId(weekKey()))
if (spec) ed.beginPuzzle(spec)
else void ed.openPuzzle('weekly')
}
function compTitle(d: ComponentDef) {
if (d.id === ed.def.value.id) return 'You are editing this one'
if (!defUsable(ed.project.value, d)) return 'Solve this challenge to use it as a part'
if (!ed.canPlace(d.id)) return 'Contains the circuit you are editing'
return d.description || 'Click, then click on the canvas to place'
}
const started = computed(() => new Map(ed.project.value.components.filter(d => d.challenge).map(d => [d.challenge!, d])))
</script>
@ -66,7 +97,7 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
<button :class="{ active: tab === 'parts' }" @click="tab = 'parts'">Parts</button>
<button :class="{ active: tab === 'challenges' }" @click="tab = 'challenges'">
Challenges
<span class="count">{{ solved.size }}/{{ CHALLENGES.length }}</span>
<span class="count">{{ solvedCount }}/{{ CHALLENGES.length }}</span>
</button>
</div>
@ -76,16 +107,17 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
<li v-for="item in BASICS" :key="item.kind">
<button
class="item"
:class="{ active: ed.placing.value?.kind === item.kind && !ed.placing.value?.chip }"
:title="item.hint"
draggable="true"
:class="{ active: ed.placing.value?.kind === item.kind && !ed.placing.value?.chip, blocked: !ed.canPlaceKind(item.kind) }"
:title="ed.canPlaceKind(item.kind) ? item.hint : lockedHint(item.kind)"
:draggable="ed.canPlaceKind(item.kind)"
@click="pick(item.kind)"
@dragstart="onDragStart($event, item.kind)"
>
<span v-if="item.kind === 'nand'" class="nand-badge">&amp;</span>
<Icon v-else :name="item.icon" class="size-4 shrink-0 text-(--muted)" />
<span class="grow truncate">{{ item.name }}</span>
<kbd v-if="item.key">{{ item.key }}</kbd>
<Icon v-if="!ed.canPlaceKind(item.kind)" name="lucide:lock" class="size-3.5 shrink-0 text-(--muted)" />
<kbd v-else-if="item.key">{{ item.key }}</kbd>
</button>
</li>
</ul>
@ -102,7 +134,7 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
<button
class="item"
:class="{ active: ed.placing.value?.chip === d.id, current: d.id === ed.def.value.id, blocked: !ed.canPlace(d.id) }"
:title="d.id === ed.def.value.id ? 'You are editing this one' : !ed.canPlace(d.id) ? 'Contains the circuit you are editing' : d.description || 'Click, then click on the canvas to place'"
:title="compTitle(d)"
:draggable="ed.canPlace(d.id)"
@click="pick('chip', d.id)"
@dragstart="onDragStart($event, 'chip', d.id)"
@ -130,17 +162,60 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
</div>
<div v-else class="scroll">
<p class="intro">
<div v-if="campaign" class="campaign">
<div class="flex items-center justify-between">
<span class="font-semibold">Campaign</span>
<span class="tabular-nums text-(--muted)">{{ solvedCount }} / {{ CHALLENGES.length }}</span>
</div>
<div class="bar"><span :style="{ width: `${progress * 100}%` }" /></div>
<p>Every part you solve becomes yours to use. New parts and challenges open as you go.</p>
</div>
<p v-else class="intro">
Build each part from NAND and the parts you already made. Start a challenge, wire it up, then press
<strong>Check</strong> on the right.
</p>
<div class="weekly">
<div class="flex items-center gap-2">
<Icon name="lucide:calendar-days" class="size-4 shrink-0 text-(--accent)" />
<span class="grow font-medium">Puzzle of the week</span>
<button class="btn-sm" @click="openWeekly">{{ weeklyStarted ? 'Open' : 'Play' }}</button>
</div>
<p>A new logic puzzle every Monday, the same for everyone. Fewest transistors wins.</p>
</div>
<template v-if="puzzles.length">
<h3>Puzzles</h3>
<ul class="challenges">
<li v-for="p in puzzles" :key="p.id" :class="{ solved: solved.has(p.id) }">
<div class="flex items-center gap-2">
<Icon :name="solved.has(p.id) ? 'lucide:circle-check' : 'lucide:puzzle'" class="size-4 shrink-0" :class="solved.has(p.id) ? 'text-(--on)' : 'text-(--muted)'" />
<span class="grow font-medium">{{ p.name }}</span>
<button class="btn-sm" @click="ed.beginPuzzle(p)">Open</button>
</div>
<p class="pins">
{{ p.inputs.join(', ') }} → {{ p.outputs.join(', ') }}
<span v-if="best[p.id] !== undefined" class="best"> · best {{ best[p.id]!.toLocaleString() }} transistors</span>
</p>
</li>
</ul>
</template>
<h3>Challenges</h3>
<ul class="challenges">
<li v-for="c in CHALLENGES" :key="c.id" :class="{ solved: solved.has(c.id) }">
<li v-for="c in CHALLENGES" :key="c.id" :class="{ solved: solved.has(c.id), locked: !open(c.id) }">
<div class="flex items-center gap-2">
<Icon :name="solved.has(c.id) ? 'lucide:circle-check' : 'lucide:circle'" class="size-4 shrink-0" :class="solved.has(c.id) ? 'text-(--on)' : 'text-(--muted)'" />
<Icon
:name="solved.has(c.id) ? 'lucide:circle-check' : open(c.id) ? 'lucide:circle' : 'lucide:lock'"
class="size-4 shrink-0"
:class="solved.has(c.id) ? 'text-(--on)' : 'text-(--muted)'"
/>
<span class="grow font-medium">{{ c.name }}</span>
<button class="btn-sm" @click="ed.beginChallenge(c)">{{ started.has(c.id) ? 'Open' : 'Start' }}</button>
<button class="btn-sm" :disabled="!open(c.id) && !started.has(c.id)" :title="open(c.id) ? '' : needsText(c.id)" @click="ed.beginChallenge(c)">
{{ started.has(c.id) ? 'Open' : 'Start' }}
</button>
</div>
<p v-if="!open(c.id)" class="needs">{{ needsText(c.id) }}</p>
<p>{{ c.goal }}</p>
<p class="pins">
{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}

View File

@ -116,6 +116,9 @@ function onFile(e: Event) {
</template>
<div class="mt-4 flex flex-wrap gap-2">
<button class="btn btn-primary" title="Start with NAND only and earn every other part by solving challenges" @click="ed.newProject(false, true); close()">
<Icon name="lucide:trophy" class="size-4" /> New campaign
</button>
<button class="btn" @click="ed.newProject(false); close()"><Icon name="lucide:file" class="size-4" /> New (NAND only)</button>
<button class="btn" @click="ed.newProject(true); close()"><Icon name="lucide:file-plus" class="size-4" /> New with examples</button>
<button class="btn" @click="fileInput?.click()"><Icon name="lucide:folder-open" class="size-4" /> Open file</button>

View File

@ -0,0 +1,85 @@
<script setup lang="ts">
import { chipPins } from '~/lib/logic/geometry'
import { describeCircuit } from '~/lib/logic/puzzles'
const ed = useEditor()
const close = () => (ed.dialog.value = null)
const name = ref(ed.def.value.name)
const goal = ref(ed.def.value.description ?? '')
const link = ref('')
const error = ref('')
const busy = ref(false)
/** What players will get, or why this circuit can't be a puzzle yet. */
const preview = computed(() => {
try {
const d = describeCircuit(ed.getDef.value, ed.def.value.id)
return { ok: true as const, ...d }
} catch (e) {
return { ok: false as const, error: (e as Error).message }
}
})
const pins = computed(() => chipPins(ed.def.value))
async function publish() {
busy.value = true
error.value = ''
try {
link.value = await ed.publishPuzzle(name.value, goal.value)
ed.play('unlock')
} catch (e) {
error.value = (e as Error).message
} finally {
busy.value = false
}
}
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div class="modal" role="dialog" aria-labelledby="publish-title">
<div class="flex items-start justify-between gap-4">
<h2 id="publish-title">Publish as puzzle</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<p class="hint mt-1">
Others get the pins of "{{ ed.def.value.name }}" and have to build something that behaves the same. Your circuit stays private: only its behaviour is
published. Everyone's transistor count goes on the puzzle's board, next to yours ({{ ed.transistors(ed.def.value.id).toLocaleString() }}).
</p>
<template v-if="!link">
<label class="field mt-4">
<span>Name</span>
<input v-model="name" maxlength="60" />
</label>
<label class="field">
<span>Goal, shown to players</span>
<textarea v-model="goal" rows="3" maxlength="400" placeholder="What should it do? Leave empty to just show the target." />
</label>
<p v-if="preview.ok" class="result pass">
<Icon name="lucide:circle-check" class="size-4 shrink-0" />
<span>
{{ pins.inputs.map(p => p.label).join(', ') }} → {{ pins.outputs.map(p => p.label).join(', ') }}.
<template v-if="preview.sequential">It stores state, so players get {{ preview.steps.length }} steps to match from power-on.</template>
<template v-else>Players get the full truth table, {{ preview.steps.length }} rows.</template>
</span>
</p>
<p v-else class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ preview.error }}</p>
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
<button class="btn btn-primary mt-3" :disabled="!preview.ok || busy" @click="publish">
<Icon name="lucide:puzzle" class="size-4" /> {{ busy ? 'Publishing…' : 'Publish' }}
</button>
</template>
<template v-else>
<h3>Puzzle link</h3>
<div class="link-row">
<input :value="link" readonly @focus="($event.target as HTMLInputElement).select()" />
<button class="btn btn-primary" @click="ed.copyText(link, 'Puzzle link copied')"><Icon name="lucide:copy" class="size-4" /> Copy</button>
</div>
<p class="hint mt-2">Anyone with the link gets the puzzle in their own project. Changing your circuit later doesn't change the puzzle.</p>
</template>
</div>
</div>
</template>

View File

@ -0,0 +1,126 @@
<script setup lang="ts">
// How everyone did on a puzzle: players per transistor count, fewest on the
// left. Wide ranges are grouped into at most 16 bars. Your own bar stands
// out and is named in the text, so it never relies on colour alone.
import type { PuzzleSummary } from '~/composables/useEditor'
const props = defineProps<{ summary: PuzzleSummary; mine?: number }>()
const MAX_BARS = 16
const bars = computed(() => {
const h = props.summary.histogram
if (!h.length) return []
const lo = h[0]!.t
const hi = h[h.length - 1]!.t
// Transistor counts come in steps of 4 (one NAND each).
const steps = (hi - lo) / 4 + 1
const per = Math.max(1, Math.ceil(steps / MAX_BARS))
const out: { from: number; to: number; n: number }[] = []
for (let i = 0; i < Math.ceil(steps / per); i++) out.push({ from: lo + i * per * 4, to: lo + ((i + 1) * per - 1) * 4, n: 0 })
for (const { t, n } of h) out[Math.min(out.length - 1, Math.floor((t - lo) / 4 / per))]!.n += n
return out
})
const top = computed(() => Math.max(1, ...bars.value.map(b => b.n)))
const you = computed(() => props.summary.you?.t ?? props.mine)
const isMine = (b: { from: number; to: number }) => you.value !== undefined && you.value >= b.from && you.value <= b.to
const range = (b: { from: number; to: number }) => (b.from === b.to ? `${b.from}` : `${b.from}–${b.to}`)
const hover = ref<number | null>(null)
const readout = computed(() => {
const b = hover.value !== null ? bars.value[hover.value] : undefined
if (b) return `${b.n} player${b.n === 1 ? '' : 's'} with ${range(b)} transistors`
const y = props.summary.you
if (y) return `You: ${y.t} transistors, place ${y.rank} of ${props.summary.players}`
return `${props.summary.players} player${props.summary.players === 1 ? '' : 's'} solved it`
})
</script>
<template>
<figure class="score-chart">
<figcaption>Everyone's transistors</figcaption>
<div class="plot" @pointerleave="hover = null">
<div
v-for="(b, i) in bars"
:key="i"
class="col"
:class="{ mine: isMine(b), hot: hover === i }"
:aria-label="`${range(b)} transistors: ${b.n} players`"
@pointerenter="hover = i"
>
<span class="bar" :style="{ height: b.n ? `${Math.max(6, (b.n / top) * 100)}%` : '0' }" />
</div>
</div>
<div class="axis">
<span>{{ bars[0]?.from }}</span>
<span>fewer is better</span>
<span>{{ bars.at(-1)?.to }}</span>
</div>
<p class="readout">{{ readout }}</p>
</figure>
</template>
<style scoped>
.score-chart {
margin-top: 10px;
padding: 10px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--panel-2);
}
figcaption {
font-size: 11px;
font-weight: 600;
color: var(--muted);
margin-bottom: 6px;
}
.plot {
display: flex;
align-items: stretch;
gap: 2px;
height: 64px;
border-bottom: 1px solid var(--border);
}
.col {
flex: 1;
display: flex;
align-items: flex-end;
justify-content: center;
cursor: default;
}
.bar {
width: 100%;
max-width: 22px;
border-radius: 4px 4px 0 0;
background: #4f6278;
transition: height 0.4s ease;
}
.col.hot .bar {
background: #7d93ad;
}
.col.mine .bar {
background: var(--on);
}
.axis {
display: flex;
justify-content: space-between;
margin-top: 3px;
font-family: var(--font-mono);
font-size: 10px;
color: var(--muted);
}
.readout {
margin-top: 6px;
font-size: 12px;
color: var(--text);
}
</style>

View File

@ -96,6 +96,14 @@ const linkIcon = computed(() => {
>
<Icon name="lucide:zap" class="size-4" />
</button>
<button
class="tb-btn"
:class="{ active: ed.sound.value.on }"
:title="ed.sound.value.on ? 'Sound on (volume and clock ticks under Display, right)' : 'Sound off'"
@click="ed.setSound({ on: !ed.sound.value.on })"
>
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
</button>
<button class="tb-btn share-btn" :class="ed.linkState.value" title="Save online, share a link, export or import a file" @click="ed.dialog.value = 'share'">
<Icon :name="linkIcon" class="size-4" />
<span class="hidden md:inline">Share</span>

View File

@ -4,6 +4,9 @@
import { nandCounts, runSteps, stats, tableCsv, TRANSISTORS_PER_NAND, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze'
import { bundleWires, dissolveCable } from '~/lib/logic/cables'
import { loadSoundSettings, saveSoundSettings, sfx, type Sound, type SoundSettings } from '~/lib/audio'
import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUnlocked, NEEDS, unlockedBy } from '~/lib/logic/progress'
import { apiId, makePuzzle, scoreSolution } from '~/lib/logic/puzzles'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { compile, rowSource } from '~/lib/logic/compile'
import { MAX_BITS, shapeOf, type Pt } from '~/lib/logic/geometry'
@ -24,6 +27,7 @@ import {
pasteClip,
pruneWires,
startChallenge,
startPuzzle,
swapNode,
uid,
unlinkWires,
@ -50,11 +54,22 @@ import {
type AccountUser,
type ProjectMeta,
} from '~/lib/logic/storage'
import type { CircuitNode, NodeKind, PanelControl, PanelRow, PinRef, Project, WireColor } from '~/lib/logic/types'
import type { CircuitNode, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
/** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */
export interface PuzzleSummary {
players: number
histogram: { t: number; n: number }[]
you?: { t: number; d: number | null; rank: number }
}
export interface ChallengeCheck extends TestResult {
transistors: number
/** Parts this first solve made usable (campaign). */
unlocked?: string[]
/** Challenges it opened. */
nextUp?: string[]
/** Fewest transistors of any passing solution so far, this one included. */
best?: number
/** Set when this one beat an earlier record: that record. */
@ -125,7 +140,7 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table'>(null)
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish'>(null)
/** Pins being wired one after another; `at` is the one the next click connects. */
const linking = ref<{ queue: LinkEnd[]; at: number } | null>(null)
/** Project whose savegames the versions dialog shows. */
@ -299,11 +314,13 @@ function create() {
const s = sim.value
if (s) {
let rises = 0
let tickHz = 0
const n = s.nl.clocks.length
if (running.value && n) {
if (acc.length !== n) acc = new Array(n).fill(0)
// Ticks count the first clock that follows the top-bar speed (or the first clock).
const counted = Math.max(0, s.nl.clockHz.indexOf(0))
tickHz = s.nl.clockHz[counted] || hz.value
const fastest: number[] = []
for (let i = 0; i < n; i++) {
const f = s.nl.clockHz[i] || hz.value
@ -329,6 +346,7 @@ function create() {
}
}
if (rises) cycles.value += rises
if (rises && sound.value.ticks && tickHz > 0 && tickHz <= 8) play('tick')
const settled = s.run(BUDGET)
unsettled = settled ? 0 : unsettled + 1
status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy'
@ -392,11 +410,29 @@ function create() {
selection.value = [node.id]
wireSel.value = []
commit()
play('place')
return node
}
function canPlace(chipId: string) {
return !containsDef(project.value, chipId, def.value.id)
const d = getDef.value(chipId)
return !containsDef(project.value, chipId, def.value.id) && (!d || defUsable(project.value, d))
}
/** In a campaign, basic parts are earned; elsewhere everything can be placed. */
function canPlaceKind(kind: NodeKind) {
return kindUnlocked(project.value, kind)
}
// ── Sound ─────────────────────────────────────────────────────────
const sound = ref<SoundSettings>(loadSoundSettings())
function play(s: Sound) {
sfx(s, sound.value)
}
function setSound(patch: Partial<SoundSettings>) {
sound.value = { ...sound.value, ...patch }
saveSoundSettings(sound.value)
if (patch.on || patch.volume !== undefined) play('on')
}
/** True when the pin is a cable end (bundle output, split input). */
@ -410,6 +446,7 @@ function create() {
function connect(from: PinRef, to: PinRef, pts?: Pt[]) {
const d = def.value
if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) {
play('error')
return notify('A cable runs from a bundle to a split; single wires go to the bundle’s and split’s side pins', 'error')
}
const old = d.wires.find(w => w.to.node === to.node && w.to.pin === to.pin)
@ -428,6 +465,7 @@ function create() {
}
wireSel.value = []
commit()
play('connect')
}
/** Parts plus the panels docked to them: they move, copy and delete together. */
@ -446,6 +484,7 @@ function create() {
d.wires = d.wires.filter(w => !ids.has(w.from.node) && !ids.has(w.to.node) && !wires.has(w.id))
clearSelection()
commit()
play('delete')
}
const selectedWires = computed(() => {
@ -503,10 +542,12 @@ function create() {
function toggleInput(node: CircuitNode) {
node.on = !node.on
sim.value?.setSource(node.id, node.on)
play(node.on ? 'on' : 'off')
persist()
}
function press(node: CircuitNode, down: boolean) {
if (down && !pressed.has(node.id)) play('press')
if (down) pressed.add(node.id)
else pressed.delete(node.id)
sim.value?.setSource(node.id, down)
@ -517,12 +558,14 @@ function create() {
if (row.type !== 'switch') return
row.on = !row.on
sim.value?.setSource(rowSource(node.id, row.id), row.on)
play(row.on ? 'on' : 'off')
persist()
}
function pressRow(node: CircuitNode, row: PanelRow, down: boolean) {
if (row.type !== 'button') return
const key = rowSource(node.id, row.id)
if (down && !pressed.has(key)) play('press')
if (down) pressed.add(key)
else pressed.delete(key)
sim.value?.setSource(key, down)
@ -695,33 +738,130 @@ function create() {
function beginChallenge(c: Challenge) {
const existing = project.value.components.find(d => d.challenge === c.id)
if (existing) return open(existing.id)
if (!challengeOpen(project.value, c.id)) {
play('error')
return notify(`Solve ${(NEEDS[c.id] ?? []).filter(n => !project.value.solved.includes(n)).map(challengeName).join(' and ')} first`, 'error')
}
const d = startChallenge(project.value, c)
commit()
open(d.id)
}
/** The challenge or puzzle the open circuit is for. */
const task = computed(() => {
const id = def.value.challenge
if (!id) return null
const c = CHALLENGES.find(c => c.id === id)
if (c) return { id, challenge: c, puzzle: undefined, steps: challengeSteps(c) }
const p = project.value.puzzles?.find(p => p.id === id)
return p ? { id, challenge: undefined, puzzle: p, steps: p.steps } : null
})
function checkChallenge(): ChallengeCheck | null {
const c = CHALLENGES.find(c => c.id === def.value.challenge)
if (!c) return null
const res = runSteps(getDef.value, def.value.id, challengeSteps(c))
const t = task.value
if (!t) return null
const res = t.puzzle ? scoreSolution(toRaw(project.value.components), def.value.id, toRaw(t.puzzle)) : runSteps(getDef.value, def.value.id, t.steps)
const used = transistors(def.value.id)
const before = project.value.best?.[c.id]
if (!res.pass) return { ...res, transistors: used, best: before }
const before = project.value.best?.[t.id]
if (!res.pass) {
play('fail')
return { ...res, transistors: used, best: before }
}
let changed = false
if (!project.value.solved.includes(c.id)) {
project.value.solved.push(c.id)
const first = !project.value.solved.includes(t.id)
const opened = first && t.challenge ? unlockedBy(project.value, t.id) : { challenges: [], kinds: [] }
if (first) {
project.value.solved.push(t.id)
changed = true
}
const record = before === undefined || used < before
if (record) {
project.value.best = { ...project.value.best, [c.id]: used }
project.value.best = { ...project.value.best, [t.id]: used }
changed = true
}
if (changed) {
commit(false)
persist()
}
return { ...res, transistors: used, best: record ? used : before, record: record && before !== undefined ? before : undefined }
const unlocked = isCampaign(project.value) && first && t.challenge ? [def.value.name, ...opened.kinds.map(k => KIND_NAMES[k] ?? k)] : []
const nextUp = opened.challenges.map(challengeName)
play(record && before !== undefined ? 'record' : 'solve')
if (unlocked.length || nextUp.length) play('unlock')
if (t.puzzle) void submitScore(t.puzzle)
return {
...res,
transistors: used,
best: record ? used : before,
record: record && before !== undefined ? before : undefined,
unlocked,
nextUp,
}
}
// ── Puzzles ───────────────────────────────────────────────────────
/** A random id for this browser, so the server can keep one best score per player. */
function playerId(): string {
try {
let id = localStorage.getItem('logigate:player')
if (!id) {
id = uid('p') + uid() + uid()
localStorage.setItem('logigate:player', id)
}
return id
} catch {
return 'anonymous-player'
}
}
/** How everyone did, per puzzle id, as last heard from the server. */
const boards = reactive<Record<string, PuzzleSummary>>({})
async function loadBoard(spec: PuzzleSpec) {
try {
const res = await api<{ summary: PuzzleSummary }>('GET', `/api/puzzles/${apiId(spec.id)}?player=${encodeURIComponent(playerId())}`)
boards[spec.id] = res.summary
} catch {}
}
async function submitScore(spec: PuzzleSpec) {
try {
const res = await api<{ score: { pass: boolean; transistors: number }; summary: PuzzleSummary }>('POST', `/api/puzzles/${apiId(spec.id)}/scores`, {
player: playerId(),
defId: def.value.id,
components: toRaw(project.value.components),
})
boards[spec.id] = res.summary
} catch (e) {
notify(`Your score could not be sent: ${(e as Error).message}`, 'error')
}
}
function beginPuzzle(spec: PuzzleSpec) {
const d = startPuzzle(project.value, spec)
commit()
open(d.id)
void loadBoard(spec)
}
/** Opens a puzzle from the server: a link id, or "weekly". */
async function openPuzzle(id: string) {
try {
const res = await api<{ spec: PuzzleSpec; summary: PuzzleSummary }>('GET', `/api/puzzles/${encodeURIComponent(id)}?player=${encodeURIComponent(playerId())}`)
boards[res.spec.id] = res.summary
beginPuzzle(res.spec)
notify(`Puzzle: ${res.spec.name}`)
} catch (e) {
notify((e as Error).message, 'error')
} finally {
syncUrl()
}
}
/** Publishes the open circuit as a puzzle; returns its link. */
async function publishPuzzle(name: string, goal: string): Promise<string> {
const spec = makePuzzle(toRaw(project.value.components), def.value.id, name, goal)
const res = await api<{ id: string }>('POST', '/api/puzzles', { puzzle: spec })
return `${location.origin}/puzzle/${res.id}`
}
// ── Transistors ───────────────────────────────────────────────────
@ -792,10 +932,11 @@ function create() {
return m
}
function newProject(examples: boolean) {
function newProject(examples: boolean, campaign = false) {
persistNow()
const p = createProject({ examples })
const p = createProject({ examples, campaign })
activate(addProject(p), p)
if (campaign) notify('Campaign started: you have NAND. Open Challenges on the left and build NOT first.')
}
function duplicateProject(id: string) {
@ -1367,6 +1508,16 @@ function create() {
tidyAll,
exportTable,
transistors,
canPlaceKind,
sound,
setSound,
play,
task,
boards,
loadBoard,
beginPuzzle,
openPuzzle,
publishPuzzle,
isBus,
bundleSelected,
removeCable,

168
app/lib/audio.ts Normal file
View File

@ -0,0 +1,168 @@
// Sound effects, synthesised with the Web Audio API: no sound files to
// load or license. Every sound is a few short notes or a filtered click
// shaped by an envelope. Settings live in this browser only.
export type Sound = 'place' | 'connect' | 'on' | 'off' | 'press' | 'delete' | 'tick' | 'solve' | 'fail' | 'unlock' | 'record' | 'error'
export interface SoundSettings {
on: boolean
/** 0 to 1. */
volume: number
/** A soft tick on every clock cycle, at speeds up to 8 Hz. */
ticks: boolean
}
const KEY = 'logigate:sound'
const DEFAULTS: SoundSettings = { on: true, volume: 0.6, ticks: false }
export function loadSoundSettings(): SoundSettings {
try {
const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}') as Partial<SoundSettings>
return {
on: typeof raw.on === 'boolean' ? raw.on : DEFAULTS.on,
volume: typeof raw.volume === 'number' && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
ticks: typeof raw.ticks === 'boolean' ? raw.ticks : DEFAULTS.ticks,
}
} catch {
return { ...DEFAULTS }
}
}
export function saveSoundSettings(s: SoundSettings) {
try {
localStorage.setItem(KEY, JSON.stringify(s))
} catch {}
}
let ctx: AudioContext | null = null
let master: GainNode | null = null
let noise: AudioBuffer | null = null
/** The audio graph, made on first use (browsers only allow it after a click or key). */
function audio(volume: number): { ctx: AudioContext; out: GainNode } | null {
if (typeof window === 'undefined' || !('AudioContext' in window)) return null
if (!ctx) {
ctx = new AudioContext()
master = ctx.createGain()
// A gentle limiter so overlapping sounds never clip.
const comp = ctx.createDynamicsCompressor()
comp.threshold.value = -12
comp.ratio.value = 6
master.connect(comp).connect(ctx.destination)
noise = ctx.createBuffer(1, ctx.sampleRate * 0.2, ctx.sampleRate)
const data = noise.getChannelData(0)
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1
}
if (ctx.state === 'suspended') void ctx.resume()
master!.gain.value = volume * volume * 0.5
return { ctx, out: master! }
}
interface Note {
/** Hz; with `to`, glides there over the note. */
f: number
to?: number
/** Start, seconds from now. */
at?: number
/** Length in seconds. */
len: number
type?: OscillatorType
gain?: number
}
function play(a: { ctx: AudioContext; out: GainNode }, n: Note) {
const t = a.ctx.currentTime + (n.at ?? 0)
const osc = a.ctx.createOscillator()
const env = a.ctx.createGain()
osc.type = n.type ?? 'sine'
osc.frequency.setValueAtTime(n.f, t)
if (n.to) osc.frequency.exponentialRampToValueAtTime(n.to, t + n.len)
const peak = n.gain ?? 0.3
env.gain.setValueAtTime(0.0001, t)
env.gain.exponentialRampToValueAtTime(peak, t + 0.006)
env.gain.exponentialRampToValueAtTime(0.0001, t + n.len)
osc.connect(env).connect(a.out)
osc.start(t)
osc.stop(t + n.len + 0.02)
}
/** A short burst of filtered noise: the mechanical part of a click. */
function click(a: { ctx: AudioContext; out: GainNode }, freq: number, len: number, gain: number, at = 0) {
const t = a.ctx.currentTime + at
const src = a.ctx.createBufferSource()
src.buffer = noise
const bp = a.ctx.createBiquadFilter()
bp.type = 'bandpass'
bp.frequency.value = freq
bp.Q.value = 2.5
const env = a.ctx.createGain()
env.gain.setValueAtTime(gain, t)
env.gain.exponentialRampToValueAtTime(0.0001, t + len)
src.connect(bp).connect(env).connect(a.out)
src.start(t)
src.stop(t + len + 0.02)
}
const NOTE = (semitones: number) => 440 * 2 ** ((semitones - 9) / 12) // 0 = C4
function render(a: { ctx: AudioContext; out: GainNode }, s: Sound) {
switch (s) {
case 'place':
play(a, { f: 260, to: 150, len: 0.09, gain: 0.35 })
click(a, 1800, 0.03, 0.25)
break
case 'connect':
click(a, 3200, 0.02, 0.2)
play(a, { f: NOTE(19), len: 0.06, type: 'triangle', gain: 0.18 })
play(a, { f: NOTE(26), at: 0.045, len: 0.08, type: 'triangle', gain: 0.16 })
break
case 'on':
click(a, 2600, 0.025, 0.35)
play(a, { f: NOTE(24), len: 0.05, type: 'triangle', gain: 0.12 })
break
case 'off':
click(a, 1500, 0.025, 0.3)
play(a, { f: NOTE(17), len: 0.05, type: 'triangle', gain: 0.1 })
break
case 'press':
click(a, 900, 0.04, 0.35)
break
case 'delete':
play(a, { f: 420, to: 160, len: 0.12, type: 'triangle', gain: 0.22 })
click(a, 700, 0.06, 0.15)
break
case 'tick':
click(a, 5200, 0.012, 0.08)
break
case 'error':
play(a, { f: 150, len: 0.09, type: 'square', gain: 0.08 })
play(a, { f: 140, at: 0.1, len: 0.12, type: 'square', gain: 0.08 })
break
case 'fail':
play(a, { f: NOTE(4), len: 0.14, type: 'triangle', gain: 0.25 })
play(a, { f: NOTE(1), at: 0.15, len: 0.28, type: 'triangle', gain: 0.25 })
break
case 'solve':
;[0, 4, 7, 12].forEach((n, i) => play(a, { f: NOTE(12 + n), at: i * 0.075, len: 0.32, type: 'triangle', gain: 0.22 }))
play(a, { f: NOTE(24), at: 0.3, len: 0.6, gain: 0.12 })
break
case 'unlock':
;[0, 7, 12, 16, 19, 24].forEach((n, i) => play(a, { f: NOTE(19 + n), at: 0.35 + i * 0.045, len: 0.25, gain: 0.1 }))
break
case 'record':
;[[7, 0], [12, 0.11], [16, 0.22], [19, 0.33]].forEach(([n, at]) => play(a, { f: NOTE(n!), at, len: 0.3, type: 'square', gain: 0.07 }))
;[0, 4, 7].forEach(n => play(a, { f: NOTE(12 + n), at: 0.45, len: 0.9, type: 'triangle', gain: 0.16 }))
break
}
}
/** Plays a sound if sound is on. Cheap to call often: rapid repeats of the same sound are thinned out. */
const lastAt = new Map<Sound, number>()
export function sfx(s: Sound, settings: SoundSettings) {
if (!settings.on || settings.volume <= 0) return
const now = performance.now()
if (now - (lastAt.get(s) ?? 0) < (s === 'tick' ? 40 : 25)) return
lastAt.set(s, now)
const a = audio(settings.volume)
if (a) render(a, s)
}

View File

@ -5,7 +5,7 @@ import type { Challenge } from './challenges'
import { inputKeys, outputKeys } from './compile'
import { exampleLibrary, starterCircuit } from './examples'
import { chipPins, shapeOf, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, NodeKind, Project, Wire } from './types'
import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types'
export function uid(prefix = ''): string {
return prefix + Math.random().toString(36).slice(2, 10)
@ -21,17 +21,41 @@ export function lookup(project: Project): DefLookup {
return id => map.get(id)
}
export function createProject(opts: { examples: boolean; name?: string }): Project {
export function createProject(opts: { examples: boolean; name?: string; campaign?: boolean }): Project {
const campaign = !!opts.campaign
return {
version: 1,
name: opts.name ?? (opts.examples ? 'NAND to computer' : 'New project'),
components: [starterCircuit(), ...(opts.examples ? exampleLibrary() : [])],
name: opts.name ?? (campaign ? 'Campaign' : opts.examples ? 'NAND to computer' : 'New project'),
components: [starterCircuit(), ...(opts.examples && !campaign ? exampleLibrary() : [])],
openId: 'main',
settings: { symbols: 'iec', flow: true },
solved: [],
...(campaign ? { mode: 'campaign' as const } : {}),
}
}
/** Starts a puzzle: a component with its pins, set up like a challenge. */
export function startPuzzle(project: Project, spec: PuzzleSpec): ComponentDef {
const existing = project.components.find(d => d.challenge === spec.id)
if (existing) return existing
if (!project.puzzles?.some(p => p.id === spec.id)) project.puzzles = [...(project.puzzles ?? []), spec]
const def: ComponentDef = {
id: uid('c'),
name: uniqueName(project, spec.name),
symbol: 'box',
description: spec.goal,
challenge: spec.id,
group: 'Puzzles',
nodes: [
...spec.inputs.map((label, i) => ({ id: uid('n'), kind: 'input' as const, x: 0, y: i * 3, label })),
...spec.outputs.map((label, i) => ({ id: uid('n'), kind: 'output' as const, x: 24, y: i * 3, label })),
],
wires: [],
}
project.components.push(def)
return def
}
/** Adds the example parts that are missing. Returns how many were added. */
export function addExamples(project: Project): number {
const have = new Set(project.components.map(d => d.id))

94
app/lib/logic/progress.ts Normal file
View File

@ -0,0 +1,94 @@
// Campaign: a project where parts are earned. It starts with NAND, inputs,
// outputs and lamps. Each challenge opens once the ones it builds on are
// solved, and your own solution becomes the part you use from then on.
// Basic parts like the clock unlock on the way. Sandbox projects have
// everything from the start.
import { CHALLENGES } from './challenges'
import type { ComponentDef, NodeKind, Project } from './types'
/** Display names of the basic parts. */
export const KIND_NAMES: Partial<Record<NodeKind, string>> = {
nand: 'NAND gate',
input: 'Input switch',
output: 'Output pin',
lamp: 'Lamp',
button: 'Push button',
clock: 'Clock',
high: 'Constant 1',
low: 'Ground (0)',
hex: 'Hex display',
note: 'Note',
panel: 'Input panel',
bundle: 'Cable bundle',
split: 'Cable split',
pixel: 'Pixel',
}
/** Challenges each one builds on. */
export const NEEDS: Record<string, string[]> = {
not: [],
and: ['not'],
or: ['not'],
nor: ['or'],
xor: ['and'],
xnor: ['xor'],
and3: ['and'],
mux: ['and', 'or'],
demux: ['and'],
dec2: ['and'],
ha: ['xor'],
fa: ['ha', 'or'],
eq2: ['xnor'],
add2: ['fa'],
sr: ['not'],
dlatch: ['sr'],
dff: ['dlatch'],
}
/** Basic parts that have to be earned, and the challenge that earns each. */
export const KIND_UNLOCK: Partial<Record<NodeKind, string>> = {
high: 'not',
low: 'not',
panel: 'and',
hex: 'dec2',
pixel: 'dec2',
bundle: 'add2',
split: 'add2',
button: 'sr',
clock: 'dlatch',
}
export const isCampaign = (p: Project) => p.mode === 'campaign'
const solved = (p: Project, id: string) => p.solved.includes(id)
export function kindUnlocked(p: Project, kind: NodeKind): boolean {
const by = KIND_UNLOCK[kind]
return !isCampaign(p) || !by || solved(p, by)
}
/** A challenge can be started once everything it builds on is solved. */
export function challengeOpen(p: Project, id: string): boolean {
return !isCampaign(p) || (NEEDS[id] ?? []).every(n => solved(p, n))
}
/** In a campaign, a challenge's component becomes usable as a part once it is solved. */
export function defUsable(p: Project, def: ComponentDef): boolean {
return !isCampaign(p) || !def.challenge || solved(p, def.challenge)
}
export const challengeName = (id: string) => CHALLENGES.find(c => c.id === id)?.name ?? id
/** What solving a challenge opens up: further challenges and basic parts. */
export function unlockedBy(p: Project, id: string): { challenges: string[]; kinds: NodeKind[] } {
const after = { ...p, solved: [...new Set([...p.solved, id])] }
const challenges = CHALLENGES.filter(c => !solved(p, c.id) && c.id !== id && !challengeOpen(p, c.id) && challengeOpen(after, c.id)).map(c => c.id)
const kinds = (Object.keys(KIND_UNLOCK) as NodeKind[]).filter(k => KIND_UNLOCK[k] === id && !solved(p, id))
return { challenges, kinds }
}
/** Share of the campaign done, 0 to 1. */
export function campaignProgress(p: Project): number {
return CHALLENGES.filter(c => solved(p, c.id)).length / CHALLENGES.length
}

View File

@ -1,7 +1,8 @@
// Reading project data from files, links and storage. Shared by the browser
// and the share-link server, so it must stay free of browser APIs.
import { CROSSING_STYLES, LAMP_COLORS, PANEL_CONTROLS, WIRE_COLORS, type CircuitNode, type PanelRow, type Project } from './types'
import { cleanPuzzle } from './puzzles'
import { CROSSING_STYLES, LAMP_COLORS, PANEL_CONTROLS, WIRE_COLORS, type CircuitNode, type PanelRow, type Project, type PuzzleSpec } from './types'
/** Drops optional node settings that are out of range, so a hand-edited file can't break the editor. */
function cleanNode(n: CircuitNode) {
@ -68,6 +69,8 @@ export function toProject(data: unknown): Project {
},
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}),
...(p.mode === 'campaign' ? { mode: 'campaign' as const } : {}),
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
}
}
@ -79,6 +82,20 @@ function bestOf(raw: unknown): Record<string, number> | null {
return Object.keys(out).length ? out : null
}
/** Puzzles kept in a project; broken ones are dropped. */
function puzzlesOf(raw: unknown): PuzzleSpec[] | null {
if (!Array.isArray(raw)) return null
const out: PuzzleSpec[] = []
for (const p of raw.slice(0, 200)) {
const id = (p as PuzzleSpec)?.id
if (typeof id !== 'string' || !/^(pz|week):[A-Za-z0-9-]{1,32}$/.test(id) || out.some(o => o.id === id)) continue
try {
out.push(cleanPuzzle(p, id))
} catch {}
}
return out.length ? out : null
}
export function parseProject(json: string): Project {
if (json.length > LIMITS.bytes) throw new Error('File too large')
let data: unknown

233
app/lib/logic/puzzles.ts Normal file
View File

@ -0,0 +1,233 @@
// Puzzles: a circuit someone built, turned into a task for others. Only the
// behaviour is published (a list of input settings and the outputs they must
// give), never the circuit. Every week there is also a generated puzzle.
// Shared by the browser and the server, which checks scores itself.
import { nandCounts, stats, TRANSISTORS_PER_NAND, type TestStep } from './analyze'
import { compile } from './compile'
import { chipPins, type DefLookup } from './geometry'
import { Simulator } from './sim'
import type { ComponentDef, PuzzleSpec } from './types'
export const PUZZLE_LIMITS = { inputs: 12, outputs: 16, steps: 4096, label: 24, name: 60, goal: 400 }
/** Gate evaluations allowed per step and per whole check, so a check always ends quickly. */
const STEP_BUDGET = 200_000
const TOTAL_BUDGET = 20_000_000
/** Small fast seeded random numbers (mulberry32). */
export function rng(seed: number) {
let a = seed >>> 0
return () => {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
const hash = (s: string) => [...s].reduce((h, c) => (Math.imul(h, 31) + c.charCodeAt(0)) | 0, 7)
/**
* The steps that describe a circuit: every input combination when it has no
* memory, otherwise a fixed run of random input changes from power-on.
* Throws with a readable reason when the circuit can't be a puzzle.
*/
export function describeCircuit(get: DefLookup, defId: string): { inputs: string[]; outputs: string[]; steps: TestStep[]; sequential: boolean } {
const def = get(defId)
if (!def) throw new Error('Circuit not found')
const pins = chipPins(def)
if (!pins.inputs.length) throw new Error('Add at least one input')
if (!pins.outputs.length) throw new Error('Add at least one output')
if (pins.inputs.length > PUZZLE_LIMITS.inputs) throw new Error(`At most ${PUZZLE_LIMITS.inputs} inputs`)
if (pins.outputs.length > PUZZLE_LIMITS.outputs) throw new Error(`At most ${PUZZLE_LIMITS.outputs} outputs`)
const labels = [...pins.inputs, ...pins.outputs].map(p => p.label)
if (new Set(labels.map(l => l.toLowerCase())).size !== labels.length) throw new Error('Give every input and output its own name')
if (labels.some(l => l.length > PUZZLE_LIMITS.label)) throw new Error(`Pin names can have at most ${PUZZLE_LIMITS.label} characters`)
const nl = compile(get, defId)
if (nl.clocks.length) throw new Error('Use an input instead of a clock, so the steps can drive it')
const sequential = stats(nl).sequential
const sim = new Simulator(nl)
sim.run(STEP_BUDGET)
const n = pins.inputs.length
const patterns: number[][] = []
if (!sequential && n <= 10) {
for (let i = 0; i < 1 << n; i++) patterns.push(pins.inputs.map((_, k) => (i >> (n - 1 - k)) & 1))
} else {
// Change one input at a time, so latches and edges get exercised.
const r = rng(hash(def.name) ^ n)
const cur = pins.inputs.map(() => 0)
patterns.push([...cur])
for (let i = 0; i < Math.min(PUZZLE_LIMITS.steps - 1, 32 * n + 32); i++) {
cur[Math.floor(r() * n)]! ^= 1
patterns.push([...cur])
}
}
const steps: TestStep[] = []
for (const ins of patterns) {
pins.inputs.forEach((p, k) => sim.setSource(p.key, ins[k] === 1))
if (!sim.run(STEP_BUDGET)) throw new Error('The circuit keeps oscillating, so it has no clear answer')
steps.push({
set: Object.fromEntries(pins.inputs.map((p, k) => [p.label, ins[k]!])),
expect: Object.fromEntries(pins.outputs.map(p => [p.label, sim.pin(p.key, 'a')])),
})
}
return { inputs: pins.inputs.map(p => p.label), outputs: pins.outputs.map(p => p.label), steps, sequential }
}
/** A puzzle from one of your circuits. */
export function makePuzzle(components: ComponentDef[], defId: string, name: string, goal: string): Omit<PuzzleSpec, 'id'> {
const get = (id: string) => components.find(d => d.id === id)
const d = describeCircuit(get, defId)
return {
name: name.trim().slice(0, PUZZLE_LIMITS.name) || 'Puzzle',
goal: goal.trim().slice(0, PUZZLE_LIMITS.goal) || (d.sequential ? 'Match the outputs step by step, from power-on.' : 'Match the truth table.'),
inputs: d.inputs,
outputs: d.outputs,
steps: d.steps,
author: (nandCounts(components).get(defId) ?? 0) * TRANSISTORS_PER_NAND,
}
}
/** Checks puzzle data from outside. Returns a clean copy, or throws. */
export function cleanPuzzle(raw: unknown, id: string): PuzzleSpec {
const p = raw as Partial<PuzzleSpec>
const fail = (why: string): never => {
throw new Error(`Not a valid puzzle: ${why}`)
}
if (!p || typeof p !== 'object') fail('no data')
const labels = (v: unknown, max: number) => {
if (!Array.isArray(v) || !v.length || v.length > max) fail('pins')
const list = (v as unknown[]).map(l => (typeof l === 'string' ? l.trim() : ''))
if (list.some(l => !l || l.length > PUZZLE_LIMITS.label)) fail('pin names')
return list
}
const inputs = labels(p.inputs, PUZZLE_LIMITS.inputs)
const outputs = labels(p.outputs, PUZZLE_LIMITS.outputs)
if (new Set([...inputs, ...outputs].map(l => l.toLowerCase())).size !== inputs.length + outputs.length) fail('pin names repeat')
if (!Array.isArray(p.steps) || !p.steps.length || p.steps.length > PUZZLE_LIMITS.steps) fail('steps')
const bit = (v: unknown) => (v === 0 || v === 1 ? v : fail('values must be 0 or 1'))
const steps = p.steps!.map(s => ({
set: Object.fromEntries(inputs.filter(l => s?.set && l in s.set).map(l => [l, bit(s.set[l])])),
expect: Object.fromEntries(outputs.filter(l => s?.expect && l in s.expect).map(l => [l, bit(s.expect[l])])),
}))
return {
id,
name: typeof p.name === 'string' && p.name.trim() ? p.name.trim().slice(0, PUZZLE_LIMITS.name) : 'Puzzle',
goal: typeof p.goal === 'string' ? p.goal.trim().slice(0, PUZZLE_LIMITS.goal) : '',
inputs,
outputs,
steps,
...(typeof p.author === 'number' && Number.isInteger(p.author) && p.author >= 0 ? { author: p.author } : {}),
}
}
export interface PuzzleScore {
pass: boolean
message: string
transistors: number
/** Longest gate path; null with feedback loops. */
delay: number | null
}
/** Runs a solution against a puzzle within a fixed amount of work. */
export function scoreSolution(components: ComponentDef[], defId: string, spec: PuzzleSpec): PuzzleScore {
const get = (id: string) => components.find(d => d.id === id)
const def = get(defId)
const transistors = (nandCounts(components).get(defId) ?? 0) * TRANSISTORS_PER_NAND
const out = (pass: boolean, message: string, delay: number | null = null): PuzzleScore => ({ pass, message, transistors, delay })
if (!def) return out(false, 'Circuit not found')
const pins = chipPins(def)
const find = (list: { key: string; label: string }[], label: string) => list.find(p => p.label.toLowerCase() === label.toLowerCase())
for (const l of spec.inputs) if (!find(pins.inputs, l)) return out(false, `Missing input pin "${l}"`)
for (const l of spec.outputs) if (!find(pins.outputs, l)) return out(false, `Missing output pin "${l}"`)
const nl = compile(get, defId)
if (nl.errors.length) return out(false, nl.errors[0]!)
const delay = stats(nl).delay
const sim = new Simulator(nl)
let left = TOTAL_BUDGET
const settle = () => {
let ok = false
for (let k = 0; k < STEP_BUDGET && left > 0; k += 20_000) {
left -= 20_000
if ((ok = sim.run(20_000))) break
}
return ok
}
settle()
for (let i = 0; i < spec.steps.length; i++) {
const step = spec.steps[i]!
for (const [l, v] of Object.entries(step.set)) sim.setSource(find(pins.inputs, l)!.key, v === 1)
if (!settle()) return out(false, left <= 0 ? 'The circuit takes too long to settle' : 'The circuit oscillates and never settles', delay)
for (const [l, want] of Object.entries(step.expect)) {
const got = sim.pin(find(pins.outputs, l)!.key, 'a')
if (got !== want) {
const ins = Object.entries(step.set).map(([k, v]) => `${k}=${v}`).join(' ')
return out(false, `${spec.steps.length > 1 << spec.inputs.length ? `Step ${i + 1}: with` : 'With'} ${ins}: ${l} is ${got}, expected ${want}`, delay)
}
}
}
return out(true, `All ${spec.steps.length} checks pass`, delay)
}
// ── Puzzle of the week ──────────────────────────────────────────────
/** ISO week of a date, like "2026-43". */
export function weekKey(date = new Date()): string {
const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()))
const day = d.getUTCDay() || 7
d.setUTCDate(d.getUTCDate() + 4 - day)
const year = d.getUTCFullYear()
const week = Math.ceil(((d.getTime() - Date.UTC(year, 0, 1)) / 86_400_000 + 1) / 7)
return `${year}-${String(week).padStart(2, '0')}`
}
export const weeklyId = (key: string) => `week:${key}`
export const isWeekKey = (key: string) => /^\d{4}-\d{2}$/.test(key)
/**
* The generated puzzle of a week: a random logic function of three or four
* inputs with one or two outputs. Each output depends on every input, so
* there is no shortcut through a single wire.
*/
export function weeklyPuzzle(key: string): PuzzleSpec {
const r = rng(hash(`logigate-week-${key}`))
const n = r() < 0.5 ? 3 : 4
const m = n === 3 ? 2 : r() < 0.5 ? 1 : 2
const inputs = ['A', 'B', 'C', 'D'].slice(0, n)
const outputs = m === 1 ? ['Q'] : ['X', 'Y']
const rows = 1 << n
const dependsOnAll = (t: number[]) => inputs.every((_, k) => t.some((v, i) => v !== t[i ^ (1 << (n - 1 - k))]))
const tables: number[][] = []
while (tables.length < m) {
const t = Array.from({ length: rows }, () => (r() < 0.5 ? 1 : 0))
if (dependsOnAll(t) && !tables.some(o => o.join() === t.join())) tables.push(t)
}
const steps: TestStep[] = []
for (let i = 0; i < rows; i++) {
steps.push({
set: Object.fromEntries(inputs.map((l, k) => [l, (i >> (n - 1 - k)) & 1])),
expect: Object.fromEntries(outputs.map((l, k) => [l, tables[k]![i]!])),
})
}
return {
id: weeklyId(key),
name: `Puzzle of week ${key.slice(5)}`,
goal: `Build the circuit from the table with as few transistors as you can. Everyone gets the same puzzle this week (${key}).`,
inputs,
outputs,
steps,
}
}
/** True when the steps are exactly one per input combination, so they read as a truth table. */
export function isTable(spec: PuzzleSpec): boolean {
return spec.steps.length === 1 << spec.inputs.length && spec.steps.every(s => Object.keys(s.set).length === spec.inputs.length)
}
/** Path segment of a puzzle in the API and links: "pz:abc" → "abc", "week:2026-43" → "week-2026-43". */
export function apiId(specId: string): string {
return specId.startsWith('pz:') ? specId.slice(3) : specId.replace(':', '-')
}

View File

@ -135,4 +135,22 @@ export interface Project {
solved: string[]
/** Fewest transistors a passing solution used, per challenge id. */
best?: Record<string, number>
/** "campaign": parts are earned by solving challenges. Default: sandbox, everything available. */
mode?: 'campaign'
/** Puzzles opened from links or the weekly puzzle; their components carry `challenge: <puzzle id>`. */
puzzles?: PuzzleSpec[]
}
/** A puzzle someone published: what to build, without their solution. */
export interface PuzzleSpec {
/** "pz:<link id>" for published puzzles, "week:<yyyy-ww>" for the weekly one. */
id: string
name: string
goal: string
inputs: string[]
outputs: string[]
/** Set inputs, let it settle, check outputs; in order, from power-on. */
steps: { set: Record<string, number>; expect: Record<string, number> }[]
/** Transistors in the author's own solution. */
author?: number
}

10
app/pages/puzzle/[id].vue Normal file
View File

@ -0,0 +1,10 @@
<script setup lang="ts">
// A puzzle link: /puzzle/<id> adds that puzzle to the open project and opens it.
const route = useRoute()
const ed = useEditor()
onMounted(() => ed.openPuzzle(String(route.params.id)))
</script>
<template>
<EditorApp />
</template>

View File

@ -0,0 +1,11 @@
// A puzzle and how everyone did on it. "weekly" is this week's puzzle.
import { weekKey } from '../../../app/lib/logic/puzzles'
export default defineEventHandler(async event => {
let id = getRouterParam(event, 'id')
if (id === 'weekly') id = `week-${weekKey()}`
const spec = await findPuzzle(id)
if (!spec) throw createError({ statusCode: 404, message: 'Puzzle not found' })
setHeader(event, 'cache-control', 'no-store')
return { id, spec, summary: summarize(await board(id!), playerParam(event)) }
})

View File

@ -0,0 +1,42 @@
// Submit a solution. The server runs the puzzle's checks on it and counts
// its transistors itself, so a score can't be made up. Each player keeps
// their best: fewer transistors, then shorter delay.
import { toProject } from '../../../../app/lib/logic/project'
import { scoreSolution } from '../../../../app/lib/logic/puzzles'
export default defineEventHandler(async event => {
rateLimit(event, 'score', 60, 10 * 60_000)
const id = getRouterParam(event, 'id')
const spec = await findPuzzle(id)
if (!spec || !id) throw createError({ statusCode: 404, message: 'Puzzle not found' })
const raw = await readRawBody(event, 'utf8')
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
if (raw.length > 2_000_000) throw createError({ statusCode: 413, message: 'Solution too large' })
let body: { player?: unknown; defId?: unknown; components?: unknown }
try {
body = JSON.parse(raw)
} catch {
throw createError({ statusCode: 400, message: 'Not valid JSON' })
}
if (!isPlayer(body.player) || typeof body.defId !== 'string') throw createError({ statusCode: 400, message: 'Missing player or circuit' })
let components
try {
components = toProject({ components: body.components, name: 'solution' }).components
} catch (e) {
throw createError({ statusCode: 400, message: (e as Error).message })
}
const score = scoreSolution(components, body.defId, spec)
if (!score.pass) return { score, summary: summarize(await board(id), body.player) }
const player = body.player
const summary = await locked(id, async () => {
const scores = await board(id)
const old = scores[player]
const better = !old || score.transistors < old.t || (score.transistors === old.t && (score.delay ?? Infinity) < (old.d ?? Infinity))
if (better) {
scores[player] = { t: score.transistors, d: score.delay, at: Date.now() }
await puzzleStorage().setItem(`scores:${id}`, scores)
}
return summarize(scores, player)
})
return { score, summary }
})

View File

@ -0,0 +1,22 @@
// Publish a puzzle. The body carries only its behaviour, never a circuit.
import { cleanPuzzle } from '../../../app/lib/logic/puzzles'
export default defineEventHandler(async event => {
rateLimit(event, 'puzzle', 20, 10 * 60_000)
const raw = await readRawBody(event, 'utf8')
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
if (raw.length > 1_000_000) throw createError({ statusCode: 413, message: 'Puzzle too large' })
let spec
try {
spec = cleanPuzzle((JSON.parse(raw) as { puzzle?: unknown }).puzzle, '')
} catch (e) {
throw createError({ statusCode: 400, message: (e as Error).message })
}
const storage = puzzleStorage()
let id = newShareId()
while (await storage.hasItem(`specs:${id}`)) id = newShareId()
spec.id = `pz:${id}`
await storage.setItem(`specs:${id}`, { spec, created: Date.now() })
setResponseStatus(event, 201)
return { id }
})

View File

@ -4,7 +4,7 @@ import { join, resolve } from 'node:path'
export default defineNitroPlugin(() => {
const root = resolve(process.cwd(), 'data')
const storage = useStorage()
for (const name of ['shares', 'users', 'sessions', 'accounts']) {
for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles']) {
storage.mount(name, safeFsDriver({ base: join(root, name) }))
}
void removeStaleTemp(root)

74
server/utils/puzzles.ts Normal file
View File

@ -0,0 +1,74 @@
// Published puzzles and their scores, as JSON files under data/puzzles:
// specs:<id> holds the puzzle, scores:<id> the best score of each player.
// The puzzle of the week is generated, so only its scores are stored.
import type { H3Event } from 'h3'
import { cleanPuzzle, isWeekKey, weekKey, weeklyPuzzle } from '../../app/lib/logic/puzzles'
import type { PuzzleSpec } from '../../app/lib/logic/types'
export interface PuzzleRecord {
spec: PuzzleSpec
created: number
}
export interface Entry {
t: number
d: number | null
at: number
}
export type ScoreBoard = Record<string, Entry>
export const puzzleStorage = () => useStorage('puzzles')
export const isPlayer = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{8,40}$/.test(v)
/** The puzzle behind an API id: a link id, or "week-2026-43" for a weekly one up to this week. */
export async function findPuzzle(id: string | undefined): Promise<PuzzleSpec | null> {
if (!id) return null
const week = /^week-(\d{4}-\d{2})$/.exec(id)?.[1]
if (week) return isWeekKey(week) && week <= weekKey() ? weeklyPuzzle(week) : null
if (!isShareId(id)) return null
const rec = await puzzleStorage().getItem<PuzzleRecord>(`specs:${id}`)
return rec ? cleanPuzzle(rec.spec, `pz:${id}`) : null
}
/** One write at a time per puzzle, so two scores arriving together both count. */
const queues = new Map<string, Promise<unknown>>()
export function locked<T>(key: string, fn: () => Promise<T>): Promise<T> {
const prev = queues.get(key) ?? Promise.resolve()
const next = prev.then(fn, fn)
queues.set(
key,
next.catch(() => {}),
)
return next
}
export interface Summary {
players: number
/** Transistor counts and how many players have each, fewest first. */
histogram: { t: number; n: number }[]
/** This player's best and place (1 = best), when they have a score. */
you?: { t: number; d: number | null; rank: number }
}
export function summarize(board: ScoreBoard, player?: string): Summary {
const entries = Object.values(board)
const counts = new Map<number, number>()
for (const e of entries) counts.set(e.t, (counts.get(e.t) ?? 0) + 1)
const histogram = [...counts.entries()].sort((a, b) => a[0] - b[0]).map(([t, n]) => ({ t, n }))
const mine = player ? board[player] : undefined
const summary: Summary = { players: entries.length, histogram }
if (mine) summary.you = { t: mine.t, d: mine.d, rank: 1 + entries.filter(e => e.t < mine.t).length }
return summary
}
export async function board(id: string): Promise<ScoreBoard> {
return (await puzzleStorage().getItem<ScoreBoard>(`scores:${id}`)) ?? {}
}
export function playerParam(event: H3Event): string | undefined {
const p = getQuery(event).player
return isPlayer(p) ? p : undefined
}

194
tests/game.test.ts Normal file
View File

@ -0,0 +1,194 @@
import { describe, expect, it } from 'vitest'
import { CHALLENGES } from '../app/lib/logic/challenges'
import { createProject, startPuzzle } from '../app/lib/logic/ops'
import { challengeOpen, defUsable, kindUnlocked, NEEDS, unlockedBy } from '../app/lib/logic/progress'
import { toProject } from '../app/lib/logic/project'
import { cleanPuzzle, describeCircuit, isTable, makePuzzle, scoreSolution, weekKey, weeklyPuzzle } from '../app/lib/logic/puzzles'
import type { ComponentDef } from '../app/lib/logic/types'
/** XOR from four NANDs. */
function xor(id = 'x'): ComponentDef {
return {
id,
name: 'My XOR',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'b', kind: 'input', x: 0, y: 4, label: 'B' },
{ id: 'n1', kind: 'nand', x: 4, y: 2 },
{ id: 'n2', kind: 'nand', x: 8, y: 0 },
{ id: 'n3', kind: 'nand', x: 8, y: 4 },
{ id: 'n4', kind: 'nand', x: 12, y: 2 },
{ id: 'q', kind: 'output', x: 16, y: 2, label: 'Q' },
],
wires: [
{ id: 'w1', from: { node: 'a', pin: 'q' }, to: { node: 'n1', pin: 'a' } },
{ id: 'w2', from: { node: 'b', pin: 'q' }, to: { node: 'n1', pin: 'b' } },
{ id: 'w3', from: { node: 'a', pin: 'q' }, to: { node: 'n2', pin: 'a' } },
{ id: 'w4', from: { node: 'n1', pin: 'q' }, to: { node: 'n2', pin: 'b' } },
{ id: 'w5', from: { node: 'n1', pin: 'q' }, to: { node: 'n3', pin: 'a' } },
{ id: 'w6', from: { node: 'b', pin: 'q' }, to: { node: 'n3', pin: 'b' } },
{ id: 'w7', from: { node: 'n2', pin: 'q' }, to: { node: 'n4', pin: 'a' } },
{ id: 'w8', from: { node: 'n3', pin: 'q' }, to: { node: 'n4', pin: 'b' } },
{ id: 'w9', from: { node: 'n4', pin: 'q' }, to: { node: 'q', pin: 'a' } },
],
}
}
describe('campaign', () => {
it('starts with NAND and earns the rest', () => {
const p = createProject({ examples: true, campaign: true })
expect(p.mode).toBe('campaign')
expect(p.components).toHaveLength(1)
expect(kindUnlocked(p, 'nand')).toBe(true)
expect(kindUnlocked(p, 'clock')).toBe(false)
expect(challengeOpen(p, 'not')).toBe(true)
expect(challengeOpen(p, 'and')).toBe(false)
expect(unlockedBy(p, 'not')).toEqual({ challenges: ['and', 'or', 'sr'], kinds: ['high', 'low'] })
p.solved.push('not')
expect(challengeOpen(p, 'and')).toBe(true)
expect(kindUnlocked(p, 'high')).toBe(true)
})
it('a challenge component becomes a part once solved, and sandbox projects have everything', () => {
const p = createProject({ examples: false, campaign: true })
const def: ComponentDef = { ...xor(), challenge: 'xor' }
expect(defUsable(p, def)).toBe(false)
p.solved.push('xor')
expect(defUsable(p, def)).toBe(true)
const sandbox = createProject({ examples: false })
expect(kindUnlocked(sandbox, 'clock') && challengeOpen(sandbox, 'dff') && defUsable(sandbox, { ...def, challenge: 'dff' })).toBe(true)
})
it('every challenge can be reached, and the chain has no loops', () => {
for (const c of CHALLENGES) expect(NEEDS[c.id], c.id).toBeDefined()
const p = createProject({ examples: false, campaign: true })
for (let round = 0; round < CHALLENGES.length; round++) {
for (const c of CHALLENGES) if (challengeOpen(p, c.id) && !p.solved.includes(c.id)) p.solved.push(c.id)
}
expect(p.solved).toHaveLength(CHALLENGES.length)
})
it('keeps the mode through validation', () => {
const p = createProject({ examples: false, campaign: true })
expect(toProject(JSON.parse(JSON.stringify(p))).mode).toBe('campaign')
expect(toProject({ ...JSON.parse(JSON.stringify(p)), mode: 'cheat' }).mode).toBeUndefined()
})
})
describe('puzzles', () => {
it('describes a circuit by its truth table, without the circuit', () => {
const spec = makePuzzle([xor()], 'x', 'Odd one', '')
expect(spec.inputs).toEqual(['A', 'B'])
expect(spec.steps.map(s => s.expect.Q)).toEqual([0, 1, 1, 0])
expect(spec.author).toBe(16)
expect(JSON.stringify(spec)).not.toContain('nand')
expect(isTable({ ...spec, id: 'pz:x' })).toBe(true)
})
it('a different circuit with the same behaviour passes, and is scored by its own transistors', () => {
const spec = { ...makePuzzle([xor()], 'x', 'XOR', ''), id: 'pz:abc' }
const mine = xor('y')
// Add a useless gate: still correct, but costs 4 more.
mine.nodes.push({ id: 'extra', kind: 'nand', x: 20, y: 9 })
const score = scoreSolution([mine], 'y', spec)
expect(score.pass).toBe(true)
expect(score.transistors).toBe(20)
expect(score.delay).toBe(3)
})
it('a wrong circuit fails with the step that shows it', () => {
const spec = { ...makePuzzle([xor()], 'x', 'XOR', ''), id: 'pz:abc' }
const wrong = xor('w')
wrong.wires = wrong.wires.filter(w => w.id !== 'w8')
const score = scoreSolution([wrong], 'w', spec)
expect(score.pass).toBe(false)
expect(score.message).toMatch(/Q is \d, expected \d/)
const renamed = xor('r')
renamed.nodes.find(n => n.id === 'q')!.label = 'Out'
expect(scoreSolution([renamed], 'r', spec).message).toBe('Missing output pin "Q"')
})
it('a circuit with memory becomes a run of steps from power-on', () => {
// SR latch from two NANDs with active-low inputs.
const latch: ComponentDef = {
id: 'l',
name: 'Latch',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: 0, y: 0, label: 'S' },
{ id: 'r', kind: 'input', x: 0, y: 4, label: 'R' },
{ id: 'n1', kind: 'nand', x: 5, y: 0 },
{ id: 'n2', kind: 'nand', x: 5, y: 4 },
{ id: 'q', kind: 'output', x: 12, y: 0, label: 'Q' },
],
wires: [
{ id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'n1', pin: 'a' } },
{ id: 'w2', from: { node: 'n2', pin: 'q' }, to: { node: 'n1', pin: 'b' } },
{ id: 'w3', from: { node: 'r', pin: 'q' }, to: { node: 'n2', pin: 'b' } },
{ id: 'w4', from: { node: 'n1', pin: 'q' }, to: { node: 'n2', pin: 'a' } },
{ id: 'w5', from: { node: 'n1', pin: 'q' }, to: { node: 'q', pin: 'a' } },
],
}
const d = describeCircuit(id => (id === 'l' ? latch : undefined), 'l')
expect(d.sequential).toBe(true)
expect(d.steps.length).toBeGreaterThan(4)
const spec = { ...makePuzzle([latch], 'l', 'Latch', ''), id: 'pz:latch' }
expect(isTable(spec)).toBe(false)
expect(scoreSolution([{ ...latch, id: 'm' }], 'm', spec).pass).toBe(true)
})
it('refuses circuits that cannot be puzzles', () => {
const noOut = xor()
noOut.nodes = noOut.nodes.filter(n => n.kind !== 'output')
expect(() => makePuzzle([noOut], 'x', 'P', '')).toThrow('Add at least one output')
const twins = xor()
twins.nodes.find(n => n.id === 'b')!.label = 'a'
expect(() => makePuzzle([twins], 'x', 'P', '')).toThrow('its own name')
})
it('cleans puzzle data from outside', () => {
const spec = makePuzzle([xor()], 'x', 'XOR', 'Hello')
expect(cleanPuzzle(JSON.parse(JSON.stringify(spec)), 'pz:a').steps).toEqual(spec.steps)
expect(() => cleanPuzzle({ ...spec, steps: [{ set: { A: 2 }, expect: {} }] }, 'pz:a')).toThrow()
expect(() => cleanPuzzle({ ...spec, inputs: ['A', 'A'] }, 'pz:a')).toThrow()
expect(() => cleanPuzzle(null, 'pz:a')).toThrow()
})
it('a project keeps its puzzles and their components', () => {
const p = createProject({ examples: false })
const spec = { ...makePuzzle([xor()], 'x', 'XOR', ''), id: 'pz:abc12345' }
const def = startPuzzle(p, spec)
expect(def.challenge).toBe('pz:abc12345')
expect(startPuzzle(p, spec)).toBe(def)
const back = toProject(JSON.parse(JSON.stringify(p)))
expect(back.puzzles?.map(x => x.id)).toEqual(['pz:abc12345'])
expect(toProject({ ...JSON.parse(JSON.stringify(p)), puzzles: [{ ...spec, id: 'evil id' }] }).puzzles).toBeUndefined()
})
})
describe('puzzle of the week', () => {
it('is the same for everyone in a week and changes between weeks', () => {
expect(weeklyPuzzle('2026-43')).toEqual(weeklyPuzzle('2026-43'))
const names = new Set(['2026-40', '2026-41', '2026-42', '2026-43'].map(k => JSON.stringify(weeklyPuzzle(k).steps)))
expect(names.size).toBe(4)
})
it('has outputs that depend on every input', () => {
for (let w = 1; w <= 30; w++) {
const spec = weeklyPuzzle(`2027-${String(w).padStart(2, '0')}`)
expect(isTable(spec)).toBe(true)
const n = spec.inputs.length
for (const out of spec.outputs) {
const t = spec.steps.map(s => s.expect[out])
for (let k = 0; k < n; k++) expect(t.some((v, i) => v !== t[i ^ (1 << (n - 1 - k))]), `${spec.id} ${out} ${spec.inputs[k]}`).toBe(true)
}
}
})
it('counts ISO weeks', () => {
expect(weekKey(new Date('2026-10-20T12:00:00Z'))).toBe('2026-43')
expect(weekKey(new Date('2027-01-01T12:00:00Z'))).toBe('2026-53')
expect(weekKey(new Date('2027-01-04T12:00:00Z'))).toBe('2027-01')
})
})