From 60af45262d52a6f91842987b862c35656a9e9076 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:33:02 -0500 Subject: [PATCH] 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 --- src/game/MatchBoard.tsx | 123 +++++++++++++++++++++++++++++++++ src/game/MatchScreen.tsx | 144 +++++---------------------------------- src/game/OnlinePlay.tsx | 134 ++++++++++++++++++++++++++++++++++++ src/game/PlaySection.tsx | 16 +++-- src/game/adapter.ts | 97 +++++++++++++++----------- src/game/online.ts | 64 +++++++++++++++++ src/game/types.ts | 2 + src/game/useModes.ts | 2 +- 8 files changed, 411 insertions(+), 171 deletions(-) create mode 100644 src/game/MatchBoard.tsx create mode 100644 src/game/OnlinePlay.tsx create mode 100644 src/game/online.ts diff --git a/src/game/MatchBoard.tsx b/src/game/MatchBoard.tsx new file mode 100644 index 0000000..4ca0085 --- /dev/null +++ b/src/game/MatchBoard.tsx @@ -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(); + const [sheet, setSheet] = useState(null); + const [banner, setBanner] = useState(''); + const prevBoard = useRef(new Set()); + const [fresh, setFresh] = useState(new Set()); + 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
+
+ Turn {view.turn}/{view.maxTurns} + {opponent} · {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''} + +
+ {banner &&
{banner}
} + +
+ {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
+
+ {lane.theirs.map(c => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)} +
+ +
+ {lane.mine.map(c => setSheet({ kind: 'card', card: c, side: 'mine' })} />)} + {lane.staged.map(c => act({ type: 'unstage', cardId: c.id })} selected />)} + {target && {onTopic ? `On-topic +${topicBonus}` : 'Play here'}} +
+
; + })} +
+ +
+

+ {error ? {error} + : ending ? <> Opponent is choosing… + : sel ? <> {sel.title}{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane. + : lastEvent} +

+
+ {view.hand.length ? view.hand.map(c => setSelected(selected === c.id ? undefined : c.id)} />) + : No cards in hand.} +
+
+ + {Array.from({ length: view.maxEnergy }, (_, i) => )} + {view.energy} + + {view.deckCount} + +
+
+ + {sheet &&
{ if (e.target === e.currentTarget) setSheet(null); }}> +
+ + {sheet.kind === 'card' && <>
+

{sheet.card.title}

{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})` : ''}

+ {sheet.card.keyword &&

{sheet.card.keyword.name}. {sheet.card.keyword.text}

}} + {sheet.kind === 'lane' && <>

{sheet.lane.name}

+

Judged on {STAT_LABEL[sheet.lane.stat]} ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.

+ {sheet.lane.modifier ?

Portal: {sheet.lane.modifier.name}. {sheet.lane.modifier.text}

: sheet.lane.portalNote &&

{sheet.lane.portalNote}.

} +

You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.

+ {sel && !canPlay(sel.id, sheet.lane.index) &&

{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')}.

}} + {sheet.kind === 'concede' && <>

Concede this match?

It counts as a loss. Nothing on-chain changes.

+
+
} +
+
} +
; +} diff --git a/src/game/MatchScreen.tsx b/src/game/MatchScreen.tsx index 69ef793..171e624 100644 --- a/src/game/MatchScreen.tsx +++ b/src/game/MatchScreen.tsx @@ -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(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed)); - const [selected, setSelected] = useState(); - const [sheet, setSheet] = useState(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()); - const [fresh, setFresh] = useState(new Set()); - // 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
-
- Turn {view.turn}/{view.maxTurns} - {bot.name} bot · {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''} - -
- {banner &&
{banner}
} - -
- {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
-
- {lane.theirs.map(c => setSheet({ kind: 'card', card: c, side: 'theirs' })} />)} -
- -
- {lane.mine.map(c => setSheet({ kind: 'card', card: c, side: 'mine' })} />)} - {lane.staged.map(c => act({ type: 'unstage', cardId: c.id })} selected />)} - {target && {onTopic ? `On-topic +${topicBonus}` : 'Play here'}} -
-
; - })} -
- -
-

- {error ? {error} - : ending ? <> Opponent is choosing… - : sel ? <> {sel.title}{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane. - : lastEvent} -

-
- {view.hand.length ? view.hand.map(c => setSelected(selected === c.id ? undefined : c.id)} />) - : No cards in hand.} -
-
- - {Array.from({ length: view.maxEnergy }, (_, i) => )} - {view.energy} - - {view.deckCount} - -
-
- - {sheet &&
{ if (e.target === e.currentTarget) setSheet(null); }}> -
- - {sheet.kind === 'card' && <>
-

{sheet.card.title}

{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})` : ''}

