V1.3.0
Game pack 3: 22 new games (19-40), 40 in total. - New engines: dial (Wavelength / Mind Meld), twin (Twin Rooms / Spot the Difference, incl. mirror mode) and blueprint (Describe & Draw, incl. peeks, overlap scoring and a rotated Builder canvas) - Labyrinth: items and doors (Hedge Maze) - Defuse: manualFrom, roles swapping every level behind a Ready card, and duplicate wire modules (Tick Tock: Switch) - Generic time limits for the new engines; sync/defuse successEnding - Library: engine-label chips and filters; Noto Color Emoji font - Validation: Appendix A checks ported, with a per-game summary - Quote comma/colon-split labels in five new YAMLs (wording unchanged) - Tests for all new engines and sanitized payloads of all 22 games - Docs: CLAUDE.md, GAMES.md (pack 3 spoiler guide), How to Play Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -9,7 +9,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Caveat:wght@500;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;700&family=Noto+Sans+Symbols+2&family=Playfair+Display:ital,wght@0,500;0,700;1,500&display=swap"
|
||||
href="https://fonts.googleapis.com/css2?family=Caveat:wght@500;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;700&family=Noto+Color+Emoji&family=Noto+Sans+Symbols+2&family=Playfair+Display:ital,wght@0,500;0,700;1,500&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<title>Two Keys · Co-op mysteries for couples</title>
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@two-keys/client",
|
||||
"version": "1.2.2",
|
||||
"version": "1.3.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { formatClock, type GameSummary, type PlayMode } from '@two-keys/shared';
|
||||
import { getBest, saveSession } from '../lib/session';
|
||||
import { request } from '../lib/socket';
|
||||
import { CATEGORY_LABEL, DIFFICULTY_LABEL, MAX_DIFFICULTY, difficultyKeys, themeVars } from '../lib/theme';
|
||||
import { DIFFICULTY_LABEL, MAX_DIFFICULTY, chipLabel, difficultyKeys, themeVars } from '../lib/theme';
|
||||
import { pushToast } from '../lib/toasts';
|
||||
import { RoleBadge, Sheet } from './ui';
|
||||
|
||||
@@ -12,6 +12,9 @@ const ENGINE_BLURB: Record<GameSummary['engine'], string> = {
|
||||
defuse: 'One sees it, one has the manual',
|
||||
sync: 'How well do you know each other?',
|
||||
labyrinth: 'One map, one explorer',
|
||||
dial: 'One clue, one dial',
|
||||
twin: 'Same room... almost',
|
||||
blueprint: 'One describes, one draws',
|
||||
};
|
||||
|
||||
/** A library card, themed with its game's own colours. Opens the "how do you want to play" sheet. */
|
||||
@@ -37,7 +40,7 @@ export function GameCard({ game, className = '' }: { game: GameSummary; classNam
|
||||
className="group flex h-full w-full flex-col rounded-2xl border border-white/10 bg-bg bg-gradient-to-br from-primary/60 via-primary/15 to-transparent p-5 text-left shadow-lg shadow-black/30 transition hover:-translate-y-0.5 hover:border-accent/60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="chip text-accent">{CATEGORY_LABEL[game.category]}</span>
|
||||
<span className="chip text-accent">{chipLabel(game)}</span>
|
||||
<span className="text-xs text-stone-300">⏱ {game.estimatedMinutes} min</span>
|
||||
<span
|
||||
className="text-xs"
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { BlueprintColor, BlueprintView, Role, RoomState } from '@two-keys/shared';
|
||||
import { otherRole } from '@two-keys/shared';
|
||||
import { useNow } from '../lib/hooks';
|
||||
import type { Send } from '../lib/socket';
|
||||
|
||||
interface Props {
|
||||
view: BlueprintView;
|
||||
state: RoomState;
|
||||
role: Role;
|
||||
receivedAt: number;
|
||||
send: Send;
|
||||
}
|
||||
|
||||
const EMPTY = '.';
|
||||
const UNDO_LIMIT = 20;
|
||||
type Cell = { x: number; y: number; color: string | null };
|
||||
|
||||
const formatSeconds = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
|
||||
const percent = (score: number) => `${Math.round(score * 100)}%`;
|
||||
|
||||
/**
|
||||
* The Builder's canvas is shown rotated clockwise. Displayed (column c, row r) on an n×n grid is
|
||||
* stored cell (x = r, y = n − 1 − c) for each 90°. The server stores and scores in target orientation.
|
||||
*/
|
||||
function toStored(n: number, rotate: number, c: number, r: number) {
|
||||
let p = { x: c, y: r };
|
||||
for (let turn = 0; turn < (rotate / 90) % 4; turn++) p = { x: p.y, y: n - 1 - p.x };
|
||||
return p;
|
||||
}
|
||||
|
||||
function useRemaining(view: BlueprintView, receivedAt: number) {
|
||||
const now = useNow(250);
|
||||
return view.status === 'building' ? Math.max(0, view.remaining - (now - receivedAt) / 1000) : view.remaining;
|
||||
}
|
||||
|
||||
/** One square grid. `cellAt` gets displayed coordinates; numbers run along the edges. */
|
||||
function Grid({
|
||||
size,
|
||||
label,
|
||||
cellAt,
|
||||
onPaint,
|
||||
gridlines = true,
|
||||
}: {
|
||||
size: number;
|
||||
label: string;
|
||||
cellAt: (c: number, r: number) => { fill: string | null; mark?: 'right' | 'wrong' | 'missed' };
|
||||
onPaint?: (c: number, r: number, start: boolean) => void;
|
||||
gridlines?: boolean;
|
||||
}) {
|
||||
const painting = useRef(false);
|
||||
const cellFromPoint = (x: number, y: number) => {
|
||||
const el = document.elementFromPoint(x, y) as HTMLElement | null;
|
||||
const c = Number(el?.dataset.c);
|
||||
const r = Number(el?.dataset.r);
|
||||
return Number.isInteger(c) && Number.isInteger(r) ? { c, r } : null;
|
||||
};
|
||||
return (
|
||||
<div className="mx-auto w-full" style={{ maxWidth: `${size * 44 + 20}px` }}>
|
||||
<div
|
||||
className={`grid gap-px ${onPaint ? 'touch-none select-none' : ''}`}
|
||||
style={{ gridTemplateColumns: `16px repeat(${size}, minmax(0, 1fr))` }}
|
||||
role="grid"
|
||||
aria-label={label}
|
||||
onPointerUp={() => (painting.current = false)}
|
||||
onPointerLeave={() => (painting.current = false)}
|
||||
onPointerCancel={() => (painting.current = false)}
|
||||
onPointerMove={(e) => {
|
||||
if (!painting.current || !onPaint) return;
|
||||
const hit = cellFromPoint(e.clientX, e.clientY);
|
||||
if (hit) onPaint(hit.c, hit.r, false);
|
||||
}}
|
||||
>
|
||||
<span aria-hidden />
|
||||
{Array.from({ length: size }, (_, c) => (
|
||||
<span key={c} className="text-center font-mono text-[10px] text-stone-500" aria-hidden>
|
||||
{c + 1}
|
||||
</span>
|
||||
))}
|
||||
{Array.from({ length: size }, (_, r) => (
|
||||
<div key={r} role="row" className="contents">
|
||||
<span className="flex items-center font-mono text-[10px] text-stone-500" aria-hidden>
|
||||
{r + 1}
|
||||
</span>
|
||||
{Array.from({ length: size }, (_, c) => {
|
||||
const { fill, mark } = cellAt(c, r);
|
||||
const ring =
|
||||
mark === 'right' ? 'ring-2 ring-inset ring-emerald-400' : mark === 'wrong' ? 'ring-2 ring-inset ring-red-500' : mark === 'missed' ? 'outline outline-2 -outline-offset-2 outline-dashed outline-amber-300' : '';
|
||||
return (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
role="gridcell"
|
||||
data-c={c}
|
||||
data-r={r}
|
||||
tabIndex={onPaint ? 0 : -1}
|
||||
disabled={!onPaint}
|
||||
aria-label={`Row ${r + 1}, column ${c + 1}${fill ? '' : ', empty'}`}
|
||||
onPointerDown={(e) => {
|
||||
if (!onPaint) return;
|
||||
e.preventDefault();
|
||||
// A drag keeps painting: moves are hit-tested by position, wherever the pointer is captured.
|
||||
painting.current = true;
|
||||
onPaint(c, r, true);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (onPaint && (e.key === 'Enter' || e.key === ' ')) {
|
||||
e.preventDefault();
|
||||
onPaint(c, r, true);
|
||||
}
|
||||
}}
|
||||
className={`aspect-square min-h-[24px] ${gridlines ? 'border border-white/10' : ''} ${ring} disabled:cursor-default`}
|
||||
style={{ backgroundColor: fill ?? 'rgb(255 255 255 / 0.04)' }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Palette({ palette, color, onPick }: { palette: BlueprintColor[]; color: string | null; onPick: (c: string | null) => void }) {
|
||||
return (
|
||||
<div className="flex flex-wrap justify-center gap-2" role="radiogroup" aria-label="Colour">
|
||||
{palette.map((p) => (
|
||||
<button
|
||||
key={p.key}
|
||||
role="radio"
|
||||
aria-checked={color === p.key}
|
||||
onClick={() => onPick(p.key)}
|
||||
className={`flex min-h-[44px] items-center gap-2 rounded-xl border px-3 py-1.5 text-sm font-semibold ${color === p.key ? 'border-accent bg-accent/20' : 'border-white/15 bg-white/5'}`}
|
||||
>
|
||||
<span className="h-5 w-5 rounded border border-white/30" style={{ backgroundColor: p.hex }} aria-hidden />
|
||||
{p.name}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
role="radio"
|
||||
aria-checked={color === null}
|
||||
onClick={() => onPick(null)}
|
||||
className={`flex min-h-[44px] items-center gap-2 rounded-xl border px-3 py-1.5 text-sm font-semibold ${color === null ? 'border-accent bg-accent/20' : 'border-white/15 bg-white/5'}`}
|
||||
>
|
||||
<span aria-hidden>🧽</span> Eraser
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The Builder's side: the canvas lives here and goes to the server in small debounced batches. */
|
||||
function Builder({ view, send, remaining }: { view: BlueprintView; send: Send; remaining: number }) {
|
||||
const n = view.pattern.size;
|
||||
const [canvas, setCanvasState] = useState<string[]>(() => view.canvas ?? Array.from({ length: n }, () => EMPTY.repeat(n)));
|
||||
// Pointer events can arrive faster than renders, so painting reads the latest canvas from a ref.
|
||||
const latest = useRef(canvas);
|
||||
const setCanvas = (next: string[]) => {
|
||||
latest.current = next;
|
||||
setCanvasState(next);
|
||||
};
|
||||
const [color, setColor] = useState<string | null>(view.palette[0]?.key ?? null);
|
||||
const [undo, setUndo] = useState<string[][]>([]);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const queue = useRef(new Map<string, Cell>());
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
/** Whether this stroke has already saved an undo step. */
|
||||
const stroke = useRef(false);
|
||||
const hex = Object.fromEntries(view.palette.map((p) => [p.key, p.hex]));
|
||||
const pushUndo = (snapshot: string[]) => setUndo((u) => [...u.slice(-(UNDO_LIMIT - 1)), snapshot]);
|
||||
|
||||
const flush = () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
if (queue.current.size === 0) return;
|
||||
send('blueprint:paint', { cells: [...queue.current.values()] });
|
||||
queue.current.clear();
|
||||
};
|
||||
useEffect(() => () => flush(), []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const apply = (cells: Cell[], next: string[]) => {
|
||||
for (const cell of cells) queue.current.set(`${cell.x},${cell.y}`, cell);
|
||||
setCanvas(next);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(flush, 250);
|
||||
};
|
||||
|
||||
const paintAt = (c: number, r: number) => {
|
||||
const { x, y } = toStored(n, view.rotateBuilder, c, r);
|
||||
const value = color ?? EMPTY;
|
||||
const current = latest.current;
|
||||
if (current[y][x] === value) return;
|
||||
// One undo step per stroke.
|
||||
if (!stroke.current) pushUndo(current);
|
||||
stroke.current = true;
|
||||
const next = current.map((row, ry) => (ry === y ? row.slice(0, x) + value + row.slice(x + 1) : row));
|
||||
apply([{ x, y, color }], next);
|
||||
};
|
||||
|
||||
const restore = (target: string[]) => {
|
||||
const current = latest.current;
|
||||
const cells: Cell[] = [];
|
||||
target.forEach((row, y) => [...row].forEach((v, x) => v !== current[y][x] && cells.push({ x, y, color: v === EMPTY ? null : v })));
|
||||
if (cells.length > 0) apply(cells, target);
|
||||
};
|
||||
|
||||
const submit = () => {
|
||||
flush();
|
||||
setConfirming(false);
|
||||
send('blueprint:submit');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Grid
|
||||
size={n}
|
||||
label={`Your canvas${view.rotateBuilder ? `, turned ${view.rotateBuilder}° clockwise` : ''}`}
|
||||
cellAt={(c, r) => {
|
||||
const { x, y } = toStored(n, view.rotateBuilder, c, r);
|
||||
const v = canvas[y][x];
|
||||
return { fill: v === EMPTY ? null : hex[v] };
|
||||
}}
|
||||
onPaint={(c, r, start) => {
|
||||
if (start) stroke.current = false;
|
||||
paintAt(c, r);
|
||||
}}
|
||||
/>
|
||||
<Palette palette={view.palette} color={color} onPick={setColor} />
|
||||
<div className="flex gap-2">
|
||||
<button className="btn flex-1" disabled={undo.length === 0} onClick={() => { restore(undo[undo.length - 1]); setUndo((u) => u.slice(0, -1)); }}>
|
||||
↶ Undo
|
||||
</button>
|
||||
<button
|
||||
className="btn flex-1"
|
||||
onClick={() => {
|
||||
pushUndo(latest.current);
|
||||
restore(Array.from({ length: n }, () => EMPTY.repeat(n)));
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
{confirming ? (
|
||||
<div className="rounded-2xl border border-accent/50 bg-accent/10 p-4 text-center">
|
||||
<p className="font-semibold">
|
||||
Submit this canvas?{' '}
|
||||
{view.submitsLeft > 1 ? `You have ${view.submitsLeft} tries; the best counts.` : "It's your only try."}
|
||||
</p>
|
||||
<div className="mt-3 flex justify-center gap-2">
|
||||
<button className="btn-primary" onClick={submit}>Yes, score it</button>
|
||||
<button className="btn" onClick={() => setConfirming(false)}>Keep painting</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button className="btn-primary w-full" onClick={() => setConfirming(true)} disabled={remaining <= 0}>
|
||||
Submit ({view.submitsLeft} {view.submitsLeft === 1 ? 'try' : 'tries'} left)
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BlueprintGame({ view, state, role, receivedAt, send }: Props) {
|
||||
const roles = state.game.roles;
|
||||
const partnerName = roles[otherRole(role)].name;
|
||||
const architect = view.seat === 'architect';
|
||||
const remaining = useRemaining(view, receivedAt);
|
||||
const now = useNow(200);
|
||||
const n = view.pattern.size;
|
||||
const hex = Object.fromEntries(view.palette.map((p) => [p.key, p.hex]));
|
||||
// A peek lasts until the server's peekUntil, measured on this device's clock.
|
||||
const peekOn = view.peekUntil !== null && view.canvas !== null && now - receivedAt < view.peekUntil - state.timer.serverNow;
|
||||
const seatName = architect ? 'Architect' : 'Builder';
|
||||
|
||||
const header = (
|
||||
<div className="text-center">
|
||||
<div className="text-xs font-bold uppercase tracking-widest text-accent">
|
||||
Picture {view.pattern.index + 1} of {view.pattern.total}
|
||||
</div>
|
||||
<div className="font-display text-3xl font-bold uppercase tracking-wide">
|
||||
You're the <span className="text-accent">{seatName}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (view.status === 'ready') {
|
||||
return (
|
||||
<div className="space-y-5 text-center">
|
||||
{header}
|
||||
<div className="text-6xl" aria-hidden>{architect ? '📐' : '🖌️'}</div>
|
||||
<p className="text-stone-200">
|
||||
{architect
|
||||
? `You see the picture. Describe it to ${partnerName}, square by square. You can't see their canvas${view.peeksLeft > 0 ? `, except with a peek (${view.peeksLeft} for this picture)` : ''}.`
|
||||
: `${partnerName} sees a picture you can't. Paint it from their description alone.${view.rotateBuilder ? ` Your canvas is turned ${view.rotateBuilder}° clockwise!` : ''}`}
|
||||
</p>
|
||||
<p className="text-sm text-stone-400">
|
||||
{n}×{n} grid, {formatSeconds(view.timeSeconds)}. Match {percent(view.threshold)} of the painted squares to earn the {view.pattern.keyName}.
|
||||
</p>
|
||||
<button className="btn-primary w-full" onClick={() => send('chapter:continue')}>
|
||||
Start the clock ⏱
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const status = (
|
||||
<div className="flex items-center justify-between gap-3 text-sm">
|
||||
<div>
|
||||
Need <strong>{percent(view.threshold)}</strong>
|
||||
{view.bestScore !== null && <span className="text-stone-400"> · best {percent(view.bestScore)}</span>}
|
||||
</div>
|
||||
<div
|
||||
className={`rounded-lg border px-3 py-1 font-mono text-xl font-bold tabular-nums ${remaining <= 20 && view.status === 'building' ? 'border-red-400 text-red-300' : 'border-white/15'}`}
|
||||
role="timer"
|
||||
aria-label={`${formatSeconds(remaining)} left for this picture`}
|
||||
>
|
||||
{formatSeconds(remaining)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (view.status === 'scored' && view.target && view.canvas) {
|
||||
const target = view.target;
|
||||
const canvas = view.canvas;
|
||||
// On the Builder's screen the reveal keeps the Builder's orientation.
|
||||
const rotate = architect ? 0 : view.rotateBuilder;
|
||||
return (
|
||||
<div className="space-y-4" aria-live="polite">
|
||||
{header}
|
||||
<div className={`rounded-2xl border-2 p-4 text-center ${view.passed ? 'border-emerald-500/70 bg-emerald-950/50' : 'border-red-500/70 bg-red-950/50'}`}>
|
||||
<div className="text-xs font-bold uppercase tracking-widest text-stone-300">It was…</div>
|
||||
<h3 className="font-display text-2xl font-bold">{view.title}</h3>
|
||||
<p className="mt-1 text-3xl font-bold">{percent(view.bestScore ?? 0)}</p>
|
||||
<p className="text-stone-300">{view.passed ? `🔑 ${view.pattern.keyName}!` : `Needed ${percent(view.threshold)}. No key this time.`}</p>
|
||||
</div>
|
||||
<Grid
|
||||
size={n}
|
||||
label="The picture over the canvas: green is right, red is wrong, dashed was missed"
|
||||
cellAt={(c, r) => {
|
||||
const { x, y } = toStored(n, rotate, c, r);
|
||||
const t = target[y][x];
|
||||
const p = canvas[y][x];
|
||||
if (p !== EMPTY) return { fill: hex[p], mark: p === t ? 'right' : 'wrong' };
|
||||
return { fill: null, mark: t !== EMPTY ? 'missed' : undefined };
|
||||
}}
|
||||
/>
|
||||
<p className="text-center text-xs text-stone-400">Green: right. Red: wrong colour or shouldn't be painted. Dashed: missed.</p>
|
||||
<button className="btn-primary w-full" onClick={() => send('chapter:continue')}>
|
||||
{view.pattern.index === view.pattern.total - 1 ? 'See how we did →' : 'Next picture →'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{header}
|
||||
{status}
|
||||
{view.lastScore !== null && (
|
||||
<p className="text-center text-sm text-amber-200">Last try: {percent(view.lastScore)}. Keep going!</p>
|
||||
)}
|
||||
{architect && view.target ? (
|
||||
<>
|
||||
<Grid size={n} label="The picture to describe" cellAt={(c, r) => ({ fill: view.target![r][c] === EMPTY ? null : hex[view.target![r][c]] })} />
|
||||
<ul className="flex flex-wrap justify-center gap-2 text-sm">
|
||||
{view.palette.map((p) => (
|
||||
<li key={p.key} className="chip">
|
||||
<span className="mr-1 inline-block h-3 w-3 rounded-sm align-middle" style={{ backgroundColor: p.hex }} aria-hidden />
|
||||
{p.name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{peekOn && view.canvas ? (
|
||||
<div className="rounded-2xl border border-accent/50 bg-accent/10 p-3">
|
||||
<p className="mb-2 text-center text-sm font-semibold text-accent">👀 Their canvas right now</p>
|
||||
<Grid size={n} label="The Builder's canvas" cellAt={(c, r) => ({ fill: view.canvas![r][c] === EMPTY ? null : hex[view.canvas![r][c]] })} />
|
||||
</div>
|
||||
) : (
|
||||
<button className="btn w-full" disabled={view.peeksLeft === 0} onClick={() => send('blueprint:peek')}>
|
||||
👀 Peek at their canvas for 3s ({view.peeksLeft} left)
|
||||
</button>
|
||||
)}
|
||||
<p className="text-center text-sm text-stone-400">
|
||||
Describe it out loud: rows, columns, colours. {partnerName} submits when you're both happy.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<Builder key={`${view.pattern.index}`} view={view} send={send} remaining={remaining} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
TechnicianView,
|
||||
WiresModuleView,
|
||||
} from '@two-keys/shared';
|
||||
import { otherRole } from '@two-keys/shared';
|
||||
import { SignalLamp } from '../components/ClueCard';
|
||||
import { Markdown } from '../components/ui';
|
||||
import { useNow } from '../lib/hooks';
|
||||
@@ -99,7 +100,7 @@ function ModuleFrame({ title, solved, children }: { title: string; solved: boole
|
||||
|
||||
function Wires({ module, act }: { module: WiresModuleView; act: (a: DefuseAction) => void }) {
|
||||
return (
|
||||
<ModuleFrame title="Wires" solved={module.solved}>
|
||||
<ModuleFrame title={module.title} solved={module.solved}>
|
||||
<ol className="space-y-2">
|
||||
{module.wires.map((color, i) => (
|
||||
<li key={i} className="flex items-center gap-2">
|
||||
@@ -359,7 +360,7 @@ function Device({ view, send }: { view: TechnicianView; send: Send }) {
|
||||
{modules.map((m) => {
|
||||
switch (m.id) {
|
||||
case 'wires':
|
||||
return <Wires key={m.id} module={m} act={act(m.id)} />;
|
||||
return <Wires key={m.instance} module={m} act={act(m.instance)} />;
|
||||
case 'button':
|
||||
return <BigButton key={m.id} module={m} act={act(m.id)} />;
|
||||
case 'keypad':
|
||||
@@ -379,10 +380,41 @@ function Device({ view, send }: { view: TechnicianView; send: Send }) {
|
||||
export function DefuseGame({ view, state, receivedAt, send }: Props) {
|
||||
const remaining = useRemaining(view, receivedAt);
|
||||
const technician = view.seat === 'technician';
|
||||
const partner = state.game.roles[technician ? 'B' : 'A'].name;
|
||||
// Roles can swap every level, so the partner is whoever doesn't hold the seat you hold now.
|
||||
const partner = state.game.roles[technician ? otherRole(view.technician) : view.technician].name;
|
||||
const seatName = technician ? 'Technician' : 'Expert';
|
||||
|
||||
let banner = null;
|
||||
if (view.status === 'ready') {
|
||||
if (view.status === 'ready' && view.swapRoles) {
|
||||
const swapped = view.level.index > 0;
|
||||
banner = (
|
||||
<div className="card flex min-h-[60vh] flex-col items-center justify-center text-center" aria-live="polite">
|
||||
<div className="text-6xl" aria-hidden>{swapped ? '🔄' : technician ? '🧰' : '📖'}</div>
|
||||
<h2 className="mt-3 font-display text-3xl font-bold">
|
||||
{swapped ? 'Swap! ' : ''}You're {swapped ? 'now ' : ''}the <span className="text-accent">{seatName}</span>
|
||||
</h2>
|
||||
<p className="mt-2 text-stone-300">
|
||||
Level {view.level.index + 1} of {view.level.total}: {view.level.title}. {timerText(view.level.timeSeconds)} on the clock,{' '}
|
||||
{view.maxStrikes} {view.maxStrikes === 1 ? 'strike' : 'strikes'} and it's over.
|
||||
</p>
|
||||
<p className="mt-3 text-sm text-stone-400">
|
||||
{technician
|
||||
? `You'll see the device. Describe everything to the ${partner}.`
|
||||
: `You have the manual. Ask the ${partner} for the serial number and battery count first.`}
|
||||
</p>
|
||||
<button
|
||||
className={`${view.swapReady.you ? 'btn' : 'btn-primary'} mt-5 w-full max-w-xs`}
|
||||
aria-pressed={view.swapReady.you}
|
||||
onClick={() => send('level:ready')}
|
||||
>
|
||||
{view.swapReady.you ? '✓ Ready (tap to undo)' : 'Ready'}
|
||||
</button>
|
||||
<p className="mt-2 text-sm text-stone-400">
|
||||
{view.swapReady.partner ? `${partner} is ready.` : `Waiting for ${partner}…`} The clock starts when you both are.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
} else if (view.status === 'ready') {
|
||||
banner = (
|
||||
<div className="card text-center">
|
||||
<div className="text-5xl" aria-hidden>💣</div>
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import { useEffect, useRef, useState, type FormEvent, type KeyboardEvent, type PointerEvent } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { DialView, Role, RoomState } from '@two-keys/shared';
|
||||
import { otherRole } from '@two-keys/shared';
|
||||
import type { Send } from '../lib/socket';
|
||||
|
||||
interface Props {
|
||||
view: DialView;
|
||||
state: RoomState;
|
||||
role: Role;
|
||||
send: Send;
|
||||
}
|
||||
|
||||
// The dial is a half circle: the range's low end on the left, high end on the right.
|
||||
const W = 300;
|
||||
const CX = 150;
|
||||
const CY = 150;
|
||||
const R = 130;
|
||||
const STATIC = '▒▒▒ static ▒▒▒';
|
||||
// Narrowest band first: 4 points, 3, 2, 1.
|
||||
const BAND_COLORS = ['rgb(var(--accent))', 'rgb(var(--accent) / 0.6)', 'rgb(var(--accent) / 0.35)', 'rgb(var(--accent) / 0.18)'];
|
||||
|
||||
function useDial(range: [number, number]) {
|
||||
const [lo, hi] = range;
|
||||
const angle = (v: number) => Math.PI * (1 - (v - lo) / (hi - lo));
|
||||
const point = (v: number, r = R) => ({ x: CX + r * Math.cos(angle(v)), y: CY - r * Math.sin(angle(v)) });
|
||||
/** A pie slice from value a to value b. */
|
||||
const wedge = (a: number, b: number) => {
|
||||
const [from, to] = [Math.max(lo, a), Math.min(hi, b)];
|
||||
const p1 = point(from);
|
||||
const p2 = point(to);
|
||||
return `M ${CX} ${CY} L ${p1.x} ${p1.y} A ${R} ${R} 0 0 1 ${p2.x} ${p2.y} Z`;
|
||||
};
|
||||
const clamp = (v: number) => Math.min(hi, Math.max(lo, Math.round(v)));
|
||||
return { lo, hi, point, wedge, clamp };
|
||||
}
|
||||
|
||||
function Dial({
|
||||
view,
|
||||
needle,
|
||||
onNeedle,
|
||||
interactive,
|
||||
}: {
|
||||
view: DialView;
|
||||
needle: number | null;
|
||||
onNeedle?: (value: number) => void;
|
||||
interactive: boolean;
|
||||
}) {
|
||||
const { lo, hi, point, wedge, clamp } = useDial(view.range);
|
||||
const svg = useRef<SVGSVGElement>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const showTarget = view.target !== null;
|
||||
|
||||
const fromPointer = (e: PointerEvent) => {
|
||||
const box = svg.current?.getBoundingClientRect();
|
||||
if (!box || !onNeedle) return;
|
||||
const x = ((e.clientX - box.left) / box.width) * W - CX;
|
||||
const y = CY - ((e.clientY - box.top) / box.width) * W;
|
||||
const a = Math.atan2(Math.max(y, 0), x); // 0 (right) .. π (left)
|
||||
onNeedle(clamp(lo + (1 - a / Math.PI) * (hi - lo)));
|
||||
};
|
||||
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (!onNeedle || needle === null) return;
|
||||
const step = e.shiftKey ? 5 : 1;
|
||||
const next = { ArrowLeft: -step, ArrowDown: -step, ArrowRight: step, ArrowUp: step, Home: lo - needle, End: hi - needle }[e.key];
|
||||
if (next === undefined) return;
|
||||
e.preventDefault();
|
||||
onNeedle(clamp(needle + next));
|
||||
};
|
||||
|
||||
const tip = needle !== null ? point(needle, R - 6) : null;
|
||||
const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => lo + f * (hi - lo));
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-md">
|
||||
<svg
|
||||
ref={svg}
|
||||
viewBox={`0 0 ${W} ${CY + 24}`}
|
||||
className={`w-full select-none ${interactive ? 'cursor-pointer touch-none' : ''}`}
|
||||
role={interactive ? 'slider' : 'img'}
|
||||
tabIndex={interactive ? 0 : undefined}
|
||||
aria-label={interactive ? 'Dial' : showTarget ? `Dial, target at ${view.target}` : 'Dial'}
|
||||
aria-valuemin={interactive ? lo : undefined}
|
||||
aria-valuemax={interactive ? hi : undefined}
|
||||
aria-valuenow={interactive && needle !== null ? needle : undefined}
|
||||
onKeyDown={interactive ? onKey : undefined}
|
||||
onPointerDown={(e) => {
|
||||
if (!interactive) return;
|
||||
(e.currentTarget as Element).setPointerCapture(e.pointerId);
|
||||
setDragging(true);
|
||||
fromPointer(e);
|
||||
}}
|
||||
onPointerMove={(e) => dragging && fromPointer(e)}
|
||||
onPointerUp={() => setDragging(false)}
|
||||
onPointerCancel={() => setDragging(false)}
|
||||
>
|
||||
<path d={wedge(lo, hi)} fill="rgb(255 255 255 / 0.06)" stroke="rgb(255 255 255 / 0.2)" />
|
||||
{showTarget &&
|
||||
[...view.bands]
|
||||
.map((b, i) => ({ ...b, color: BAND_COLORS[i] ?? BAND_COLORS[BAND_COLORS.length - 1] }))
|
||||
.reverse()
|
||||
.map((b) => (
|
||||
<motion.path
|
||||
key={b.within}
|
||||
d={wedge(view.target! - b.within - 0.5, view.target! + b.within + 0.5)}
|
||||
fill={b.color}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.6 }}
|
||||
/>
|
||||
))}
|
||||
{showTarget &&
|
||||
view.bands.map((b, i) => {
|
||||
const prev = i === 0 ? 0 : view.bands[i - 1].within;
|
||||
const mid = view.target! + (prev + b.within) / 2 + 0.5;
|
||||
if (mid > hi) return null;
|
||||
const p = point(mid, R * 0.82);
|
||||
return (
|
||||
<text key={b.within} x={p.x} y={p.y} textAnchor="middle" dominantBaseline="middle" className="fill-stone-950 text-[9px] font-bold">
|
||||
{b.points}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
{view.showNumbers &&
|
||||
ticks.map((t) => {
|
||||
const p = point(t, R + 11);
|
||||
return (
|
||||
<text key={t} x={p.x} y={Math.min(p.y, CY + 14)} textAnchor="middle" className="fill-stone-400 text-[10px]">
|
||||
{Math.round(t)}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
{tip && (
|
||||
<g>
|
||||
<line x1={CX} y1={CY} x2={tip.x} y2={tip.y} stroke="#f5f5f4" strokeWidth={4} strokeLinecap="round" />
|
||||
<circle cx={CX} cy={CY} r={9} fill="#f5f5f4" />
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
<div className="mt-1 flex justify-between gap-4 text-sm font-semibold">
|
||||
<span className="max-w-[45%]">← {view.left ?? STATIC}</span>
|
||||
<span className="max-w-[45%] text-right">{view.right ?? STATIC} →</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KeyProgress({ view }: { view: DialView }) {
|
||||
const pct = (n: number) => `${Math.min(100, (n / view.maxTotal) * 100)}%`;
|
||||
return (
|
||||
<div aria-label={`${view.total} points. Keys at ${view.keys.map((k) => k.at).join(', ')}.`}>
|
||||
<div className="flex items-baseline justify-between text-sm">
|
||||
<span className="font-bold">{view.total} points</span>
|
||||
<span className="text-stone-400">Round {view.round + 1} of {view.rounds}</span>
|
||||
</div>
|
||||
<div className="relative mt-1 h-2.5 rounded-full bg-white/10">
|
||||
<motion.div className="h-full rounded-full bg-accent" animate={{ width: pct(view.total) }} />
|
||||
{view.keys.map((k) => (
|
||||
<span
|
||||
key={k.at}
|
||||
className={`absolute -top-2 -translate-x-1/2 text-base ${k.earned ? '' : 'opacity-40 grayscale'}`}
|
||||
style={{ left: pct(k.at) }}
|
||||
title={`${k.name}: ${k.at} points`}
|
||||
aria-hidden
|
||||
>
|
||||
🔑
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ClueForm({ view, send }: { view: DialView; send: Send }) {
|
||||
const [text, setText] = useState('');
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (text.trim()) send('dial:clue', { text: text.trim() });
|
||||
};
|
||||
const { maxWords, maxChars, banLabelWords, noRepeatWords } = view.rules;
|
||||
return (
|
||||
<form onSubmit={submit} className="space-y-2">
|
||||
<label htmlFor="dial-clue" className="block text-sm font-semibold">
|
||||
Your clue: something that sits right at the target
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id="dial-clue"
|
||||
className="field text-lg"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
maxLength={maxChars}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder={maxWords === 1 ? 'One word' : `Up to ${maxWords} words`}
|
||||
/>
|
||||
<button type="submit" className="btn-primary shrink-0" disabled={!text.trim()}>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-stone-400">
|
||||
{maxWords === 1 ? 'Exactly one word' : `Up to ${maxWords} words`}, {maxChars} characters.
|
||||
{banLabelWords && ' No words from the dial labels.'}
|
||||
{noRepeatWords && ' No word used earlier in the game.'}
|
||||
</p>
|
||||
{noRepeatWords && view.usedWords.length > 0 && (
|
||||
<p className="text-xs text-stone-500">Used: {view.usedWords.join(', ').toLowerCase()}</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function DialGame({ view, state, role, send }: Props) {
|
||||
const roles = state.game.roles;
|
||||
const partnerName = roles[otherRole(role)].name;
|
||||
const giverName = roles[view.giver].name;
|
||||
const [needle, setNeedle] = useState<number>(view.needle ?? Math.round((view.range[0] + view.range[1]) / 2));
|
||||
const lastSent = useRef(0);
|
||||
const pending = useRef<number | null>(null);
|
||||
|
||||
// A new round starts the needle in the middle again (or where the server says it was).
|
||||
useEffect(() => {
|
||||
setNeedle(view.needle ?? Math.round((view.range[0] + view.range[1]) / 2));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [view.round]);
|
||||
|
||||
// Throttled: the server keeps the needle for a refresh, and never shows it to the clue-giver.
|
||||
const moveNeedle = (value: number) => {
|
||||
setNeedle(value);
|
||||
pending.current = value;
|
||||
const now = Date.now();
|
||||
if (now - lastSent.current > 400) {
|
||||
lastSent.current = now;
|
||||
send('dial:needle', { value });
|
||||
pending.current = null;
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => {
|
||||
if (pending.current !== null) {
|
||||
send('dial:needle', { value: pending.current });
|
||||
lastSent.current = Date.now();
|
||||
pending.current = null;
|
||||
}
|
||||
}, 600);
|
||||
return () => clearInterval(t);
|
||||
}, [send]);
|
||||
|
||||
const last = view.round === view.rounds - 1;
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="text-center">
|
||||
<div className="text-xs font-bold uppercase tracking-widest text-accent">
|
||||
{view.iAmGiver ? 'You give the clue' : `${giverName} gives the clue`}
|
||||
</div>
|
||||
</div>
|
||||
<KeyProgress view={view} />
|
||||
|
||||
{view.status === 'clue' && view.iAmGiver && (
|
||||
<>
|
||||
<Dial view={view} needle={null} interactive={false} />
|
||||
<p className="text-center text-sm text-stone-400">Only you can see the target. {partnerName} will turn the dial from your clue.</p>
|
||||
<ClueForm key={view.round} view={view} send={send} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{view.status === 'clue' && !view.iAmGiver && (
|
||||
<>
|
||||
<Dial view={view} needle={null} interactive={false} />
|
||||
<p className="card text-center text-stone-300" aria-live="polite">
|
||||
{giverName} is thinking of a clue… 🤔
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view.status === 'guess' && (
|
||||
<div className="card text-center">
|
||||
<div className="text-xs font-semibold uppercase tracking-widest text-stone-400">The clue</div>
|
||||
<p className="mt-1 font-display text-3xl font-bold">“{view.clue}”</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{view.status === 'guess' && view.iAmGiver && (
|
||||
<>
|
||||
<Dial view={view} needle={null} interactive={false} />
|
||||
<p className="text-center text-sm text-stone-400" aria-live="polite">
|
||||
{partnerName} is turning the dial. 🤫 No hints, no faces!
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view.status === 'guess' && !view.iAmGiver && (
|
||||
<>
|
||||
<p className="text-center text-sm font-semibold text-accent">🤫 Clue only! Drag the needle (or use the arrow keys).</p>
|
||||
<Dial view={view} needle={needle} onNeedle={moveNeedle} interactive />
|
||||
{view.showNumbers && <p className="text-center font-mono text-2xl font-bold tabular-nums">{needle}</p>}
|
||||
<button className="btn-primary w-full" onClick={() => send('dial:lock', { value: needle })}>
|
||||
Lock in 🔒
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view.status === 'reveal' && (
|
||||
<div className="space-y-4" aria-live="polite">
|
||||
<Dial view={view} needle={view.guess} interactive={false} />
|
||||
<motion.div
|
||||
className="text-center"
|
||||
initial={{ opacity: 0, y: 8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<p className="font-display text-3xl font-bold">
|
||||
{view.points ? `+${view.points} point${view.points === 1 ? '' : 's'}` : 'No points'}
|
||||
</p>
|
||||
<p className="mt-1 text-stone-300">
|
||||
Target {view.target}, guess {view.guess}: {Math.abs((view.target ?? 0) - (view.guess ?? 0))} away.
|
||||
</p>
|
||||
</motion.div>
|
||||
<button className="btn-primary w-full" onClick={() => send('chapter:continue')}>
|
||||
{last ? 'See how we did →' : 'Next round →'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{view.history.length > 0 && (
|
||||
<details className="card text-sm">
|
||||
<summary className="cursor-pointer font-semibold">Rounds so far</summary>
|
||||
<ol className="mt-2 space-y-1 text-stone-300">
|
||||
{view.history.map((h, i) => (
|
||||
<li key={i}>
|
||||
{i + 1}. {h.left} ↔ {h.right}: “{h.clue}” ({roles[h.giver].name}). Target {h.target}, guess {h.guess},{' '}
|
||||
<strong>{h.points} pts</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,8 @@ function NavigatorMap({ view, explorerName }: { view: NavigatorView; explorerNam
|
||||
const gateAt = new Map(view.oneWay.map((g) => [`${g.x},${g.y}`, g]));
|
||||
const glyphAt = new Map(view.glyphs.map((g) => [`${g.x},${g.y}`, g]));
|
||||
const lanternAt = new Map(view.lanterns.map((l) => [`${l.x},${l.y}`, l]));
|
||||
const itemAt = new Map(view.items.map((it) => [`${it.x},${it.y}`, it]));
|
||||
const doorAt = new Map(view.doors.map((d) => [`${d.x},${d.y}`, d]));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -66,8 +68,10 @@ function NavigatorMap({ view, explorerName }: { view: NavigatorView; explorerNam
|
||||
let tone = 'bg-stone-800/40';
|
||||
if (cell === '#') tone = 'bg-stone-700';
|
||||
else if (cell === 'T') { content = '☠'; tone = 'bg-red-950 text-red-400'; }
|
||||
else if (cell === 'E') { content = '🚪'; tone = 'bg-emerald-950'; }
|
||||
else if (cell === 'E') { content = view.doors.length > 0 ? '🟩' : '🚪'; tone = 'bg-emerald-950'; }
|
||||
else if (lantern) { content = '🏮'; tone = lantern.collected ? 'bg-stone-800/40 opacity-30 grayscale' : 'bg-amber-950'; }
|
||||
else if (doorAt.has(key)) { content = '🚪'; tone = 'bg-amber-900/60'; }
|
||||
else if (itemAt.has(key)) { content = '🗝'; tone = itemAt.get(key)!.collected ? 'bg-stone-800/40 opacity-30 grayscale' : 'bg-yellow-900/60'; }
|
||||
else if (glyph) content = splitLabel(glyph.label)[0];
|
||||
const gate = gateAt.get(key);
|
||||
if (gate && cell !== '#') {
|
||||
@@ -106,11 +110,24 @@ function NavigatorMap({ view, explorerName }: { view: NavigatorView; explorerNam
|
||||
{l.collected && <span className="no-underline"> ✓</span>}
|
||||
</li>
|
||||
))}
|
||||
{view.items.map((it) => (
|
||||
<li key={it.name} className={`flex gap-2 ${it.collected ? 'text-stone-500 line-through' : ''}`}>
|
||||
<span className="w-6 text-center" aria-hidden>🗝</span>
|
||||
{it.name}
|
||||
{it.collected && <span className="no-underline"> ✓</span>}
|
||||
</li>
|
||||
))}
|
||||
{view.doors.map((d) => (
|
||||
<li key={d.name} className="flex gap-2">
|
||||
<span className="w-6 text-center" aria-hidden>🚪</span>
|
||||
{d.name}: shut until they carry its key
|
||||
</li>
|
||||
))}
|
||||
{view.oneWay.length > 0 && (
|
||||
<li className="flex gap-2 text-accent"><span className="w-6 text-center" aria-hidden>→</span>One-way gate. Only opens the way the arrow points.</li>
|
||||
)}
|
||||
<li className="flex gap-2 text-red-300"><span className="w-6 text-center" aria-hidden>☠</span>Trap. They can't see it!</li>
|
||||
<li className="flex gap-2"><span className="w-6 text-center" aria-hidden>🚪</span>Exit (needs all {view.totalKeys} lanterns)</li>
|
||||
<li className="flex gap-2"><span className="w-6 text-center" aria-hidden>{view.doors.length > 0 ? '🟩' : '🚪'}</span>Exit (needs all {view.totalKeys} lanterns)</li>
|
||||
<li className="flex gap-2 text-stone-400"><span className="w-6 text-center" aria-hidden>▪</span>Most floor is bare stone</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -163,6 +180,14 @@ function ExplorerCell({ view, send, navigatorName }: { view: ExplorerView; send:
|
||||
<Lanterns carried={view.keysCarried} total={view.totalKeys} />
|
||||
<div className="text-sm text-stone-300">{view.moves} moves</div>
|
||||
</div>
|
||||
{view.inventory.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm" aria-label="Inventory">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-stone-400">Carrying</span>
|
||||
{view.inventory.map((name) => (
|
||||
<span key={name} className="chip">🗝 {name}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="rounded-2xl border border-accent/30 bg-[radial-gradient(circle_at_center,rgb(var(--accent)/0.22),transparent_70%)] p-6 text-center"
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { Role, RoomState, TwinView } from '@two-keys/shared';
|
||||
import { otherRole } from '@two-keys/shared';
|
||||
import { useNow } from '../lib/hooks';
|
||||
import type { Send } from '../lib/socket';
|
||||
|
||||
interface Props {
|
||||
view: TwinView;
|
||||
state: RoomState;
|
||||
role: Role;
|
||||
receivedAt: number;
|
||||
send: Send;
|
||||
}
|
||||
|
||||
// Symbols that render as plain text unless asked for their emoji form.
|
||||
const TEXT_DEFAULT = new Set(['🛏', '🕯', '🖼', '☂', '✉', '✏', '☘', '🛋', '🕰', '🗝', '⏱', '☕', '⏰', '🍽', '🪑', '🕶', '☀', '❄', '⚱', '🏺', '♠', '♥', '♦', '♣']);
|
||||
/** Ask for the emoji form, so both phones draw the same picture. */
|
||||
const asEmoji = (cell: string) => (TEXT_DEFAULT.has(cell) ? `${cell}️` : cell);
|
||||
|
||||
const formatSeconds = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
|
||||
|
||||
function useCountdown(seconds: number, receivedAt: number, running: boolean): number {
|
||||
const now = useNow(250);
|
||||
return running ? Math.max(0, seconds - (now - receivedAt) / 1000) : seconds;
|
||||
}
|
||||
|
||||
export function TwinGame({ view, state, role, receivedAt, send }: Props) {
|
||||
const roles = state.game.roles;
|
||||
const partnerName = roles[otherRole(role)].name;
|
||||
const playing = view.status === 'playing';
|
||||
const remaining = useCountdown(view.remaining, receivedAt, playing);
|
||||
// Taps expire on their own, so the rings fade out here without waiting for the server.
|
||||
const myTapLeft = useCountdown(view.myTap?.secondsLeft ?? 0, receivedAt, playing);
|
||||
const partnerTapLeft = useCountdown(view.partnerTap?.secondsLeft ?? 0, receivedAt, playing);
|
||||
const myTap = view.myTap && myTapLeft > 0 ? view.myTap : null;
|
||||
const found = new Set(view.found.map((f) => `${f.x},${f.y}`));
|
||||
const width = view.grid[0]?.length ?? 0;
|
||||
const rows = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
|
||||
const header = (
|
||||
<div className="text-center">
|
||||
<div className="text-xs font-bold uppercase tracking-widest text-accent">
|
||||
Room {view.scene.index + 1} of {view.scene.total}
|
||||
{view.isRetry && ' · Retry'}
|
||||
</div>
|
||||
<h2 className="font-display text-3xl font-bold">{view.scene.title}</h2>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (view.status === 'ready') {
|
||||
return (
|
||||
<div className="space-y-5 text-center">
|
||||
{header}
|
||||
<p className="text-lg text-stone-200">
|
||||
{view.scene.differences} differences, {formatSeconds(view.timeSeconds)} on the clock.
|
||||
</p>
|
||||
<p className="text-sm text-stone-400">
|
||||
Describe your room to {partnerName}, square by square. When you spot a difference, you <strong>both</strong> tap
|
||||
that square within {view.claimWindowSeconds} seconds. A wrong claim costs {view.wrongClaimPenaltySeconds}s.
|
||||
</p>
|
||||
<button className="btn-primary w-full" onClick={() => send('chapter:continue')}>
|
||||
Open the room 🚪
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{header}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="font-display text-xl font-bold" aria-label={`${view.found.length} of ${view.scene.differences} differences found`}>
|
||||
{view.found.length} / {view.scene.differences}
|
||||
</div>
|
||||
<div
|
||||
className={`rounded-lg border px-3 py-1 font-mono text-xl font-bold tabular-nums ${remaining <= 30 && playing ? 'border-red-400 text-red-300' : 'border-white/15'}`}
|
||||
role="timer"
|
||||
aria-label={`${formatSeconds(remaining)} left in this room`}
|
||||
>
|
||||
{formatSeconds(remaining)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scrolls inside its card if it ever has to, never the page. */}
|
||||
<div className="overflow-x-auto rounded-xl border border-accent/30 bg-black/40 p-1.5">
|
||||
<div
|
||||
className="mx-auto grid w-full gap-0.5 font-emoji"
|
||||
// Cells shrink to 30px at the narrowest (10 columns fit a 375px phone) and stop growing at 48px.
|
||||
style={{
|
||||
gridTemplateColumns: `${view.showCoordinates ? 'auto ' : ''}repeat(${width}, minmax(30px, 1fr))`,
|
||||
maxWidth: `${width * 48 + (view.showCoordinates ? 20 : 0)}px`,
|
||||
}}
|
||||
role="grid"
|
||||
aria-label="Your room. Tap a square to claim a difference."
|
||||
>
|
||||
{view.showCoordinates && (
|
||||
<>
|
||||
<span aria-hidden />
|
||||
{Array.from({ length: width }, (_, x) => (
|
||||
<span key={x} className="text-center font-mono text-[11px] text-stone-400" aria-hidden>
|
||||
{x + 1}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{view.grid.map((row, y) => (
|
||||
<div key={y} role="row" className="contents">
|
||||
{view.showCoordinates && (
|
||||
<span className="flex items-center pr-1 font-mono text-[11px] text-stone-400" aria-hidden>
|
||||
{rows[y]}
|
||||
</span>
|
||||
)}
|
||||
{row.map((cell, x) => {
|
||||
const isFound = found.has(`${x},${y}`);
|
||||
const isMine = myTap?.x === x && myTap?.y === y;
|
||||
const name = view.showCoordinates ? `${rows[y]}${x + 1}` : `row ${y + 1}, column ${x + 1}`;
|
||||
return (
|
||||
<button
|
||||
key={x}
|
||||
role="gridcell"
|
||||
disabled={!playing || isFound}
|
||||
onClick={() => send('twin:tap', { x, y })}
|
||||
aria-label={`${name}: ${cell}${isFound ? ', found' : isMine ? ', tapped' : ''}`}
|
||||
className={`relative flex aspect-square items-center justify-center rounded-md text-[clamp(18px,6vw,28px)] leading-none transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent ${
|
||||
isFound ? 'bg-emerald-500/30 ring-2 ring-emerald-400' : 'bg-white/5 hover:bg-white/10'
|
||||
}`}
|
||||
>
|
||||
{asEmoji(cell)}
|
||||
{isMine && <span className="absolute inset-0 rounded-md ring-4 ring-accent motion-safe:animate-pulse" aria-hidden />}
|
||||
{isFound && <span className="absolute -right-0.5 -top-1 text-xs" aria-hidden>✅</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm text-stone-400" aria-live="polite">
|
||||
{!playing
|
||||
? ''
|
||||
: myTap
|
||||
? `You tapped a square. ${partnerName} has ${Math.ceil(myTapLeft)}s to tap the same one.`
|
||||
: view.partnerTap && partnerTapLeft > 0
|
||||
? `${partnerName} tapped a square! Which one? Ask, then tap it within ${Math.ceil(partnerTapLeft)}s.`
|
||||
: 'Both tap the same square to claim a difference. No screen-peeking!'}
|
||||
</p>
|
||||
|
||||
{view.status === 'won' && (
|
||||
<div className="rounded-2xl border-2 border-emerald-500/70 bg-emerald-950/50 p-5 text-center" aria-live="polite">
|
||||
<div className="text-5xl" aria-hidden>🔑</div>
|
||||
<h3 className="mt-2 font-display text-2xl font-bold">Every difference found! {view.scene.keyName}</h3>
|
||||
<button className="btn-primary mt-4 w-full" onClick={() => send('chapter:continue')}>
|
||||
{view.scene.index === view.scene.total - 1 ? 'See how we did →' : 'Next room →'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{view.status === 'failed' && (
|
||||
<div className="rounded-2xl border-2 border-red-500/70 bg-red-950/50 p-5 text-center" aria-live="polite">
|
||||
<div className="text-5xl" aria-hidden>⏰</div>
|
||||
<h3 className="mt-2 font-display text-2xl font-bold">Out of time in this room</h3>
|
||||
<p className="mt-1 text-stone-300">
|
||||
{view.canRetry ? 'You get one retry, with the clock reset.' : 'No key for this room.'}
|
||||
</p>
|
||||
<button className="btn-primary mt-4 w-full" onClick={() => send('chapter:continue')}>
|
||||
{view.canRetry ? 'Try this room again ↻' : view.scene.index === view.scene.total - 1 ? 'See how we did →' : 'Next room →'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+20
-1
@@ -1,6 +1,6 @@
|
||||
import { useEffect } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { Category, Role, Theme } from '@two-keys/shared';
|
||||
import type { Category, EngineId, Role, Theme } from '@two-keys/shared';
|
||||
|
||||
/** "#7b1e3a" → "123 30 58", the form Tailwind's rgb(var(--x) / alpha) wants. */
|
||||
export function hexToRgb(hex: string): string {
|
||||
@@ -37,6 +37,25 @@ export const CATEGORY_LABEL: Record<Category, string> = {
|
||||
'co-op': 'Co-op',
|
||||
};
|
||||
|
||||
/** The newer game types show their own label instead of plain "Co-op", and get their own filter. */
|
||||
const LABELLED_ENGINES = ['dial', 'twin', 'blueprint'] as const;
|
||||
|
||||
/** A library filter: a category, or one of the engines that has its own label. */
|
||||
export type LibraryFilter = Category | (typeof LABELLED_ENGINES)[number];
|
||||
|
||||
export const filterOf = (game: { category: Category; engine: EngineId }): LibraryFilter =>
|
||||
(LABELLED_ENGINES as readonly string[]).includes(game.engine) ? (game.engine as LibraryFilter) : game.category;
|
||||
|
||||
export const FILTER_LABEL: Record<LibraryFilter, string> = {
|
||||
...CATEGORY_LABEL,
|
||||
dial: 'Mind Meld',
|
||||
twin: 'Spot the Difference',
|
||||
blueprint: 'Describe & Draw',
|
||||
};
|
||||
|
||||
/** What a game's chip says. */
|
||||
export const chipLabel = (game: { category: Category; engine: EngineId }) => FILTER_LABEL[filterOf(game)];
|
||||
|
||||
/** A is warm (amber), B is cool (teal). */
|
||||
export const ROLE_TEXT: Record<Role, string> = { A: 'text-roleA', B: 'text-roleB' };
|
||||
export const ROLE_BORDER: Record<Role, string> = { A: 'border-roleA/60', B: 'border-roleB/60' };
|
||||
|
||||
@@ -26,6 +26,7 @@ const STEPS = [
|
||||
|
||||
const TIPS = [
|
||||
['💡 Hints', 'Three per lock, from a nudge to nearly the answer. Each costs two minutes: added to your final time, or taken off the countdown in timed games. You both see it.'],
|
||||
['🎯 Mind Meld, Spot the Difference, Describe & Draw', 'No locks here: one of you gives a clue for a hidden spot on a dial, you both hunt for the differences between two rooms, or one describes a picture the other paints.'],
|
||||
['📝 Shared notepad', 'Jot down times, names and theories. You both see it update live.'],
|
||||
['👋 Pings', "Tap your partner's name to send a little wave, a magnifying glass, a lightbulb or a heart."],
|
||||
['🔄 Lost connection?', 'Just refresh or reopen the link. You land back in the same seat with all your progress.'],
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import type { Category } from '@two-keys/shared';
|
||||
import { GameCard } from '../components/GameCard';
|
||||
import { SiteShell } from '../components/SiteShell';
|
||||
import { useGames } from '../lib/hooks';
|
||||
import { CATEGORY_LABEL, DIFFICULTY_LABEL, MAX_DIFFICULTY } from '../lib/theme';
|
||||
import { DIFFICULTY_LABEL, FILTER_LABEL, MAX_DIFFICULTY, filterOf, type LibraryFilter } from '../lib/theme';
|
||||
|
||||
const FILTERS: (Category | 'all')[] = ['all', 'murder-mystery', 'escape-room', 'co-op'];
|
||||
const FILTERS: (LibraryFilter | 'all')[] = ['all', 'murder-mystery', 'escape-room', 'co-op', 'dial', 'twin', 'blueprint'];
|
||||
const LEVELS = Array.from({ length: MAX_DIFFICULTY }, (_, i) => i + 1);
|
||||
|
||||
function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: ReactNode }) {
|
||||
@@ -24,11 +23,11 @@ function Chip({ active, onClick, children }: { active: boolean; onClick: () => v
|
||||
|
||||
export function Library() {
|
||||
const games = useGames();
|
||||
const [filter, setFilter] = useState<Category | 'all'>('all');
|
||||
const [filter, setFilter] = useState<LibraryFilter | 'all'>('all');
|
||||
const [level, setLevel] = useState<number | null>(null);
|
||||
// Easiest first; ties keep the library's own order.
|
||||
const shown = (games ?? [])
|
||||
.filter((g) => (filter === 'all' || g.category === filter) && (level === null || g.difficulty === level))
|
||||
.filter((g) => (filter === 'all' || filterOf(g) === filter) && (level === null || g.difficulty === level))
|
||||
.map((g, i) => ({ g, i }))
|
||||
.sort((a, b) => a.g.difficulty - b.g.difficulty || a.i - b.i)
|
||||
.map(({ g }) => g);
|
||||
@@ -43,7 +42,7 @@ export function Library() {
|
||||
<div className="mt-5 flex flex-wrap gap-2" role="group" aria-label="Filter by category">
|
||||
{FILTERS.map((f) => (
|
||||
<Chip key={f} active={filter === f} onClick={() => setFilter(f)}>
|
||||
{f === 'all' ? 'All games' : CATEGORY_LABEL[f]}
|
||||
{f === 'all' ? 'All games' : FILTER_LABEL[f]}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from 'react';
|
||||
import type { Role, RoomState } from '@two-keys/shared';
|
||||
import { Markdown, RoleBadge } from '../components/ui';
|
||||
import { socket } from '../lib/socket';
|
||||
import { CATEGORY_LABEL, MAX_DIFFICULTY, ROLE_BORDER, difficultyKeys } from '../lib/theme';
|
||||
import { MAX_DIFFICULTY, chipLabel, ROLE_BORDER, difficultyKeys } from '../lib/theme';
|
||||
|
||||
function ShareBox({ code }: { code: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
@@ -49,7 +49,7 @@ export function Lobby({ state }: { state: RoomState }) {
|
||||
<div className="mx-auto w-full max-w-2xl space-y-5 px-4 py-6">
|
||||
<header className="text-center">
|
||||
<div className="flex flex-wrap items-center justify-center gap-2 text-xs text-stone-300">
|
||||
<span className="chip text-accent">{CATEGORY_LABEL[game.category]}</span>
|
||||
<span className="chip text-accent">{chipLabel(game)}</span>
|
||||
<span>⏱ {game.estimatedMinutes} min</span>
|
||||
<span aria-label={`Difficulty ${game.difficulty} of ${MAX_DIFFICULTY}`}>{difficultyKeys(game.difficulty)}</span>
|
||||
{game.timeLimitMinutes !== null && <span className="text-red-300">⏳ {game.timeLimitMinutes} min limit</span>}
|
||||
|
||||
@@ -7,10 +7,13 @@ import { PartnerStatus, PingOverlay } from '../components/PartnerStatus';
|
||||
import { PassDeviceScreen } from '../components/PassDeviceScreen';
|
||||
import { Timer, WaterGauge, isWaterLevel } from '../components/Timer';
|
||||
import { RoleBadge } from '../components/ui';
|
||||
import { BlueprintGame } from '../engines/BlueprintGame';
|
||||
import { DefuseGame } from '../engines/DefuseGame';
|
||||
import { DialGame } from '../engines/DialGame';
|
||||
import { LabyrinthGame } from '../engines/LabyrinthGame';
|
||||
import { StoryGame } from '../engines/StoryGame';
|
||||
import { SyncGame } from '../engines/SyncGame';
|
||||
import { TwinGame } from '../engines/TwinGame';
|
||||
import { socket, type Send } from '../lib/socket';
|
||||
|
||||
const ROLE_COLOR: Record<Role, string> = { A: '#f5b942', B: '#2dd4bf' };
|
||||
@@ -82,6 +85,11 @@ export function Play({ state, receivedAt }: { state: RoomState; receivedAt: numb
|
||||
{view?.engine === 'defuse' && <DefuseGame view={view} state={state} receivedAt={receivedAt} send={send} />}
|
||||
{view?.engine === 'sync' && <SyncGame view={view} state={state} role={activeRole} send={send} />}
|
||||
{view?.engine === 'labyrinth' && <LabyrinthGame view={view} state={state} send={send} />}
|
||||
{view?.engine === 'dial' && <DialGame view={view} state={state} role={activeRole} send={send} />}
|
||||
{view?.engine === 'twin' && <TwinGame view={view} state={state} role={activeRole} receivedAt={receivedAt} send={send} />}
|
||||
{view?.engine === 'blueprint' && (
|
||||
<BlueprintGame view={view} state={state} role={activeRole} receivedAt={receivedAt} send={send} />
|
||||
)}
|
||||
</main>
|
||||
|
||||
{!couch && <PingOverlay roles={game.roles} />}
|
||||
|
||||
@@ -19,6 +19,8 @@ export default {
|
||||
sans: ['Inter', 'system-ui', 'Noto Sans Symbols 2', 'sans-serif'],
|
||||
hand: ['Caveat', 'Noto Sans Symbols 2', 'cursive'],
|
||||
mono: ['JetBrains Mono', 'ui-monospace', 'Noto Sans Symbols 2', 'monospace'],
|
||||
// Twin Rooms: the same emoji glyphs on both phones.
|
||||
emoji: ['Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user