Play: online lobbies for modes hosted on this node; MatchBoard split

MatchBoard renders any PlayerView; the local controller runs the engine
and bot, the online controller polls the host lobby API (create, join,
draft picks, actions, resign). Player secret is HMAC(master, hostOrigin)
per night-review. Illegal local moves no longer throw inside a state
updater.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 23:33:02 -05:00
co-authored by Claude Opus 5.5
parent dcb2c45af2
commit 60af45262d
8 changed files with 411 additions and 171 deletions
+123
View File
@@ -0,0 +1,123 @@
import { useEffect, useRef, useState } from 'react';
import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
import { GameCard, StatIcon } from './GameCard.tsx';
import { STAT_HINT, STAT_LABEL } from './rulesText.ts';
import type { LaneView, MatchView, UIAction, UICard } from './types.ts';
type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
/** The match screen itself: board, thumb dock and bottom sheets. Controllers (local bot / hosted lobby) feed it. */
export function MatchBoard({ title, opponent, view, legal, onAct, problem, error, onTopicBonus }: {
title: string; opponent: string; view: MatchView; legal: UIAction[]; onAct: (a: UIAction) => void;
problem?: (a: UIAction) => string | null; error?: string; onTopicBonus: number[];
}) {
const [selected, setSelected] = useState<string>();
const [sheet, setSheet] = useState<Sheet>(null);
const [banner, setBanner] = useState('');
const prevBoard = useRef(new Set<string>());
const [fresh, setFresh] = useState(new Set<string>());
const boardKey = view.lanes.map(l => [...l.mine, ...l.theirs].map(c => c.id).join(',')).join('|');
// Turn feedback: banner on turn change, and a short highlight on newly revealed cards.
const lastTurn = useRef(view.turn);
useEffect(() => {
const ids = new Set(boardKey.split(/[|,]/).filter(Boolean));
const added = new Set([...ids].filter(id => !prevBoard.current.has(id)));
prevBoard.current = ids;
if (added.size) { setFresh(added); const t = setTimeout(() => setFresh(new Set()), 900); return () => clearTimeout(t); }
}, [boardKey]);
useEffect(() => {
if (view.turn !== lastTurn.current && !view.over) {
lastTurn.current = view.turn;
setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
const t = setTimeout(() => setBanner(''), 1400);
return () => clearTimeout(t);
}
}, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
const act = onAct;
const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
const playable = (cardId: string) => legal.some(a => a.type === 'play' && a.cardId === cardId);
const sel = view.hand.find(c => c.id === selected);
const tapLane = (lane: LaneView) => {
if (sel && canPlay(sel.id, lane.index)) { act({ type: 'play', cardId: sel.id, lane: lane.index }); setSelected(undefined); }
else setSheet({ kind: 'lane', lane });
};
const ending = view.waitingForOpponent;
const lastEvent = view.log.at(-1);
return <section className="match" aria-label={title}>
<header className="match-bar">
<span className="match-turn"><Hourglass size={14} /> Turn <b>{view.turn}</b>/{view.maxTurns}</span>
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{opponent} · <Layers3 size={13} /> {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}</span>
<button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>
</header>
{banner && <div className="turn-banner" role="status">{banner}</div>}
<div className="lanes" style={{ gridTemplateColumns: `repeat(${view.lanes.length}, minmax(0, 1fr))` }}>
{view.lanes.map(lane => {
const target = !!sel && canPlay(sel.id, lane.index);
const lead = lane.leader === 'you' ? 'ahead' : lane.leader === 'opponent' ? 'behind' : 'even';
const onTopic = !!sel && (sel.home === lane.stat || (lane.revealed && lane.modifier?.name === 'Disambiguation'));
const topicBonus = sel ? onTopicBonus[sel.cost] ?? 0 : 0;
return <div key={lane.index} className={`lane ${target ? 'is-target' : ''} ${sel && !target ? 'is-blocked' : ''}`}>
<div className="lane-side theirs" aria-label={`Opponent cards in ${lane.name}`}>
{lane.theirs.map(c => <GameCard key={c.id} card={c} size="board" fresh={fresh.has(c.id)} onClick={() => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)}
</div>
<button className={`lane-plate ${lead}`} onClick={() => tapLane(lane)}
aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
<span className="lane-score theirs">{lane.theirPower}</span>
<span className="lane-name"><StatIcon stat={lane.stat} size={13} /><span>{lane.name}</span>{!lane.revealed && <small>?</small>}</span>
<span className="lane-score mine">{lane.myPower}</span>
</button>
<div className="lane-side mine" aria-label={`Your cards in ${lane.name}`}>
{lane.mine.map(c => <GameCard key={c.id} card={c} size="board" fresh={fresh.has(c.id)} onClick={() => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
{lane.staged.map(c => <GameCard key={c.id} card={c} size="board" label={`Take back ${c.title}`} onClick={() => act({ type: 'unstage', cardId: c.id })} selected />)}
{target && <span className={`lane-drop ${onTopic ? 'on-topic' : ''}`}>{onTopic ? `On-topic +${topicBonus}` : 'Play here'}</span>}
</div>
</div>;
})}
</div>
<div className="play-dock match-dock">
<p className="dock-note" role="status" aria-live="polite">
{error ? <span className="dock-error">{error}</span>
: ending ? <><LoaderCircle className="spin" size={14} /> Opponent is choosing…</>
: sel ? <><Zap size={12} /> <b>{sel.title}</b>{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.</>
: lastEvent}
</p>
<div className="hand" aria-label="Your hand">
{view.hand.length ? view.hand.map(c => <GameCard key={c.id} card={c} selected={selected === c.id} dim={!playable(c.id)}
onClick={ending ? undefined : () => setSelected(selected === c.id ? undefined : c.id)} />)
: <span className="muted">No cards in hand.</span>}
</div>
<div className="dock-row">
<span className="energy" aria-label={`${view.energy} of ${view.maxEnergy} energy left`}>
{Array.from({ length: view.maxEnergy }, (_, i) => <i key={i} className={i < view.energy ? 'on' : ''} />)}
<b>{view.energy}</b>
</span>
<span className="deck-count"><Layers3 size={13} /> {view.deckCount}</span>
<button className="button dark end-turn" disabled={ending || view.over} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}>
{ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
</button>
</div>
</div>
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
<div className="sheet" role="dialog" aria-modal="true" aria-label="Details">
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
{sheet.kind === 'card' && <><div className="sheet-card"><GameCard card={sheet.card} /></div>
<h3>{sheet.card.title}</h3><p className="muted">{sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power} · home {STAT_LABEL[sheet.card.home]}{sheet.card.trend ? (sheet.card.trend > 0 ? ' · trending ▲' : ' · trending ▼') : ''}{sheet.card.onTopic ? ' · on-topic' : ''}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}</p>
{sheet.card.keyword && <p><b>{sheet.card.keyword.name}.</b> {sheet.card.keyword.text}</p>}</>}
{sheet.kind === 'lane' && <><h3><StatIcon stat={sheet.lane.stat} size={18} /> {sheet.lane.name}</h3>
<p>Judged on <b>{STAT_LABEL[sheet.lane.stat]}</b> ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.</p>
{sheet.lane.modifier ? <p><b>Portal: {sheet.lane.modifier.name}.</b> {sheet.lane.modifier.text}</p> : sheet.lane.portalNote && <p className="muted">{sheet.lane.portalNote}.</p>}
<p className="muted">You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.</p>
{sel && !canPlay(sel.id, sheet.lane.index) && <p className="dock-error">{sel.title} can’t go here: {problem?.({ type: 'play', cardId: sel.id, lane: sheet.lane.index }) ?? (sel.cost > view.energy ? 'not enough energy' : 'no room')}.</p>}</>}
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
<button className="button dark" onClick={() => { setSheet(null); act({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
</div>
</div>}
</section>;
}
+18 -126
View File
@@ -1,11 +1,9 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
import type { MatchState } from '../../shared/game/index.ts';
import { engine } from './adapter.ts';
import type { Bot } from './bots.ts';
import { GameCard, StatIcon } from './GameCard.tsx';
import { STAT_HINT, STAT_LABEL } from './rulesText.ts';
import type { MatchState } from '../../shared/game/index.ts';
import type { GameMode, LaneView, ResultView, UIAction, UICard } from './types.ts';
import { MatchBoard } from './MatchBoard.tsx';
import type { GameMode, ResultView, UIAction, UICard } from './types.ts';
const BOT_DELAY_MS = 450;
@@ -15,145 +13,39 @@ function seededRand(seed: string) {
return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); return ((h ^= h >>> 16) >>> 0) / 4294967296; };
}
type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
/** Local match against a bot: the engine runs in the browser, the bot plays seat 1. */
export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
mode: GameMode; deck: UICard[]; opponentDeck: UICard[]; bot: Bot; seed: string; onFinish: (r: ResultView) => void;
}) {
const [state, setState] = useState<MatchState>(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed));
const [selected, setSelected] = useState<string>();
const [sheet, setSheet] = useState<Sheet>(null);
const [error, setError] = useState('');
const [banner, setBanner] = useState('');
const rand = useRef(seededRand(`${seed}:bot`));
const view = engine.view(state, 0);
const view = useMemo(() => engine.view(state, 0), [state]);
const legal = useMemo(() => engine.legal(state, 0), [state]);
const prevBoard = useRef(new Set<string>());
const [fresh, setFresh] = useState(new Set<string>());
// Turn feedback: banner on turn change, and a short highlight on newly revealed cards.
const lastTurn = useRef(view.turn);
useEffect(() => {
const ids = new Set(view.lanes.flatMap(l => [...l.mine, ...l.theirs].map(c => c.id)));
const added = new Set([...ids].filter(id => !prevBoard.current.has(id)));
prevBoard.current = ids;
if (added.size) { setFresh(added); const t = setTimeout(() => setFresh(new Set()), 900); return () => clearTimeout(t); }
}, [state]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (view.turn !== lastTurn.current && !view.over) {
lastTurn.current = view.turn;
setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
const t = setTimeout(() => setBanner(''), 1400);
return () => clearTimeout(t);
}
}, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
useEffect(() => { if (engine.isOver(state)) { const t = setTimeout(() => onFinish(engine.result(state, 0)), 900); return () => clearTimeout(t); } }, [state, onFinish]);
// The bot moves once the player has ended the turn (it never sees staged plays).
// The bot moves once the player has committed (it never sees the player's queued plays).
useEffect(() => {
if (!view.waitingForOpponent) return;
const t = setTimeout(() => {
setState((s: MatchState) => {
let cur = s;
for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
const acts = engine.legal(cur, 1);
if (!acts.length) break;
const choice = bot.choose(engine.view(cur, 1), acts.filter(a => a.type !== 'concede'), rand.current);
try { cur = engine.apply(cur, 1, choice); } catch { cur = engine.apply(cur, 1, { type: 'endTurn' }); }
if (choice.type === 'endTurn') break;
}
return cur;
});
let cur = state;
for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
const acts = engine.legal(cur, 1);
if (!acts.length) break;
const choice = bot.choose(engine.view(cur, 1), acts.filter(a => a.type !== 'concede'), rand.current);
try { cur = engine.apply(cur, 1, choice); } catch { cur = engine.apply(cur, 1, { type: 'endTurn' }); }
if (choice.type === 'endTurn') break;
}
setState(cur);
}, BOT_DELAY_MS);
return () => clearTimeout(t);
}, [view.waitingForOpponent, state, bot]);
const act = (a: UIAction) => {
try { setState((s: MatchState) => engine.apply(s, 0, a)); setError(''); }
try { setState(engine.apply(state, 0, a)); setError(''); }
catch (e) { setError(e instanceof Error ? e.message : 'That move isn’t allowed.'); }
};
const canPlay = (cardId: string, lane: number) => legal.some(a => a.type === 'play' && a.cardId === cardId && a.lane === lane);
const playable = (cardId: string) => legal.some(a => a.type === 'play' && a.cardId === cardId);
const sel = view.hand.find(c => c.id === selected);
const tapLane = (lane: LaneView) => {
if (sel && canPlay(sel.id, lane.index)) { act({ type: 'play', cardId: sel.id, lane: lane.index }); setSelected(undefined); }
else setSheet({ kind: 'lane', lane });
};
const ending = view.waitingForOpponent;
const lastEvent = view.log.at(-1);
return <section className="match" aria-label={`${mode.name} match`}>
<header className="match-bar">
<span className="match-turn"><Hourglass size={14} /> Turn <b>{view.turn}</b>/{view.maxTurns}</span>
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{bot.name} bot · <Layers3 size={13} /> {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}</span>
<button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>
</header>
{banner && <div className="turn-banner" role="status">{banner}</div>}
<div className="lanes" style={{ gridTemplateColumns: `repeat(${view.lanes.length}, minmax(0, 1fr))` }}>
{view.lanes.map(lane => {
const target = !!sel && canPlay(sel.id, lane.index);
const lead = lane.leader === 'you' ? 'ahead' : lane.leader === 'opponent' ? 'behind' : 'even';
const onTopic = !!sel && (sel.home === lane.stat || (lane.revealed && lane.modifier?.name === 'Disambiguation'));
const topicBonus = sel ? mode.ruleset.onTopicBonus[sel.cost] ?? 0 : 0;
return <div key={lane.index} className={`lane ${target ? 'is-target' : ''} ${sel && !target ? 'is-blocked' : ''}`}>
<div className="lane-side theirs" aria-label={`Opponent cards in ${lane.name}`}>
{lane.theirs.map(c => <GameCard key={c.id} card={c} size="board" fresh={fresh.has(c.id)} onClick={() => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)}
</div>
<button className={`lane-plate ${lead}`} onClick={() => tapLane(lane)}
aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
<span className="lane-score theirs">{lane.theirPower}</span>
<span className="lane-name"><StatIcon stat={lane.stat} size={13} /><span>{lane.name}</span>{!lane.revealed && <small>?</small>}</span>
<span className="lane-score mine">{lane.myPower}</span>
</button>
<div className="lane-side mine" aria-label={`Your cards in ${lane.name}`}>
{lane.mine.map(c => <GameCard key={c.id} card={c} size="board" fresh={fresh.has(c.id)} onClick={() => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
{lane.staged.map(c => <GameCard key={c.id} card={c} size="board" label={`Take back ${c.title}`} onClick={() => act({ type: 'unstage', cardId: c.id })} selected />)}
{target && <span className={`lane-drop ${onTopic ? 'on-topic' : ''}`}>{onTopic ? `On-topic +${topicBonus}` : 'Play here'}</span>}
</div>
</div>;
})}
</div>
<div className="play-dock match-dock">
<p className="dock-note" role="status" aria-live="polite">
{error ? <span className="dock-error">{error}</span>
: ending ? <><LoaderCircle className="spin" size={14} /> Opponent is choosing…</>
: sel ? <><Zap size={12} /> <b>{sel.title}</b>{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.</>
: lastEvent}
</p>
<div className="hand" aria-label="Your hand">
{view.hand.length ? view.hand.map(c => <GameCard key={c.id} card={c} selected={selected === c.id} dim={!playable(c.id)}
onClick={ending ? undefined : () => setSelected(selected === c.id ? undefined : c.id)} />)
: <span className="muted">No cards in hand.</span>}
</div>
<div className="dock-row">
<span className="energy" aria-label={`${view.energy} of ${view.maxEnergy} energy left`}>
{Array.from({ length: view.maxEnergy }, (_, i) => <i key={i} className={i < view.energy ? 'on' : ''} />)}
<b>{view.energy}</b>
</span>
<span className="deck-count"><Layers3 size={13} /> {view.deckCount}</span>
<button className="button dark end-turn" disabled={ending || view.over} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}>
{ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
</button>
</div>
</div>
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
<div className="sheet" role="dialog" aria-modal="true" aria-label="Details">
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
{sheet.kind === 'card' && <><div className="sheet-card"><GameCard card={sheet.card} /></div>
<h3>{sheet.card.title}</h3><p className="muted">{sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power} · home {STAT_LABEL[sheet.card.home]}{sheet.card.trend ? (sheet.card.trend > 0 ? ' · trending ▲' : ' · trending ▼') : ''}{sheet.card.onTopic ? ' · on-topic' : ''}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}</p>
{sheet.card.keyword && <p><b>{sheet.card.keyword.name}.</b> {sheet.card.keyword.text}</p>}</>}
{sheet.kind === 'lane' && <><h3><StatIcon stat={sheet.lane.stat} size={18} /> {sheet.lane.name}</h3>
<p>Judged on <b>{STAT_LABEL[sheet.lane.stat]}</b> ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.</p>
{sheet.lane.modifier ? <p><b>Portal: {sheet.lane.modifier.name}.</b> {sheet.lane.modifier.text}</p> : sheet.lane.portalNote && <p className="muted">{sheet.lane.portalNote}.</p>}
<p className="muted">You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.</p>
{sel && !canPlay(sel.id, sheet.lane.index) && <p className="dock-error">{sel.title} can’t go here: {engine.problem(state, 0, { type: 'play', cardId: sel.id, lane: sheet.lane.index }) ?? 'not allowed'}.</p>}</>}
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
<button className="button dark" onClick={() => { setSheet(null); act({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
</div>
</div>}
</section>;
return <MatchBoard title={`${mode.name} match`} opponent={`${bot.name} bot`} view={view} legal={legal} onAct={act} error={error}
problem={a => engine.problem(state, 0, a)} onTopicBonus={mode.ruleset.onTopicBonus} />;
}
+134
View File
@@ -0,0 +1,134 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
import { toUICard } from './cards.ts';
import { GameCard as GameCardFace } from './GameCard.tsx';
import { MatchBoard } from './MatchBoard.tsx';
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
import type { GameMode, ResultView, UIAction } from './types.ts';
const POLL_MS = 1000;
const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
/** Human vs human on a mode hosted by this node: lobby list → (draft) → match, all via the host API. */
export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
}) {
const modeId = mode.remoteId ?? mode.id;
const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
const [lobbies, setLobbies] = useState<OpenLobby[]>();
const [seat, setSeat] = useState<LobbySeat>();
const [status, setStatus] = useState<LobbyStatus>();
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const inFlight = useRef(false);
const finished = useRef(false);
const refreshLobbies = useCallback(() => {
online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
}, [modeId]);
useEffect(() => {
if (seat) return;
refreshLobbies();
const t = setInterval(refreshLobbies, 4000);
return () => clearInterval(t);
}, [seat, refreshLobbies]);
const poll = useCallback(async () => {
if (!seat || inFlight.current) return;
inFlight.current = true;
try { setStatus(await online.status(seat)); setError(''); }
catch (e) { setError(message(e)); }
finally { inFlight.current = false; }
}, [seat]);
useEffect(() => {
if (!seat) return;
void poll();
const t = setInterval(() => { void poll(); }, POLL_MS);
return () => clearInterval(t);
}, [seat, poll]);
useEffect(() => {
const st = status?.state;
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
finished.current = true;
const names = st.lanes.map(l => l.topic.name);
const t = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
return () => clearTimeout(t);
}, [status, seat, onFinish]);
const enter = async (fn: () => Promise<LobbySeat>) => {
setBusy(true); setError('');
try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
};
const leave = async () => {
if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
onExit();
};
const send = async (fn: () => Promise<LobbyStatus>) => {
try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
};
// ----- lobby list -----
if (!seat) return <section className="play-panel online-lobby" aria-labelledby="online-title">
<div className="section-eyebrow">{mode.name.toUpperCase()} · ONLINE</div>
<h2 id="online-title">Play a person</h2>
<p className="muted">Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as <b>{playerName}</b>.</p>
<h3 className="lobby-label">Open lobbies <button className="icon-button" onClick={refreshLobbies} aria-label="Refresh lobbies"><RefreshCw size={14} /></button></h3>
<div className="mode-list">
{lobbies === undefined ? <p className="muted small"><LoaderCircle className="spin" size={13} /> Loading…</p>
: lobbies.length ? lobbies.map(l => <button key={l.lobbyId} className="mode" disabled={busy} onClick={() => enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
<span className="mode-icon"><Users size={18} /></span>
<span className="mode-copy"><b>{String(l.host).slice(0, 24)}</b><small>Waiting {Math.max(0, Math.round((Date.now() - l.createdAt) / 60000))} min · tap to join</small></span>
</button>)
: <p className="muted small">No one is waiting. Create a lobby and share this page with a friend.</p>}
</div>
{error && <p className="dock-error small" role="alert">{error}</p>}
<div className="play-dock"><div className="play-actions">
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> Back</button>
<button className="button dark play-cta" disabled={busy} onClick={() => enter(() => online.create(modeId, playerName, hostOrigin))}><Plus size={16} /> Create lobby</button>
</div></div>
</section>;
const phase = status?.phase;
// ----- match -----
if ((phase === 'playing' || phase === 'finished') && status?.state) {
const view = viewFromPlayerView(status.state);
const legal = uiActions(status.legalActions ?? []);
const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
const act = (a: UIAction) => {
if (a.type === 'concede') return void send(() => online.resign(seat));
return void send(() => online.act(seat, engineAction(a, seat.seat)));
};
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
}
// ----- draft -----
if (phase === 'drafting' && status?.draft) {
const mine = status.draft.toPick === seat.seat;
const toCard = (c: NonNullable<LobbyStatus['draft']>['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
return <section className="play-panel" aria-labelledby="draft-title">
<div className="section-eyebrow">{mode.name.toUpperCase()} · DRAFT</div>
<h2 id="draft-title">{mine ? 'Your pick' : 'Opponent is picking…'}</h2>
<p className="muted">Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.</p>
<div className="pool-grid">{status.draft.pool.map(p => <GameCardFace key={p.index} card={toCard(p.card)} size="deck"
selected={p.takenBy === seat.seat} dim={p.takenBy !== null && p.takenBy !== seat.seat}
onClick={mine && p.takenBy === null ? () => void send(() => online.pick(seat, p.index)) : undefined} />)}</div>
{error && <p className="dock-error small" role="alert">{error}</p>}
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}>Resign</button></div></div>
</section>;
}
// ----- waiting / starting / expired -----
return <section className="play-panel" aria-labelledby="wait-title">
<div className="section-eyebrow">{mode.name.toUpperCase()} · LOBBY</div>
<h2 id="wait-title">{phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}</h2>
<p className="muted">{phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.'
: <><LoaderCircle className="spin" size={14} /> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}</>}</p>
{error && <p className="dock-error small" role="alert">{error}</p>}
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {phase === 'expired' ? 'Back' : 'Cancel'}</button></div></div>
</section>;
}
+11 -5
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound, Users } from 'lucide-react';
import type { TestnetBlock } from '../../shared/testnet.ts';
import { Avatar } from '../auth/LoginButton.tsx';
import { BOTS, type Bot } from './bots.ts';
@@ -7,6 +7,8 @@ import { cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
import { CategoryIcon } from './GameCard.tsx';
import { MatchScreen } from './MatchScreen.tsx';
import { lobbyName } from './online.ts';
import { OnlinePlay } from './OnlinePlay.tsx';
import { Results } from './Results.tsx';
import { Tutorial } from './Tutorial.tsx';
import type { GameMode, ResultView } from './types.ts';
@@ -14,7 +16,7 @@ import { useAccount } from './useAccount.ts';
import { useModes } from './useModes.ts';
import './play.css';
type Screen = 'lobby' | 'deck' | 'match' | 'results' | 'tutorial';
type Screen = 'lobby' | 'deck' | 'match' | 'online' | 'results' | 'tutorial';
const DECK_KEY = 'wikideck-play-deck-v1';
const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
const store = {
@@ -46,12 +48,13 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
const warning = deckWarning(deck);
const opponent = useMemo(() => botDeck(seed, rules), [seed, rules]);
const start = () => { setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
const [lastOnline, setLastOnline] = useState(false);
const start = () => { setLastOnline(false); setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
const finish = useCallback((r: ResultView) => { setResult(r); setScreen('results'); }, []);
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen]);
// While a match is on screen, hide the floating eom.dev account button (it sits over the dock on phones).
useEffect(() => {
document.documentElement.classList.toggle('wd-in-match', screen === 'match');
document.documentElement.classList.toggle('wd-in-match', screen === 'match' || screen === 'online');
return () => document.documentElement.classList.remove('wd-in-match');
}, [screen]);
@@ -59,9 +62,11 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
if (screen === 'deck') return <DeckBuilder modeName={mode.name} pool={pool} deck={deck} ruleset={rules} onCancel={() => setScreen('lobby')}
onSave={d => { const ids = d.map(c => c.id); store.set(DECK_KEY, JSON.stringify(ids)); setSavedIds(ids); setScreen('lobby'); }} />;
if (screen === 'match') return <MatchScreen key={seed} mode={mode} deck={deck} opponentDeck={opponent} bot={bot} seed={seed} onFinish={finish} />;
if (screen === 'results' && result) return <Results result={result} modeName={mode.name} onRematch={start} onLobby={() => setScreen('lobby')} />;
if (screen === 'online') return <OnlinePlay key={mode.id} mode={mode} playerName={lobbyName(account?.name || account?.username)} onExit={() => setScreen('lobby')} onFinish={finish} />;
if (screen === 'results' && result) return <Results result={result} modeName={mode.name} onRematch={lastOnline ? () => setScreen('online') : start} onLobby={() => setScreen('lobby')} />;
const remote = mode.host.kind === 'peer' && !mode.host.self ? mode.host : null;
const hosted = mode.host.kind === 'peer' && mode.host.self;
return <section className="play-panel lobby" aria-labelledby="lobby-title">
<div className="lobby-head">
<div><div className="section-eyebrow">PLAY · OFF-CHAIN MATCHES</div><h2 id="lobby-title">Play WikiDeck</h2></div>
@@ -106,6 +111,7 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
<div className="play-dock"><div className="play-actions">
<button className="button outline" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /> How to play</button>
{hosted && <button className="button outline" onClick={() => { setLastOnline(true); setScreen('online'); }}><Users size={16} /> Play a person</button>}
<button className="button dark play-cta" disabled={!!problem} onClick={start}><Play size={16} /> Play vs {bot.name}</button>
</div></div>
</>}
+58 -39
View File
@@ -1,7 +1,7 @@
// The single place the Play UI touches the engine (import only from shared/game/index.ts).
import {
DEFAULT_RULESET, applyAction, actionProblem, createMatch, isOver, laneCapacity, legalActions, result, viewFor,
type Action, type CardInPlay, type LogEvent, type MatchState, type PlayerId, type Ruleset,
type Action, type CardInPlay, type LogEvent, type MatchResult, type MatchState, type PlayerId, type PlayerView, type Ruleset,
} from '../../shared/game/index.ts';
import { toUICard } from './cards.ts';
import { portalInfo, STAT_LABEL } from './rulesText.ts';
@@ -63,51 +63,70 @@ export const engine = {
return actionProblem(state, toEngine(action, player));
},
view(state: MatchState, me: PlayerId): MatchView {
const v = viewFor(state, me);
const rules = v.ruleset;
const titles = new Map<string, string>();
for (const p of state.players) for (const c of [...p.hand, ...p.deck]) titles.set(c.cardId, c.title);
for (const l of state.lanes) for (const side of l.cards) for (const c of side) titles.set(c.card.cardId, c.card.title);
const handUI = v.hand.map(c => toUICard(c, rules));
const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
const lanes: LaneView[] = v.lanes.map((lane, i) => {
const portal = lane.portalRevealed ? portalInfo(lane.topic.portal, lane.topic.id, rules) : undefined;
const allOn = lane.portalRevealed && lane.topic.portal === 'disambiguation';
return {
index: i, stat: lane.topic.stat, revealed: lane.portalRevealed,
name: lane.portalRevealed ? lane.topic.name : STAT_LABEL[lane.topic.stat],
modifier: portal, portalNote: lane.portalRevealed ? undefined : `Topic and Portal reveal on turn ${rules.portalReveal[i]}`,
mine: lane.cards[0].map((c, k) => onBoard(c, lane.cardPower[0][k], lane.topic.stat, allOn)),
theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
staged: v.queue.filter(q => q.lane === i).flatMap(q => {
const c = state.players[me].hand.find(h => h.cardId === q.cardId);
return c ? [toUICard(c, rules)] : [];
}),
myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader, capacity: laneCapacity(state, i),
};
});
const queued = new Set(v.queue.map(q => q.cardId));
const log = state.log.filter(e => e.t !== 'draw')
.map(e => logLine(e, me, id => titles.get(id) ?? 'a card')).filter((x): x is string => !!x).slice(-30);
return {
me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
hand: handUI.filter(c => !queued.has(c.id)), deckCount: v.deckCount,
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
lanes, log, waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
engine: { state, seat: me },
};
return { ...viewFromPlayerView(viewFor(state, me), { log, capacity: i => laneCapacity(state, i) }), engine: { state, seat: me } };
},
isOver: (s: MatchState) => isOver(s),
result(state: MatchState, me: PlayerId): ResultView {
const r = result(state)!;
const opp: PlayerId = me === 0 ? 1 : 0;
return {
winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
lanes: r.lanePower.map((pw, i) => {
const a = pw[me], b = pw[opp];
return { name: state.lanes[i].topic.name, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
}),
};
return resultView(result(state)!, me, state.lanes.map(l => l.topic.name));
},
};
/** Stub-style Portals cap a lane; online views don't carry state, so read the cap from the ruleset. */
function capacityFromView(v: PlayerView, i: number): number {
const t = v.lanes[i].topic, r = v.ruleset;
if (v.lanes[i].portalRevealed && t.portal === 'stub') return (r.portalParams[t.id] ?? r.portalParams.stub)?.capacity ?? Math.min(2, r.laneCapacity);
return r.laneCapacity;
}
/** Build the screen model from what one seat may see (local engine or a hosting node). */
export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capacity?: (lane: number) => number } = {}): MatchView {
const rules = v.ruleset;
const me = v.you;
const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
const lanes: LaneView[] = v.lanes.map((lane, i) => {
const portal = lane.portalRevealed ? portalInfo(lane.topic.portal, lane.topic.id, rules) : undefined;
const allOn = lane.portalRevealed && lane.topic.portal === 'disambiguation';
return {
index: i, stat: lane.topic.stat, revealed: lane.portalRevealed,
name: lane.portalRevealed ? lane.topic.name : STAT_LABEL[lane.topic.stat],
modifier: portal, portalNote: lane.portalRevealed ? undefined : `Topic and Portal reveal on turn ${rules.portalReveal[i]}`,
mine: lane.cards[0].map((c, k) => onBoard(c, lane.cardPower[0][k], lane.topic.stat, allOn)),
theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
staged: v.queue.filter(q => q.lane === i).flatMap(q => {
const c = v.hand.find(h => h.cardId === q.cardId);
return c ? [toUICard(c, rules)] : [];
}),
myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader,
capacity: opts.capacity ? opts.capacity(i) : capacityFromView(v, i),
};
});
const queued = new Set(v.queue.map(q => q.cardId));
return {
me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
hand: v.hand.filter(c => !queued.has(c.cardId)).map(c => toUICard(c, rules)), deckCount: v.deckCount,
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
lanes, log: opts.log ?? [], waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
};
}
/** Results from `me`'s point of view (winner stays an absolute seat; the screen compares it to `me`). */
export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
const opp: PlayerId = me === 0 ? 1 : 0;
return {
winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
lanes: r.lanePower.map((pw, i) => {
const a = pw[me], b = pw[opp];
return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
}),
};
}
/** Engine actions from a host's legalActions, mapped for the UI (the host checks the seat). */
export const uiActions = (acts: Action[]): UIAction[] => acts.map(toUI);
export const engineAction = toEngine;
+64
View File
@@ -0,0 +1,64 @@
// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
// peers' modes are opened on the peer's own site. Every response is untrusted input.
import type { Action, PlayerView } from '../../shared/game/index.ts';
export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
export type DraftCard = { index: number; takenBy: 0 | 1 | null; card: { cardId: string; title: string; pageId: number | null; faction: string; cost: number; power: number; home: string; trend: number; keyword: string | null } };
export type LobbyStatus = {
lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
seat: 0 | 1 | null; players: { id: string; name: string }[];
outcome: { winner: 0 | 1 | null; reason: string } | null;
state?: PlayerView; legalActions?: Action[];
draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
};
export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
const MASTER_KEY = 'wikideck-player-master';
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
function masterSecret(): string {
try {
const existing = localStorage.getItem(MASTER_KEY);
if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
localStorage.setItem(MASTER_KEY, fresh);
return fresh;
} catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
}
/**
* Per-host player secret: base64url(HMAC-SHA256(master, hostOrigin)), 43 chars. A host derives the
* leaderboard id from it, so a malicious host can't replay it on another host (night-review, #5).
*/
export async function playerSecret(hostOrigin: string): Promise<string> {
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(masterSecret()), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
}
/** Host display names allow 1–24 letters, digits, spaces and _ . - */
export function lobbyName(name: string | undefined): string {
const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
return clean || `Guest ${masterSecret().slice(0, 4)}`;
}
async function call<T>(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<T> {
const res = await fetch(`/api/game/${path}`, {
method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
});
const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
return data as T;
}
const id = (s: string) => encodeURIComponent(s);
export const online = {
openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
create: async (modeId: string, name: string, hostOrigin: string) => call<LobbySeat>(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }),
join: async (lobbyId: string, name: string, hostOrigin: string) => call<LobbySeat>(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }),
status: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}`, { token: s.token }),
act: (s: LobbySeat, action: Action) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }),
pick: (s: LobbySeat, index: number) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
resign: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
};
+2
View File
@@ -77,6 +77,8 @@ export type ResultView = {
export type GameMode = {
id: string;
/** The host's own mode id (for /api/game/modes/:id/...). */
remoteId?: string;
name: string;
description: string;
host: { kind: 'local' } | { kind: 'peer'; name: string; url: string; self: boolean };
+1 -1
View File
@@ -27,7 +27,7 @@ export function parseModeList(data: unknown, where: { self: boolean; origin: str
const id = str(m?.id, 64), name = str(m?.name, 60);
const ruleset = rulesFor(m?.rules);
if (!id || !name || !ruleset) return [];
return [{ id: `${where.self ? 'self' : origin}:${id}`, name, description: str(m?.description, 280) ?? '',
return [{ id: `${where.self ? 'self' : origin}:${id}`, remoteId: id, name, description: str(m?.description, 280) ?? '',
host: { kind: 'peer', name: operator, url: /^https?:\/\//.test(origin) ? origin : '', self: where.self },
ruleset, players: num(stats?.playersOnline), matchesPlayed: num(stats?.matchesPlayed) }];
});