A main menu: free play, campaign, challenges and leaderboard over a circuit that builds itself

Logigate opens on a title screen. Continue, Free play (your own projects),
Campaign (progress and what is next), Challenges (every challenge and the
puzzle of the week in one Challenges project), Leaderboard (the best ten of
this and earlier weeks, your place, your records), Settings. Arrow keys,
Enter and Esc work through it; links still open straight into the editor.
Players can name themselves on the leaderboards. The logo in the editor
leads back to the menu.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-22 12:22:35 +02:00
parent 794acad140
commit 9411527c5d
21 changed files with 1579 additions and 143 deletions

View File

@ -2220,7 +2220,8 @@ kbd {
border-color: rgb(76 194 255 / 0.35);
}
.campaign .bar {
.campaign .bar,
.menu-card .bar {
height: 6px;
margin-top: 8px;
border-radius: 3px;
@ -2228,7 +2229,8 @@ kbd {
overflow: hidden;
}
.campaign .bar span {
.campaign .bar span,
.menu-card .bar span {
display: block;
height: 100%;
background: var(--on);
@ -3377,3 +3379,443 @@ kbd {
.quick-add .item {
cursor: pointer;
}
/* ── Title screen ───────────────────────────────────────────────── */
.brand {
padding: 4px 8px 4px 4px;
border-radius: 6px;
}
.brand:hover {
background: var(--panel-2);
}
.title-screen {
position: fixed;
inset: 0;
overflow: hidden;
background: #0b0f14;
}
.menu-bg {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
.title-shade {
position: absolute;
inset: 0;
pointer-events: none;
background:
radial-gradient(ellipse at 65% 50%, transparent 35%, rgb(5 8 12 / 0.7) 100%),
linear-gradient(90deg, rgb(8 11 16 / 0.94) 0%, rgb(8 11 16 / 0.72) 32%, rgb(8 11 16 / 0) 62%);
}
.title-layout {
position: relative;
display: flex;
gap: 40px;
height: 100%;
padding: clamp(24px, 7vh, 80px) clamp(16px, 6vw, 96px);
}
.title-side {
display: flex;
flex-direction: column;
flex-shrink: 0;
width: min(380px, 100%);
min-height: 0;
}
.title-logo {
display: flex;
align-items: center;
gap: 14px;
color: var(--on);
}
.title-logo svg {
width: 52px;
height: 52px;
filter: drop-shadow(0 0 12px rgb(61 220 132 / 0.5));
}
.title-logo h1 {
font-size: clamp(38px, 5vw, 56px);
font-weight: 800;
line-height: 1;
letter-spacing: -0.03em;
color: var(--text);
}
.title-tag {
margin-top: 10px;
font-size: 15px;
color: var(--muted);
}
.title-nav {
display: flex;
flex-direction: column;
gap: 4px;
margin-top: clamp(24px, 6vh, 56px);
}
.title-item {
display: flex;
align-items: center;
gap: 14px;
width: 100%;
padding: 11px 16px;
border: 1px solid transparent;
border-radius: 10px;
text-align: left;
color: var(--text);
transition:
background 0.15s,
border-color 0.15s;
}
.title-item .label {
display: block;
font-size: 17px;
font-weight: 650;
}
.title-item .sub {
display: block;
margin-top: 1px;
font-size: 12px;
color: var(--muted);
}
.title-item .chev {
color: var(--muted);
opacity: 0;
transition:
opacity 0.15s,
transform 0.15s;
}
.title-item:hover,
.title-item:focus-visible,
.title-item.active {
background: rgb(26 33 43 / 0.85);
border-color: var(--border);
outline: none;
}
.title-item:focus-visible {
border-color: var(--accent);
}
.title-item:hover .chev,
.title-item:focus-visible .chev,
.title-item.active .chev {
opacity: 1;
transform: translateX(3px);
}
.title-item.active {
box-shadow: inset 3px 0 0 var(--on);
}
.title-item.primary > svg {
color: var(--on);
}
.title-foot {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
margin-top: auto;
padding-top: 20px;
}
.title-link {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 4px 0;
font-size: 13px;
color: var(--muted);
}
.title-link:hover {
color: var(--text);
}
.title-page {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
max-width: 780px;
overflow: hidden;
background: rgb(19 24 31 / 0.9);
backdrop-filter: blur(8px);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 30px 80px rgb(0 0 0 / 0.5);
}
.title-page > header {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
border-bottom: 1px solid var(--border);
}
.title-page h2 {
font-size: 20px;
font-weight: 700;
letter-spacing: -0.01em;
}
.title-page h3 {
margin: 18px 0 8px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted);
}
.title-page-body {
flex: 1;
overflow-y: auto;
padding: 16px 22px 24px;
}
.title-page-enter-active,
.title-page-leave-active {
transition:
opacity 0.18s,
transform 0.18s;
}
.title-page-enter-from,
.title-page-leave-to {
opacity: 0;
transform: translateX(16px);
}
@media (max-width: 860px) {
.title-layout.open .title-side {
display: none;
}
.title-page {
max-width: none;
}
}
@media (prefers-reduced-motion: reduce) {
.title-page-enter-active,
.title-page-leave-active {
transition: none;
}
}
.menu-card {
margin-top: 12px;
padding: 14px 16px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--panel-2);
}
.menu-card p {
font-size: 13px;
line-height: 1.45;
color: var(--muted);
}
.menu-card p strong {
color: var(--text);
}
.weekly-card {
margin-top: 0;
border-color: rgb(76 194 255 / 0.35);
}
.menu-steps {
display: grid;
gap: 2px;
margin-top: 14px;
}
.menu-steps li {
display: flex;
align-items: center;
gap: 10px;
padding: 7px 10px;
border-radius: 8px;
font-size: 13px;
}
.menu-steps li > svg {
color: var(--muted);
}
.menu-steps li.solved > svg {
color: var(--on);
}
.menu-steps li.locked {
opacity: 0.5;
}
.menu-steps li.next {
background: rgb(61 220 132 / 0.08);
box-shadow: inset 0 0 0 1px rgb(61 220 132 / 0.3);
}
.menu-steps .unlocks {
font-size: 12px;
color: var(--muted);
}
.menu-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 8px;
margin-top: 10px;
}
.menu-tile {
display: flex;
flex-direction: column;
gap: 6px;
width: 100%;
height: 100%;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--panel-2);
text-align: left;
transition:
border-color 0.15s,
transform 0.15s;
}
.menu-tile:hover,
.menu-tile:focus-visible {
border-color: var(--accent);
outline: none;
transform: translateY(-1px);
}
.menu-grid li.solved .menu-tile {
border-color: rgb(61 220 132 / 0.3);
}
.menu-tile .goal {
font-size: 12px;
line-height: 1.4;
color: var(--muted);
}
.menu-tile .pins {
margin-top: auto;
font-family: var(--font-mono);
font-size: 11px;
color: var(--muted);
}
.menu-board .name-row {
display: flex;
align-items: flex-end;
gap: 8px;
}
.board-tabs {
margin-top: 16px;
overflow-x: auto;
}
.board-tabs button {
flex: none;
padding: 0 12px;
}
table.board {
width: 100%;
margin-top: 12px;
border-collapse: collapse;
font-size: 13px;
}
.board th {
padding: 6px 8px;
border-bottom: 1px solid var(--border);
font-size: 11px;
font-weight: 600;
text-align: left;
color: var(--muted);
}
.board td {
padding: 7px 8px;
border-bottom: 1px solid rgb(37 46 58 / 0.5);
}
.board .num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.board .rank {
width: 32px;
font-variant-numeric: tabular-nums;
color: var(--muted);
}
.board tbody tr:first-child .rank {
color: var(--lamp);
font-weight: 700;
}
.board tr.you td {
background: rgb(61 220 132 / 0.08);
}
.board tr.gap td {
border-top: 2px dashed var(--border);
}
.you-tag {
margin-left: 8px;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
color: var(--on);
}
.records {
display: grid;
gap: 2px;
}
.records li {
display: flex;
justify-content: space-between;
padding: 6px 10px;
border-radius: 6px;
font-size: 13px;
}
.records li:nth-child(odd) {
background: rgb(26 33 43 / 0.6);
}
.menu-board .name-row .field {
margin-bottom: 0;
}

View File

@ -17,14 +17,24 @@ onMounted(() => {
const stop = ed.startLoop()
onBeforeUnmount(stop)
void ed.startAccount()
try {
if (!localStorage.getItem('logigate:help-seen')) ed.showHelp.value = true
} catch {}
})
// The first time into the editor, the help explains the basics.
watch(
ed.screen,
s => {
try {
if (s === 'editor' && !localStorage.getItem('logigate:help-seen')) ed.showHelp.value = true
} catch {}
},
{ immediate: true },
)
</script>
<template>
<div class="app">
<EditorMainMenu v-if="ed.screen.value === 'menu'" />
<template v-else>
<EditorToolbar />
<div class="workspace" :class="{ 'no-left': !ed.sidebars.left, 'no-right': !ed.sidebars.right }">
<EditorPalette v-if="ed.sidebars.left" />
@ -35,6 +45,7 @@ onMounted(() => {
<EditorInspector v-if="ed.sidebars.right" />
<EditorRail v-else side="right" />
</div>
</template>
<Transition name="fade">
<div v-if="ed.notice.value" class="toast" :class="ed.notice.value.kind">{{ ed.notice.value.text }}</div>
</Transition>

View File

@ -43,6 +43,7 @@ const SHORTCUTS: [string, string][] = [
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
['Delete', 'Remove the selection'],
['Ctrl+Z, Ctrl+Shift+Z', 'Undo, redo'],
['Logo (top left)', 'Back to the main menu: free play, campaign, challenges, leaderboard. Your work is saved'],
['F', 'Fit the circuit to the screen'],
['Enter', 'Open the selected component'],
]

View File

@ -0,0 +1,118 @@
<script setup lang="ts">
// The title screen: what you see when Logigate opens. A circuit builds
// itself in the background; the menu picks how to play. Arrow keys move
// through it, Enter chooses, Esc goes back.
import type { MenuPage } from '~/composables/useEditor'
const ed = useEditor()
const page = ed.menuPage
const nav = ref<HTMLElement>()
const ITEMS: { page?: MenuPage; label: string; icon: string; sub: string }[] = [
{ page: 'free', label: 'Free play', icon: 'lucide:cpu', sub: 'Every part from the start, your own projects' },
{ page: 'campaign', label: 'Campaign', icon: 'lucide:route', sub: 'Start with NAND, earn each part you build' },
{ page: 'challenges', label: 'Challenges', icon: 'lucide:target', sub: 'Single tasks and the puzzle of the week' },
{ page: 'leaderboard', label: 'Leaderboard', icon: 'lucide:trophy', sub: 'Fewest transistors wins' },
]
const TITLES: Record<MenuPage, string> = { main: '', free: 'Free play', campaign: 'Campaign', challenges: 'Challenges', leaderboard: 'Leaderboard' }
function go(p: MenuPage) {
page.value = page.value === p ? 'main' : p
}
function buttons() {
return [...(nav.value?.querySelectorAll<HTMLButtonElement>('button') ?? [])]
}
function onKey(e: KeyboardEvent) {
if (ed.dialog.value || ed.showHelp.value) return
const t = e.target as HTMLElement
const typing = t.closest('input, textarea, select, [contenteditable]')
if (e.key === 'Escape') {
if (typing) return (t as HTMLElement).blur()
if (page.value !== 'main') {
page.value = 'main'
e.preventDefault()
}
return
}
if (typing || (e.key !== 'ArrowDown' && e.key !== 'ArrowUp')) return
// Up and down move through the menu; from inside a page they go back to it.
const list = buttons()
const at = list.indexOf(document.activeElement as HTMLButtonElement)
const next = at < 0 ? (e.key === 'ArrowDown' ? 0 : list.length - 1) : (at + (e.key === 'ArrowDown' ? 1 : -1) + list.length) % list.length
list[next]?.focus()
e.preventDefault()
}
onMounted(() => {
window.addEventListener('keydown', onKey)
nextTick(() => buttons()[0]?.focus())
})
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
</script>
<template>
<div class="title-screen">
<EditorMenuBackground />
<div class="title-shade" />
<div class="title-layout" :class="{ open: page !== 'main' }">
<div class="title-side">
<div class="title-logo">
<svg viewBox="0 0 32 32" aria-hidden="true">
<path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.5" />
<circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.2" />
</svg>
<h1>Logigate</h1>
</div>
<p class="title-tag">From one NAND gate to a computer</p>
<nav ref="nav" class="title-nav" aria-label="Main menu">
<button class="title-item primary" @click="ed.enterGame()">
<Icon name="lucide:play" class="size-5 shrink-0" />
<span class="grow">
<span class="label">Continue</span>
<span class="sub">{{ ed.project.value.name }}</span>
</span>
</button>
<button v-for="it in ITEMS" :key="it.label" class="title-item" :class="{ active: page === it.page }" @click="go(it.page!)">
<Icon :name="it.icon" class="size-5 shrink-0" />
<span class="grow">
<span class="label">{{ it.label }}</span>
<span class="sub">{{ it.sub }}</span>
</span>
<Icon name="lucide:chevron-right" class="chev size-4 shrink-0" />
</button>
<button class="title-item" @click="ed.dialog.value = 'settings'">
<Icon name="lucide:settings" class="size-5 shrink-0" />
<span class="grow"><span class="label">Settings</span></span>
</button>
</nav>
<footer class="title-foot">
<button class="title-link" @click="ed.dialog.value = 'account'">
<Icon :name="ed.account.value ? 'lucide:cloud-check' : 'lucide:user'" class="size-4" />
{{ ed.account.value ? ed.account.value.email : 'Sign in to play on every computer' }}
</button>
<button class="title-link" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /> How to play</button>
</footer>
</div>
<Transition name="title-page" mode="out-in">
<section v-if="page !== 'main'" :key="page" class="title-page" :aria-label="TITLES[page]">
<header>
<button class="tb-btn" title="Back (Esc)" @click="page = 'main'"><Icon name="lucide:arrow-left" class="size-4" /></button>
<h2>{{ TITLES[page] }}</h2>
</header>
<div class="title-page-body">
<EditorProjectList v-if="page === 'free'" free-only @done="ed.enterGame()" />
<EditorMenuCampaign v-else-if="page === 'campaign'" />
<EditorMenuChallenges v-else-if="page === 'challenges'" />
<EditorMenuLeaderboard v-else-if="page === 'leaderboard'" />
</div>
</section>
</Transition>
</div>
</div>
</template>

View File

@ -0,0 +1,400 @@
<script setup lang="ts">
// The title screen's background: an endless circuit board seen from above,
// drifting slowly by. Parts are placed one after the other, wires draw
// themselves between them, then signals run along them and lamps light up,
// like a factory building itself. With reduced motion, it is a still board.
const canvas = ref<HTMLCanvasElement>()
const CELL = 22
const CW = 30 // chunk size in cells
const CH = 18
type Kind = 'nand' | 'chip' | 'lamp' | 'switch' | 'hex'
interface Part {
kind: Kind
x: number
y: number
w: number
h: number
label?: string
ins: [number, number][]
outs: [number, number][]
born: number
}
interface Route {
pts: [number, number][]
len: number
born: number
/** Seconds between signals, and the offset of the first. */
every: number
phase: number
to?: Part
/** Several lines side by side: a cable. */
lanes: number
}
interface Chunk {
parts: Part[]
routes: Route[]
start: number
}
/** Same chunk, same circuit: a small seeded random generator. */
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 LABELS = ['ADD', 'ALU', 'REG', 'MUX', 'CNT', 'RAM', 'DEC', 'XOR', 'CPU', 'ROM', 'PC', 'ACC', 'SR', 'D-FF', 'CMP', 'BUS']
/** `warm`: made when the menu opens, so the board starts partly built. */
function makeChunk(cx: number, cy: number, now: number, warm: boolean): Chunk {
const r = rng(cx * 73856093 ^ cy * 19349663 ^ 0x5bd1e995)
const parts: Part[] = []
const free = (x: number, y: number, w: number, h: number) =>
x >= 1 && y >= 1 && x + w <= CW - 1 && y + h <= CH - 2 && !parts.some(p => x < p.x + p.w + 2 && x + w + 2 > p.x && y < p.y + p.h + 1 && y + h + 1 > p.y)
const count = 5 + Math.floor(r() * 5)
for (let i = 0; i < count * 6 && parts.length < count; i++) {
const roll = r()
const kind: Kind = roll < 0.3 ? 'nand' : roll < 0.6 ? 'chip' : roll < 0.75 ? 'lamp' : roll < 0.9 ? 'switch' : 'hex'
const [w, h] = kind === 'nand' ? [3, 2] : kind === 'chip' ? [4 + Math.floor(r() * 3), 3 + Math.floor(r() * 4)] : kind === 'lamp' ? [2, 1] : kind === 'switch' ? [2, 1] : [2, 3]
const x = Math.floor(r() * (CW - w))
const y = Math.floor(r() * (CH - h))
if (!free(x, y, w, h)) continue
const ins: [number, number][] = []
const outs: [number, number][] = []
if (kind === 'nand') {
ins.push([x, y + 0.5], [x, y + 1.5])
outs.push([x + w, y + 1])
} else if (kind === 'chip') {
for (let k = 0; k < h; k++) ins.push([x, y + 0.5 + k])
for (let k = 0; k < Math.max(1, h - 1); k++) outs.push([x + w, y + 0.5 + k])
} else if (kind === 'lamp') ins.push([x, y + 0.5])
else if (kind === 'switch') outs.push([x + w, y + 0.5])
else for (let k = 0; k < 3; k++) ins.push([x, y + 0.5 + k])
parts.push({ kind, x, y, w, h, ins, outs, label: kind === 'chip' ? LABELS[Math.floor(r() * LABELS.length)] : undefined, born: 0 })
}
// Built left to right, one part every second or two, as you watch.
parts.sort((a, b) => a.x - b.x)
const start = now + r() * 2 - (warm ? r() * 18 : 0)
let at = start
for (const p of parts) {
p.born = at
at += 1 + r() * 1.6
}
const routes: Route[] = []
const used = new Set<string>()
for (const p of parts) {
for (const o of p.outs) {
const targets = parts.filter(q => q !== p && q.x > o[0] + 1 && q.ins.length)
if (!targets.length) continue
const q = targets[Math.floor(r() * targets.length)]!
const free = q.ins.filter(i => !used.has(`${i[0]},${i[1]}`))
const i = free[Math.floor(r() * free.length)]
if (!i) continue
used.add(`${i[0]},${i[1]}`)
const mid = Math.round((o[0] + i[0]) / 2) + (r() < 0.5 ? 0 : 1)
const pts: [number, number][] = [o, [mid, o[1]], [mid, i[1]], i]
const len = pts.reduce((s, pt, k) => (k ? s + Math.abs(pt[0] - pts[k - 1]![0]) + Math.abs(pt[1] - pts[k - 1]![1]) : 0), 0)
routes.push({ pts, len, born: Math.max(p.born, q.born) + 0.2, every: 2 + r() * 3, phase: r() * 3, to: q, lanes: 1 })
}
}
// A cable runs through every chunk of some rows, so long buses cross the board.
const rowRand = rng(cy * 2654435761)
if (rowRand() < 0.6) {
const yy = CH - 1 + 0.5
const pts: [number, number][] = [
[0, yy],
[CW, yy],
]
routes.push({ pts, len: CW, born: start + 0.3, every: 3 + rowRand() * 2, phase: rowRand() * 3, lanes: 4 })
}
return { parts, routes, start }
}
let raf = 0
let alive = true
onMounted(() => {
const c = canvas.value!
const ctx = c.getContext('2d')!
const still = window.matchMedia('(prefers-reduced-motion: reduce)').matches
const chunks = new Map<string, Chunk>()
const t0 = performance.now()
let cam = { x: 0, y: 0 }
let first = true
function resize() {
const dpr = Math.min(2, window.devicePixelRatio || 1)
c.width = c.clientWidth * dpr
c.height = c.clientHeight * dpr
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
// A still board is drawn once, and again when the window changes size.
if (still && !first) requestAnimationFrame(frame)
}
resize()
window.addEventListener('resize', resize)
onBeforeUnmount(() => window.removeEventListener('resize', resize))
/** The point a share `f` (0..1) along a route. */
function along(route: Route, f: number): [number, number] {
let left = f * route.len
for (let k = 1; k < route.pts.length; k++) {
const a = route.pts[k - 1]!
const b = route.pts[k]!
const seg = Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
if (left <= seg) {
const t = seg ? left / seg : 0
return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
}
left -= seg
}
return route.pts[route.pts.length - 1]!
}
function pathTo(route: Route, f: number, ox: number, oy: number, off: number) {
ctx.beginPath()
let left = f * route.len
const p0 = route.pts[0]!
ctx.moveTo(ox + p0[0] * CELL, oy + (p0[1] + off) * CELL)
for (let k = 1; k < route.pts.length && left > 0; k++) {
const a = route.pts[k - 1]!
const b = route.pts[k]!
const seg = Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
const t = seg ? Math.min(1, left / seg) : 1
ctx.lineTo(ox + (a[0] + (b[0] - a[0]) * t) * CELL, oy + (a[1] + (b[1] - a[1]) * t + off) * CELL)
left -= seg
}
ctx.stroke()
}
function drawPart(p: Part, ox: number, oy: number, k: number, lit: boolean) {
const x = ox + p.x * CELL
const y = oy + p.y * CELL
const w = p.w * CELL
const h = p.h * CELL
ctx.save()
ctx.globalAlpha = k
ctx.translate(x + w / 2, y + h / 2)
ctx.scale(0.85 + 0.15 * k, 0.85 + 0.15 * k)
ctx.translate(-w / 2, -h / 2)
ctx.lineWidth = 1.4
ctx.strokeStyle = '#3c4859'
ctx.fillStyle = '#141b24'
if (p.kind === 'nand') {
ctx.beginPath()
ctx.moveTo(0, 0)
ctx.lineTo(w * 0.45, 0)
ctx.arc(w * 0.45, h / 2, h / 2, -Math.PI / 2, Math.PI / 2)
ctx.lineTo(0, h)
ctx.closePath()
ctx.fill()
ctx.stroke()
ctx.beginPath()
ctx.arc(w * 0.45 + h / 2 + 4, h / 2, 3.5, 0, Math.PI * 2)
ctx.stroke()
} else if (p.kind === 'lamp') {
ctx.beginPath()
ctx.arc(w * 0.6, h / 2, CELL * 0.45, 0, Math.PI * 2)
ctx.fillStyle = lit ? '#ffd34d' : '#1b222c'
if (lit) {
ctx.shadowColor = 'rgba(255, 211, 77, 0.8)'
ctx.shadowBlur = 14
}
ctx.fill()
ctx.shadowBlur = 0
ctx.stroke()
} else if (p.kind === 'switch') {
ctx.beginPath()
ctx.roundRect(0, h * 0.15, w * 0.85, h * 0.7, h * 0.35)
ctx.fill()
ctx.stroke()
ctx.beginPath()
ctx.arc(w * 0.62, h / 2, h * 0.24, 0, Math.PI * 2)
ctx.fillStyle = '#9fb0c4'
ctx.fill()
} else {
ctx.beginPath()
ctx.roundRect(0, 0, w, h, 3)
ctx.fill()
ctx.stroke()
ctx.fillStyle = p.kind === 'hex' ? (lit ? '#ff5c5c' : '#3a2226') : '#56647a'
if (p.kind === 'hex') {
ctx.fillRect(w * 0.3, h * 0.2, w * 0.4, 2.5)
ctx.fillRect(w * 0.3, h * 0.5, w * 0.4, 2.5)
ctx.fillRect(w * 0.3, h * 0.78, w * 0.4, 2.5)
ctx.fillRect(w * 0.27, h * 0.22, 2.5, h * 0.28)
ctx.fillRect(w * 0.7, h * 0.52, 2.5, h * 0.28)
} else if (p.label) {
ctx.font = '600 12px Inter, sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(p.label, w / 2, h / 2)
}
}
// Pins
ctx.fillStyle = '#4c586b'
for (const [px, py] of [...p.ins, ...p.outs]) {
ctx.beginPath()
ctx.arc((px - p.x) * CELL, (py - p.y) * CELL, 2.2, 0, Math.PI * 2)
ctx.fill()
}
ctx.restore()
}
/** The chunk's builder: a small bot that flies to where the next part goes. */
function drawBuilder(ch: Chunk, ox: number, oy: number, now: number) {
const ps = ch.parts
const i = ps.findIndex(p => p.born > now)
if (i < 0 || !ps.length) return
const to = ps[i]!
const from = ps[i - 1]
const c = (p: Part): [number, number] => [ox + (p.x + p.w / 2) * CELL, oy + (p.y + p.h / 2) * CELL]
const [tx, ty] = c(to)
let x = tx
let y = ty
let fade = 1
if (from) {
const [fx, fy] = c(from)
const span = to.born - from.born
const t = Math.min(1, Math.max(0, (now - from.born) / span) * 1.4)
const e = t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2
x = fx + (tx - fx) * e
y = fy + (ty - fy) * e - Math.sin(e * Math.PI) * 18
} else fade = Math.max(0, 1 - (to.born - now) / 2)
// It hovers over the spot, then the part appears.
const bob = Math.sin(now * 6) * 1.5
ctx.save()
ctx.globalAlpha = fade
ctx.fillStyle = 'rgba(76, 194, 255, 0.12)'
ctx.beginPath()
ctx.ellipse(x, y + 12, 9, 3, 0, 0, Math.PI * 2)
ctx.fill()
ctx.shadowColor = 'rgba(76, 194, 255, 0.9)'
ctx.shadowBlur = 12
ctx.fillStyle = '#4cc2ff'
ctx.beginPath()
ctx.arc(x, y + bob, 3.5, 0, Math.PI * 2)
ctx.fill()
ctx.shadowBlur = 0
ctx.strokeStyle = 'rgba(76, 194, 255, 0.5)'
ctx.lineWidth = 1
ctx.beginPath()
ctx.arc(x, y + bob, 7, now * 4, now * 4 + Math.PI * 1.2)
ctx.stroke()
ctx.restore()
}
function frame(nowMs: number) {
if (!alive) return
const now = still ? 1e6 : (nowMs - t0) / 1000
const W = c.clientWidth
const H = c.clientHeight
// Drift down and to the right, slowly.
cam = { x: now * 18, y: now * 6 }
if (still) cam = { x: 0, y: 0 }
ctx.fillStyle = '#0b0f14'
ctx.fillRect(0, 0, W, H)
// Grid dots
ctx.fillStyle = '#1a222d'
const gx = -(cam.x % CELL)
const gy = -(cam.y % CELL)
for (let x = gx; x < W; x += CELL) for (let y = gy; y < H; y += CELL) ctx.fillRect(x, y, 1.2, 1.2)
const cwPx = CW * CELL
const chPx = CH * CELL
// Only chunks on screen: new ones are built where you can see it.
const x0 = Math.floor(cam.x / cwPx)
const y0 = Math.floor(cam.y / chPx)
const x1 = Math.floor((cam.x + W) / cwPx)
const y1 = Math.floor((cam.y + H) / chPx)
const seen = new Set<string>()
for (let cx = x0; cx <= x1; cx++) {
for (let cy = y0; cy <= y1; cy++) {
const key = `${cx},${cy}`
seen.add(key)
let ch = chunks.get(key)
if (!ch) {
ch = makeChunk(cx, cy, still ? now - 60 : now, first)
chunks.set(key, ch)
}
const ox = cx * cwPx - cam.x
const oy = cy * chPx - cam.y
// Wires: drawn out as they are laid, then signals run along them.
for (const r of ch.routes) {
const built = Math.min(1, Math.max(0, (now - r.born) / Math.max(0.6, r.len / 7)))
if (built <= 0) continue
for (let lane = 0; lane < r.lanes; lane++) {
const off = (lane - (r.lanes - 1) / 2) * 0.16
ctx.strokeStyle = r.lanes > 1 ? '#253040' : '#2a3442'
ctx.lineWidth = r.lanes > 1 ? 1.3 : 1.8
pathTo(r, built, ox, oy, off)
}
if (built < 1) {
// The tip of a wire being laid.
const [tx, ty] = along(r, built)
ctx.fillStyle = '#4cc2ff'
ctx.beginPath()
ctx.arc(ox + tx * CELL, oy + ty * CELL, 2.4, 0, Math.PI * 2)
ctx.fill()
continue
}
const cycle = (now - r.born + r.phase) % r.every
const travel = r.len / 9
if (cycle < travel) {
const f = cycle / travel
ctx.strokeStyle = 'rgba(61, 220, 132, 0.55)'
ctx.lineWidth = r.lanes > 1 ? 1.4 : 2
for (let lane = 0; lane < r.lanes; lane++) pathTo(r, f, ox, oy, (lane - (r.lanes - 1) / 2) * 0.16)
const [px, py] = along(r, f)
ctx.fillStyle = '#3ddc84'
ctx.shadowColor = 'rgba(61, 220, 132, 0.9)'
ctx.shadowBlur = 10
ctx.beginPath()
ctx.arc(ox + px * CELL, oy + py * CELL, 2.8, 0, Math.PI * 2)
ctx.fill()
ctx.shadowBlur = 0
}
}
for (const p of ch.parts) {
const k = Math.min(1, Math.max(0, (now - p.born) / 0.4))
if (k <= 0) continue
// A lamp or display lights for a moment after a signal reaches it.
const lit = ch.routes.some(r => r.to === p && now > r.born && (now - r.born + r.phase) % r.every < r.len / 9 + 0.9 && (now - r.born + r.phase) % r.every > r.len / 9)
drawPart(p, ox, oy, k, lit)
// A ring where a part was just put down.
const age = now - p.born
if (age < 0.7 && !still) {
const g = age / 0.7
ctx.strokeStyle = `rgba(76, 194, 255, ${0.6 * (1 - g)})`
ctx.lineWidth = 1.5
const pad = 4 + g * 10
ctx.strokeRect(ox + p.x * CELL - pad, oy + p.y * CELL - pad, p.w * CELL + pad * 2, p.h * CELL + pad * 2)
}
}
if (!still) drawBuilder(ch, ox, oy, now)
}
}
for (const key of chunks.keys()) if (!seen.has(key)) chunks.delete(key)
first = false
if (!still) raf = requestAnimationFrame(frame)
}
raf = requestAnimationFrame(frame)
})
onBeforeUnmount(() => {
alive = false
cancelAnimationFrame(raf)
})
</script>
<template>
<canvas ref="canvas" class="menu-bg" aria-hidden="true" />
</template>

View File

@ -0,0 +1,70 @@
<script setup lang="ts">
// The campaign page of the title menu: how far you are, what is next.
import { CHALLENGES } from '~/lib/logic/challenges'
import { campaignProgress, challengeOpen, KIND_NAMES, KIND_UNLOCK } from '~/lib/logic/progress'
import type { NodeKind } from '~/lib/logic/types'
const ed = useEditor()
const p = ed.projectOf('campaign')
const solved = new Set(p?.solved ?? [])
const next = p ? CHALLENGES.find(c => !solved.has(c.id) && challengeOpen(p, c.id)) : CHALLENGES[0]
const parts = (id: string) =>
(Object.keys(KIND_UNLOCK) as NodeKind[])
.filter(k => KIND_UNLOCK[k] === id)
.map(k => KIND_NAMES[k])
.join(', ')
function fresh() {
ed.newProject(false, true)
ed.paletteTab.value = 'challenges'
ed.enterGame()
}
</script>
<template>
<div class="menu-campaign">
<p class="hint">
You start with a NAND gate, switches and lamps. Each challenge you solve becomes a part you can use, and opens the next ones. Clocks, buttons, panels and
displays are earned on the way.
</p>
<div class="menu-card">
<template v-if="p">
<div class="flex items-center justify-between">
<span class="font-semibold">{{ solved.size }} of {{ CHALLENGES.length }} solved</span>
<span class="tabular-nums text-(--muted)">{{ Math.round(campaignProgress(p) * 100) }}%</span>
</div>
<div class="bar"><span :style="{ width: `${campaignProgress(p) * 100}%` }" /></div>
<p v-if="next" class="mt-2">Next: <strong>{{ next.name }}</strong>, {{ next.goal }}</p>
<p v-else class="mt-2">Every challenge solved. You built it all from NAND.</p>
</template>
<p v-else>Not started yet. The first task: build NOT from a single NAND gate.</p>
<div class="mt-3 flex flex-wrap gap-2">
<button class="btn btn-primary" @click="ed.playCampaign()">
<Icon name="lucide:play" class="size-4" /> {{ p ? 'Continue the campaign' : 'Start the campaign' }}
</button>
<button v-if="p" class="btn" title="A second campaign from the start; the first one stays in your projects" @click="fresh">
<Icon name="lucide:rotate-ccw" class="size-4" /> Start over
</button>
</div>
</div>
<ol class="menu-steps">
<li
v-for="c in CHALLENGES"
:key="c.id"
:class="{ solved: solved.has(c.id), locked: p ? !challengeOpen(p, c.id) : c !== CHALLENGES[0], next: c === next }"
>
<Icon
:name="solved.has(c.id) ? 'lucide:circle-check' : (p ? challengeOpen(p, c.id) : c === CHALLENGES[0]) ? 'lucide:circle-dot' : 'lucide:lock'"
class="size-4 shrink-0"
/>
<span class="grow">
<span class="font-medium">{{ c.name }}</span>
<span v-if="parts(c.id)" class="unlocks"> · unlocks {{ parts(c.id) }}</span>
</span>
<span v-if="p?.best?.[c.id] !== undefined" class="tabular-nums text-xs text-(--muted)">{{ p.best[c.id] }} transistors</span>
</li>
</ol>
</div>
</template>

View File

@ -0,0 +1,41 @@
<script setup lang="ts">
// The challenges page of the title menu: the puzzle of the week and every
// challenge on its own, all open, played in one "Challenges" project.
import { CHALLENGES } from '~/lib/logic/challenges'
import { weekKey } from '~/lib/logic/puzzles'
const ed = useEditor()
const p = ed.projectOf('challenges')
const solved = new Set(p?.solved ?? [])
const week = Number(weekKey().split('-')[1])
</script>
<template>
<div>
<div class="menu-card weekly-card">
<div class="flex items-center gap-3">
<Icon name="lucide:calendar-days" class="size-6 shrink-0 text-(--accent)" />
<div class="grow">
<div class="font-semibold">Puzzle of the week {{ week }}</div>
<p>A new logic puzzle every Monday, the same for everyone. Fewest transistors wins.</p>
</div>
<button class="btn btn-primary" @click="ed.playWeekly()"><Icon name="lucide:play" class="size-4" /> Play</button>
</div>
</div>
<p class="hint mt-4">Each one is a part to build from NAND gates and the parts you made before. Press Check when it works; fewer transistors is better.</p>
<ul class="menu-grid">
<li v-for="c in CHALLENGES" :key="c.id" :class="{ solved: solved.has(c.id) }">
<button class="menu-tile" @click="ed.playChallenge(c)">
<span 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)'" />
<span class="grow font-semibold">{{ c.name }}</span>
<span v-if="p?.best?.[c.id] !== undefined" class="tabular-nums text-xs text-(--muted)" title="Your best">{{ p.best[c.id] }} transistors</span>
</span>
<span class="goal">{{ c.goal }}</span>
<span class="pins">{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}</span>
</button>
</li>
</ul>
</div>
</template>

View File

@ -0,0 +1,123 @@
<script setup lang="ts">
// The leaderboard page of the title menu: the best ten of each week's
// puzzle, your place, and the name shown next to your scores.
import { CHALLENGES } from '~/lib/logic/challenges'
import { weekKey } from '~/lib/logic/puzzles'
const ed = useEditor()
const DAY = 86_400_000
const weeks = Array.from({ length: 5 }, (_, i) => {
const key = weekKey(new Date(Date.now() - i * 7 * DAY))
return { id: i ? `week-${key}` : 'weekly', label: i === 0 ? 'This week' : i === 1 ? 'Last week' : `Week ${Number(key.split('-')[1])}` }
})
const at = ref(0)
type Board = Awaited<ReturnType<typeof ed.fetchBoard>>
const boards = reactive<Record<string, Board | 'loading'>>({})
const board = computed(() => boards[weeks[at.value]!.id])
watch(
at,
async i => {
const id = weeks[i]!.id
if (boards[id] && boards[id] !== null) return
boards[id] = 'loading'
boards[id] = await ed.fetchBoard(id)
},
{ immediate: true },
)
const name = ref(ed.playerName.value)
const saving = ref(false)
const nameError = ref('')
async function saveName() {
saving.value = true
nameError.value = ''
try {
await ed.setPlayerName(name.value)
name.value = ed.playerName.value
// Your name shows on the boards already loaded once they are fetched again.
for (const k of Object.keys(boards)) delete boards[k]
const id = weeks[at.value]!.id
boards[id] = await ed.fetchBoard(id)
} catch (e) {
nameError.value = (e as Error).message
} finally {
saving.value = false
}
}
/** Your best per challenge, over the campaign and the challenges project. */
const records = (() => {
const best: Record<string, number> = {}
for (const p of [ed.projectOf('campaign'), ed.projectOf('challenges')])
for (const [id, t] of Object.entries(p?.best ?? {})) best[id] = Math.min(best[id] ?? Infinity, t)
return CHALLENGES.filter(c => best[c.id] !== undefined).map(c => ({ name: c.name, t: best[c.id]! }))
})()
</script>
<template>
<div class="menu-board">
<form class="name-row" @submit.prevent="saveName">
<label class="field grow">
<span>Your name on the leaderboards</span>
<input v-model="name" maxlength="24" placeholder="Anonymous" autocomplete="nickname" />
</label>
<button class="btn" :disabled="saving || name.trim() === ed.playerName.value">{{ saving ? 'Saving…' : 'Save' }}</button>
</form>
<p v-if="nameError" class="hint text-(--danger)">{{ nameError }}</p>
<div class="tabs board-tabs" role="tablist">
<button v-for="(w, i) in weeks" :key="w.id" role="tab" :aria-selected="at === i" :class="{ active: at === i }" @click="at = i">{{ w.label }}</button>
</div>
<p v-if="board === 'loading' || board === undefined" class="hint mt-3">Loading…</p>
<p v-else-if="board === null" class="hint mt-3">Could not load this board. Are you online?</p>
<template v-else>
<div class="mt-3 flex items-start gap-3">
<div class="grow">
<div class="font-semibold">{{ board.spec.name }}</div>
<p class="hint">{{ board.spec.goal }}</p>
</div>
<button v-if="at === 0" class="btn btn-primary shrink-0" @click="ed.playWeekly()"><Icon name="lucide:play" class="size-4" /> Play</button>
</div>
<p v-if="!board.summary.players" class="hint mt-3">Nobody has solved it yet. Be the first.</p>
<template v-else>
<table class="board">
<thead>
<tr>
<th>#</th>
<th>Player</th>
<th class="num">Transistors</th>
<th class="num" title="Gates a signal passes through on the longest path">Delay</th>
</tr>
</thead>
<tbody>
<tr v-for="(e, i) in board.summary.top" :key="i" :class="{ you: e.you }">
<td class="rank">{{ i + 1 }}</td>
<td>{{ e.name || 'Anonymous' }}<span v-if="e.you" class="you-tag">you</span></td>
<td class="num">{{ e.t.toLocaleString() }}</td>
<td class="num">{{ e.d ?? '–' }}</td>
</tr>
<tr v-if="board.summary.you && !board.summary.top?.some(e => e.you)" class="you gap">
<td class="rank">{{ board.summary.you.rank }}</td>
<td>{{ ed.playerName.value || 'Anonymous' }}<span class="you-tag">you</span></td>
<td class="num">{{ board.summary.you.t.toLocaleString() }}</td>
<td class="num">{{ board.summary.you.d ?? '–' }}</td>
</tr>
</tbody>
</table>
<EditorScoreChart :summary="board.summary" />
</template>
</template>
<h3 class="mt-6">Your challenge records</h3>
<p v-if="!records.length" class="hint">Solve challenges in the campaign or on the Challenges page; your fewest transistors show up here.</p>
<ul v-else class="records">
<li v-for="r in records" :key="r.name">
<span>{{ r.name }}</span>
<span class="tabular-nums text-(--muted)">{{ r.t.toLocaleString() }} transistors</span>
</li>
</ul>
</div>
</template>

View File

@ -7,7 +7,7 @@ import { BASIC_GROUPS } from '~/composables/useParts'
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
const ed = useEditor()
const tab = ref<'parts' | 'challenges'>('parts')
const tab = ed.paletteTab
const query = ref('')
const { componentGroups, search, recentParts } = useParts()

View File

@ -0,0 +1,129 @@
<script setup lang="ts">
// Your projects: open, rename, copy, delete, restore, and start new ones.
// Used by the Projects dialog and the main menu's Free play page.
const props = defineProps<{ /** Hide campaign and challenge projects (they have their own menu pages). */ freeOnly?: boolean }>()
const emit = defineEmits<{ done: [] }>()
const ed = useEditor()
const list = computed(() => (props.freeOnly ? ed.projects.value.filter(m => !ed.projectMode(m)) : ed.projects.value))
const fileInput = ref<HTMLInputElement>()
const renaming = ref<string | null>(null)
const renameText = ref('')
const confirmDelete = ref<string | null>(null)
const close = () => emit('done')
const showTrash = ref(false)
const trash = ref<{ id: string; name: string; deleted: number; v: number }[] | null>(null)
async function toggleTrash() {
showTrash.value = !showTrash.value
if (showTrash.value) trash.value = await ed.listTrash().catch(() => [])
}
async function restoreDeleted(t: { id: string; v: number }) {
await ed.restoreDeleted(t)
close()
}
const when = (t: number) => new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(t)
function open(id: string) {
ed.switchProject(id)
close()
}
function startRename(id: string, name: string) {
renaming.value = id
renameText.value = name
nextTick(() => document.querySelector<HTMLInputElement>('.project-list input')?.select())
}
function finishRename() {
if (renaming.value) ed.renameProject(renaming.value, renameText.value)
renaming.value = null
}
function onFile(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (file) ed.importAsProject(file).then(close)
;(e.target as HTMLInputElement).value = ''
}
</script>
<template>
<div class="projects">
<p class="hint mt-1">
Saved in this browser as you work.
<template v-if="ed.account.value">Also kept in your account, so they are on every computer you sign in on.</template>
<a v-else href="#" @click.prevent="ed.dialog.value = 'account'">Sign in to have them on every computer.</a>
</p>
<p v-if="!list.length" class="hint mt-3">No projects yet. Start one below.</p>
<ul class="project-list">
<li v-for="m in list" :key="m.id" :class="{ current: m.id === ed.meta.value.id }">
<input
v-if="renaming === m.id"
v-model="renameText"
class="rename"
@keydown.enter="finishRename"
@keydown.esc="renaming = null"
@blur="finishRename"
/>
<button v-else class="pick" @click="open(m.id)">
<span class="name">
{{ m.name }}
<span v-if="m.id === ed.meta.value.id" class="badge">open</span>
</span>
<span class="meta">
{{ when(m.updated) }}
<template v-if="m.link"> · <Icon name="lucide:link" class="size-3" /> {{ m.link.key ? 'your link' : 'from a link' }}</template>
<template v-if="ed.account.value && m.cloud?.owner === ed.account.value.id">
· <Icon :name="m.dirty ? 'lucide:cloud-upload' : 'lucide:cloud-check'" class="size-3" /> {{ m.dirty ? 'saving to account' : 'in your account' }}
</template>
<template v-else-if="ed.account.value && !m.cloud"> · <Icon name="lucide:cloud-upload" class="size-3" /> uploading</template>
<template v-else-if="!ed.account.value"> · <Icon name="lucide:laptop" class="size-3" /> this browser only</template>
</span>
</button>
<button
v-if="ed.account.value && m.cloud?.owner === ed.account.value.id"
class="icon-btn"
title="Savegames: earlier versions"
@click="ed.versionsFor.value = m.id; ed.dialog.value = 'versions'"
>
<Icon name="lucide:history" class="size-3.5" />
</button>
<button class="icon-btn" title="Rename" @click="startRename(m.id, m.name)"><Icon name="lucide:pencil" class="size-3.5" /></button>
<button class="icon-btn" title="Duplicate" @click="ed.duplicateProject(m.id); close()"><Icon name="lucide:copy" class="size-3.5" /></button>
<button v-if="confirmDelete !== m.id" class="icon-btn" title="Delete" @click="confirmDelete = m.id"><Icon name="lucide:trash-2" class="size-3.5" /></button>
<button v-else class="btn-sm btn-danger" @click="ed.deleteProject(m.id); confirmDelete = null">Delete?</button>
</li>
</ul>
<template v-if="ed.account.value">
<button class="section-toggle mt-4" @click="toggleTrash">
<Icon :name="showTrash ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
Recently deleted
</button>
<template v-if="showTrash">
<p v-if="!trash" class="hint mt-2">Loading…</p>
<p v-else-if="!trash.length" class="hint mt-2">Nothing deleted in the last 30 days.</p>
<ul v-else class="project-list">
<li v-for="t in trash" :key="t.id">
<div class="pick">
<span class="name">{{ t.name }}</span>
<span class="meta">deleted {{ when(t.deleted) }}</span>
</div>
<button class="btn-sm" @click="restoreDeleted(t)">Restore</button>
</li>
</ul>
</template>
</template>
<div class="mt-4 flex flex-wrap gap-2">
<button v-if="!freeOnly" 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>
<input ref="fileInput" type="file" accept="application/json,.json" class="hidden" @change="onFile" />
</div>
</div>
</template>

View File

@ -1,45 +1,6 @@
<script setup lang="ts">
const ed = useEditor()
const fileInput = ref<HTMLInputElement>()
const renaming = ref<string | null>(null)
const renameText = ref('')
const confirmDelete = ref<string | null>(null)
const close = () => (ed.dialog.value = null)
const showTrash = ref(false)
const trash = ref<{ id: string; name: string; deleted: number; v: number }[] | null>(null)
async function toggleTrash() {
showTrash.value = !showTrash.value
if (showTrash.value) trash.value = await ed.listTrash().catch(() => [])
}
async function restoreDeleted(t: { id: string; v: number }) {
await ed.restoreDeleted(t)
close()
}
const when = (t: number) => new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(t)
function open(id: string) {
ed.switchProject(id)
close()
}
function startRename(id: string, name: string) {
renaming.value = id
renameText.value = name
nextTick(() => document.querySelector<HTMLInputElement>('.project-list input')?.select())
}
function finishRename() {
if (renaming.value) ed.renameProject(renaming.value, renameText.value)
renaming.value = null
}
function onFile(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (file) ed.importAsProject(file).then(close)
;(e.target as HTMLInputElement).value = ''
}
</script>
<template>
@ -49,81 +10,7 @@ function onFile(e: Event) {
<h2 id="projects-title">Projects</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<p class="hint mt-1">
Saved in this browser as you work.
<template v-if="ed.account.value">Also kept in your account, so they are on every computer you sign in on.</template>
<a v-else href="#" @click.prevent="ed.dialog.value = 'account'">Sign in to have them on every computer.</a>
</p>
<ul class="project-list">
<li v-for="m in ed.projects.value" :key="m.id" :class="{ current: m.id === ed.meta.value.id }">
<input
v-if="renaming === m.id"
v-model="renameText"
class="rename"
@keydown.enter="finishRename"
@keydown.esc="renaming = null"
@blur="finishRename"
/>
<button v-else class="pick" @click="open(m.id)">
<span class="name">
{{ m.name }}
<span v-if="m.id === ed.meta.value.id" class="badge">open</span>
</span>
<span class="meta">
{{ when(m.updated) }}
<template v-if="m.link"> · <Icon name="lucide:link" class="size-3" /> {{ m.link.key ? 'your link' : 'from a link' }}</template>
<template v-if="ed.account.value && m.cloud?.owner === ed.account.value.id">
· <Icon :name="m.dirty ? 'lucide:cloud-upload' : 'lucide:cloud-check'" class="size-3" /> {{ m.dirty ? 'saving to account' : 'in your account' }}
</template>
<template v-else-if="ed.account.value && !m.cloud"> · <Icon name="lucide:cloud-upload" class="size-3" /> uploading</template>
<template v-else-if="!ed.account.value"> · <Icon name="lucide:laptop" class="size-3" /> this browser only</template>
</span>
</button>
<button
v-if="ed.account.value && m.cloud?.owner === ed.account.value.id"
class="icon-btn"
title="Savegames: earlier versions"
@click="ed.versionsFor.value = m.id; ed.dialog.value = 'versions'"
>
<Icon name="lucide:history" class="size-3.5" />
</button>
<button class="icon-btn" title="Rename" @click="startRename(m.id, m.name)"><Icon name="lucide:pencil" class="size-3.5" /></button>
<button class="icon-btn" title="Duplicate" @click="ed.duplicateProject(m.id); close()"><Icon name="lucide:copy" class="size-3.5" /></button>
<button v-if="confirmDelete !== m.id" class="icon-btn" title="Delete" @click="confirmDelete = m.id"><Icon name="lucide:trash-2" class="size-3.5" /></button>
<button v-else class="btn-sm btn-danger" @click="ed.deleteProject(m.id); confirmDelete = null">Delete?</button>
</li>
</ul>
<template v-if="ed.account.value">
<button class="section-toggle mt-4" @click="toggleTrash">
<Icon :name="showTrash ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
Recently deleted
</button>
<template v-if="showTrash">
<p v-if="!trash" class="hint mt-2">Loading…</p>
<p v-else-if="!trash.length" class="hint mt-2">Nothing deleted in the last 30 days.</p>
<ul v-else class="project-list">
<li v-for="t in trash" :key="t.id">
<div class="pick">
<span class="name">{{ t.name }}</span>
<span class="meta">deleted {{ when(t.deleted) }}</span>
</div>
<button class="btn-sm" @click="restoreDeleted(t)">Restore</button>
</li>
</ul>
</template>
</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>
<input ref="fileInput" type="file" accept="application/json,.json" class="hidden" @change="onFile" />
</div>
<EditorProjectList @done="close" />
</div>
</div>
</template>

View File

@ -36,13 +36,13 @@ const linkIcon = computed(() => {
<template>
<header class="toolbar">
<div class="flex min-w-0 items-center gap-2">
<div class="brand">
<button class="brand" title="Main menu (your work is saved)" @click="ed.showMenu()">
<svg viewBox="0 0 32 32" class="size-6" aria-hidden="true">
<path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.5" />
<circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.2" />
</svg>
<span class="hidden xl:inline">Logigate</span>
</div>
<span class="hidden xl:inline">Menu</span>
</button>
<button class="tb-btn project-btn" title="Your projects" @click="ed.dialog.value = 'projects'">
<Icon name="lucide:folder" class="size-4 shrink-0" />
<span class="truncate">{{ ed.project.value.name }}</span>

View File

@ -20,7 +20,7 @@ import { rememberPart } from '~/lib/recent'
import { checkCircuit } from '~/lib/logic/check'
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 { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles'
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
@ -79,8 +79,12 @@ export interface PuzzleSummary {
players: number
histogram: { t: number; n: number }[]
you?: { t: number; d: number | null; rank: number }
/** The best ten, named as the players chose (empty: anonymous). */
top?: { name: string; t: number; d: number | null; you?: true }[]
}
export type MenuPage = 'main' | 'free' | 'campaign' | 'challenges' | 'leaderboard'
export interface ChallengeCheck extends TestResult {
transistors: number
/** Parts this first solve made usable (campaign). */
@ -142,6 +146,8 @@ function create() {
let placeholder = false
const start = initial()
// The starter project of a first visit is in the list now.
projects.value = listProjects()
const meta = ref<ProjectMeta>(start.meta)
const project = ref<Project>(start.project)
setCurrentId(start.meta.id)
@ -202,7 +208,13 @@ function create() {
function persistNow() {
clearTimeout(saveTimer)
saveTimer = undefined
meta.value = { ...meta.value, name: project.value.name, updated: Date.now(), ...(changed ? { dirty: true, starter: undefined } : {}) }
meta.value = {
...meta.value,
name: project.value.name,
updated: Date.now(),
...(project.value.mode ? { mode: project.value.mode } : {}),
...(changed ? { dirty: true, starter: undefined } : {}),
}
if (!saveProject(toRaw(meta.value), toRaw(project.value))) notify('Browser storage is full. Export your project to keep it.', 'error')
projects.value = listProjects()
if (changed) scheduleCloud()
@ -789,6 +801,106 @@ function create() {
notify(`${res.panel.kind === 'outpanel' ? 'Output' : 'Input'} panel with ${res.panel.rows?.length ?? 0} rows`)
}
// ── Main menu ─────────────────────────────────────────────────────
/** The title menu shows when the app opens at /; links open straight into the editor. */
const screen = ref<'menu' | 'editor'>(location.pathname === '/' ? 'menu' : 'editor')
const menuPage = ref<MenuPage>('main')
/** Tab of the parts panel on the left. */
const paletteTab = ref<'parts' | 'challenges'>('parts')
function enterGame() {
screen.value = 'editor'
menuPage.value = 'main'
}
function showMenu(page: MenuPage = 'main') {
persistNow()
dialog.value = null
menuPage.value = page
screen.value = 'menu'
}
/** A project's mode, from its index entry, or (for projects saved before it was noted there) from the project. */
const modes = new Map<string, Project['mode'] | null>()
function projectMode(m: ProjectMeta): Project['mode'] | undefined {
if (m.mode) return m.mode
if (!modes.has(m.id)) modes.set(m.id, loadProject(m.id)?.mode ?? null)
return modes.get(m.id) ?? undefined
}
/** The newest project of a mode, if any. */
const newestOf = (mode: Project['mode']) => listProjects().filter(m => projectMode(m) === mode).sort((a, b) => b.updated - a.updated)[0]
/** The newest project of a mode, for the menu to show progress (the open one as it is now). */
function projectOf(mode: Project['mode']): Project | null {
const m = newestOf(mode)
if (!m) return null
return m.id === meta.value.id ? project.value : loadProject(m.id)
}
/** Into the campaign: the newest one, or a new one. */
function playCampaign() {
const m = newestOf('campaign')
if (m) switchProject(m.id)
else newProject(false, true)
paletteTab.value = 'challenges'
enterGame()
}
/** Into the challenges project (made on first use: NAND only, every challenge open). */
function intoChallenges() {
const m = newestOf('challenges')
if (m) switchProject(m.id)
else {
persistNow()
const p = createProject({ examples: false, name: 'Challenges' })
p.mode = 'challenges'
activate(addProject(p), p)
}
paletteTab.value = 'challenges'
}
function playChallenge(c: Challenge) {
intoChallenges()
beginChallenge(c)
enterGame()
}
/** The puzzle of the week, in the challenges project. */
function playWeekly() {
intoChallenges()
const spec = project.value.puzzles?.find(p => p.id === weeklyId(weekKey()))
if (spec) beginPuzzle(spec)
else void openPuzzle('weekly')
enterGame()
}
/** Name shown next to your scores on the leaderboards. */
const playerName = ref((() => {
try {
return localStorage.getItem('logigate:player-name') ?? ''
} catch {
return ''
}
})())
async function setPlayerName(name: string) {
const res = await api<{ name: string }>('POST', '/api/players/name', { player: playerId(), name })
playerName.value = res.name
try {
localStorage.setItem('logigate:player-name', res.name)
} catch {}
}
/** A puzzle and its leaderboard from the server ("weekly", "week-2026-43" or a link id). */
async function fetchBoard(id: string): Promise<{ id: string; spec: PuzzleSpec; summary: PuzzleSummary } | null> {
try {
return await api('GET', `/api/puzzles/${encodeURIComponent(id)}?player=${encodeURIComponent(playerId())}`)
} catch {
return null
}
}
/** Puts pixels on a named screen of the component's box ('' for the main screen). */
function setScreen(ids: string[], name: string) {
const v = name.trim()
@ -2021,6 +2133,19 @@ function create() {
combineSelected,
setRowsType,
setScreen,
screen,
menuPage,
paletteTab,
enterGame,
showMenu,
projectMode,
projectOf,
playCampaign,
playChallenge,
playWeekly,
playerName,
setPlayerName,
fetchBoard,
setRowType,
addRow,
dropRow,

View File

@ -139,7 +139,7 @@ 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 } : {}),
...(p.mode === 'campaign' || p.mode === 'challenges' ? { mode: p.mode } : {}),
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
}
}

View File

@ -23,6 +23,8 @@ export interface ProjectMeta {
starter?: boolean
/** Ask the server to keep the state before the next upload as a savegame (after restoring an old version). */
snapshot?: boolean
/** The project's mode (campaign, challenges), so the main menu can find them without loading every project. */
mode?: 'campaign' | 'challenges'
}
export interface AccountUser {

View File

@ -210,8 +210,12 @@ 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'
/**
* "campaign": parts are earned by solving challenges. "challenges": the
* project the main menu's challenges are played in (NAND only, every
* challenge open). Default: sandbox, everything available.
*/
mode?: 'campaign' | 'challenges'
/** Puzzles opened from links or the weekly puzzle; their components carry `challenge: <puzzle id>`. */
puzzles?: PuzzleSpec[]
}

View File

@ -0,0 +1,17 @@
// A player's name on the leaderboards. Players have no account here, just a
// random id kept in their browser; the name shows next to their scores, on
// every puzzle, past ones too. An empty name shows as anonymous.
export default defineEventHandler(async event => {
rateLimit(event, 'player-name', 20, 10 * 60_000)
const body = await readBody<{ player?: unknown; name?: unknown }>(event).catch(() => null)
if (!body || !isPlayer(body.player)) throw createError({ statusCode: 400, message: 'Missing player' })
const name = cleanName(body.name)
const player = body.player
await locked('players', async () => {
const names = await playerNames()
if (name) names[player] = name
else delete names[player]
await puzzleStorage().setItem('players', names)
})
return { name }
})

View File

@ -7,5 +7,5 @@ export default defineEventHandler(async event => {
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)) }
return { id, spec, summary: summarize(await board(id!), playerParam(event), await playerNames()) }
})

View File

@ -26,7 +26,7 @@ export default defineEventHandler(async event => {
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) }
if (!score.pass) return { score, summary: summarize(await board(id), body.player, await playerNames()) }
const player = body.player
const summary = await locked(id, async () => {
const scores = await board(id)
@ -36,7 +36,7 @@ export default defineEventHandler(async event => {
scores[player] = { t: score.transistors, d: score.delay, at: Date.now() }
await puzzleStorage().setItem(`scores:${id}`, scores)
}
return summarize(scores, player)
return summarize(scores, player, await playerNames())
})
return { score, summary }
})

View File

@ -51,15 +51,37 @@ export interface Summary {
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 }
/** The best ten: fewest transistors, then shortest delay, then first to get there. */
top: { name: string; t: number; d: number | null; you?: true }[]
}
export function summarize(board: ScoreBoard, player?: string): Summary {
/** Names players chose for leaderboards, by player id. */
export async function playerNames(): Promise<Record<string, string>> {
return (await puzzleStorage().getItem<Record<string, string>>('players')) ?? {}
}
/** A leaderboard name: letters, digits, spaces and a little punctuation, at most 24 characters. */
export function cleanName(v: unknown): string {
if (typeof v !== 'string') return ''
return v
.normalize('NFC')
.replace(/[^\p{L}\p{N} ._\-'!?&+#]/gu, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 24)
}
export function summarize(board: ScoreBoard, player?: string, names: Record<string, 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 }
const top = Object.entries(board)
.sort(([, a], [, b]) => a.t - b.t || (a.d ?? Infinity) - (b.d ?? Infinity) || a.at - b.at)
.slice(0, 10)
.map(([id, e]) => ({ name: names[id] ?? '', t: e.t, d: e.d, ...(id === player ? { you: true as const } : {}) }))
const summary: Summary = { players: entries.length, histogram, top }
if (mine) summary.you = { t: mine.t, d: mine.d, rank: 1 + entries.filter(e => e.t < mine.t).length }
return summary
}

44
tests/leaderboard.test.ts Normal file
View File

@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { cleanName, summarize, type ScoreBoard } from '../server/utils/puzzles'
describe('leaderboard names', () => {
it('keeps letters, digits and a little punctuation', () => {
expect(cleanName(' Jörg der Elektriker ')).toBe('Jörg der Elektriker')
expect(cleanName('<script>alert(1)</script>')).toBe('scriptalert1script')
expect(cleanName("O'Neil #1 & co!")).toBe("O'Neil #1 & co!")
})
it('is at most 24 characters, and empty for anything but text', () => {
expect(cleanName('x'.repeat(40))).toHaveLength(24)
expect(cleanName(42)).toBe('')
expect(cleanName(null)).toBe('')
})
})
describe('leaderboard top ten', () => {
const board: ScoreBoard = {}
for (let i = 0; i < 14; i++) board[`player-${String(i).padStart(4, '0')}`] = { t: 40 + (i % 5) * 4, d: 10 - (i % 3), at: 1000 + i }
it('ranks fewest transistors, then shortest delay, then who got there first', () => {
const s = summarize(board, undefined, { 'player-0000': 'Ada' })
expect(s.players).toBe(14)
expect(s.top).toHaveLength(10)
// t = 40 for i = 0, 5, 10; delays 10, 8, 9.
expect(s.top.slice(0, 3).map(e => [e.t, e.d])).toEqual([
[40, 8],
[40, 9],
[40, 10],
])
expect(s.top[2]!.name).toBe('Ada')
expect(s.top[0]!.name).toBe('')
for (let i = 1; i < s.top.length; i++) expect(s.top[i]!.t).toBeGreaterThanOrEqual(s.top[i - 1]!.t)
})
it('marks your own entry and your place', () => {
const s = summarize(board, 'player-0004', {})
expect(s.you).toEqual({ t: 56, d: 9, rank: 13 })
expect(s.top.some(e => e.you)).toBe(false)
const t = summarize(board, 'player-0005', {})
expect(t.top.find(e => e.you)).toMatchObject({ t: 40, d: 8 })
})
})