- {sheet.card.keyword &&

{sheet.card.keyword.name}. {sheet.card.keyword.text}

}} - {sheet.kind === 'lane' && <>

{sheet.lane.name}

-

Judged on {STAT_LABEL[sheet.lane.stat]} ({STAT_HINT[sheet.lane.stat]}). Cards whose home stat is {STAT_LABEL[sheet.lane.stat]} get an on-topic bonus here.

- {sheet.lane.modifier ?

Portal: {sheet.lane.modifier.name}. {sheet.lane.modifier.text}

: sheet.lane.portalNote &&

{sheet.lane.portalNote}.

} -

You {sheet.lane.myPower} · Opponent {sheet.lane.theirPower} · up to {sheet.lane.capacity} cards each.

- {sel && !canPlay(sel.id, sheet.lane.index) &&

{sel.title} can’t go here: {engine.problem(state, 0, { type: 'play', cardId: sel.id, lane: sheet.lane.index }) ?? 'not allowed'}.

}} - {sheet.kind === 'concede' && <>

Concede this match?

It counts as a loss. Nothing on-chain changes.

-
-
} -
-
} -
; + return engine.problem(state, 0, a)} onTopicBonus={mode.ruleset.onTopicBonus} />; } diff --git a/src/game/OnlinePlay.tsx b/src/game/OnlinePlay.tsx new file mode 100644 index 0000000..737c33b --- /dev/null +++ b/src/game/OnlinePlay.tsx @@ -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(); + const [seat, setSeat] = useState(); + const [status, setStatus] = useState(); + 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) => { + 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) => { + try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); } + }; + + // ----- lobby list ----- + if (!seat) return
+
{mode.name.toUpperCase()} · ONLINE
+

Play a person

+

Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as {playerName}.

+

Open lobbies

+
+ {lobbies === undefined ?

Loading…

+ : lobbies.length ? lobbies.map(l => ) + :

No one is waiting. Create a lobby and share this page with a friend.

} +
+ {error &&

{error}

} +
+ + +
+
; + + 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 ; + } + + // ----- draft ----- + if (phase === 'drafting' && status?.draft) { + const mine = status.draft.toPick === seat.seat; + const toCard = (c: NonNullable['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
+
{mode.name.toUpperCase()} · DRAFT
+

{mine ? 'Your pick' : 'Opponent is picking…'}

+

Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.

+
{status.draft.pool.map(p => void send(() => online.pick(seat, p.index)) : undefined} />)}
+ {error &&

{error}

} +
+
; + } + + // ----- waiting / starting / expired ----- + return
+
{mode.name.toUpperCase()} · LOBBY
+

{phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}

+

{phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.' + : <> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}}

+ {error &&

{error}

} +
+
; +} diff --git a/src/game/PlaySection.tsx b/src/game/PlaySection.tsx index a3425bc..6635139 100644 --- a/src/game/PlaySection.tsx +++ b/src/game/PlaySection.tsx @@ -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 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 ; - if (screen === 'results' && result) return setScreen('lobby')} />; + if (screen === 'online') return setScreen('lobby')} onFinish={finish} />; + if (screen === 'results' && result) return 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
PLAY · OFF-CHAIN MATCHES

Play WikiDeck

@@ -106,6 +111,7 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
+ {hosted && }
} diff --git a/src/game/adapter.ts b/src/game/adapter.ts index 8ad96c1..e70e38c 100644 --- a/src/game/adapter.ts +++ b/src/game/adapter.ts @@ -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(); 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; diff --git a/src/game/online.ts b/src/game/online.ts new file mode 100644 index 0000000..1a8f4cc --- /dev/null +++ b/src/game/online.ts @@ -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 { + 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(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise { + 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(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }), + join: async (lobbyId: string, name: string, hostOrigin: string) => call(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }), + status: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}`, { token: s.token }), + act: (s: LobbySeat, action: Action) => call(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }), + pick: (s: LobbySeat, index: number) => call(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }), + resign: (s: LobbySeat) => call(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }), +}; diff --git a/src/game/types.ts b/src/game/types.ts index 8a30c4e..ff7dd74 100644 --- a/src/game/types.ts +++ b/src/game/types.ts @@ -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 }; diff --git a/src/game/useModes.ts b/src/game/useModes.ts index 9eb4391..7ee02f8 100644 --- a/src/game/useModes.ts +++ b/src/game/useModes.ts @@ -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) }]; });