forked from WikiDeck/wikideck
Play: online results from each player's side; finish timer survives polls
Found with a two-browser test against the modes host: the seat-1 player saw Defeat after winning (ResultView is now viewer-relative), and a poll could cancel the move to the results screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+138
-134
@@ -1,134 +1,138 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-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 { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
|
||||||
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
|
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
|
||||||
import { toUICard } from './cards.ts';
|
import { toUICard } from './cards.ts';
|
||||||
import { GameCard as GameCardFace } from './GameCard.tsx';
|
import { GameCard as GameCardFace } from './GameCard.tsx';
|
||||||
import { MatchBoard } from './MatchBoard.tsx';
|
import { MatchBoard } from './MatchBoard.tsx';
|
||||||
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
|
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
|
||||||
import type { GameMode, ResultView, UIAction } from './types.ts';
|
import type { GameMode, ResultView, UIAction } from './types.ts';
|
||||||
|
|
||||||
const POLL_MS = 1000;
|
const POLL_MS = 1000;
|
||||||
const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
|
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. */
|
/** 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 }: {
|
export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||||
mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
|
mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
|
||||||
}) {
|
}) {
|
||||||
const modeId = mode.remoteId ?? mode.id;
|
const modeId = mode.remoteId ?? mode.id;
|
||||||
const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
|
const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
|
||||||
const [lobbies, setLobbies] = useState<OpenLobby[]>();
|
const [lobbies, setLobbies] = useState<OpenLobby[]>();
|
||||||
const [seat, setSeat] = useState<LobbySeat>();
|
const [seat, setSeat] = useState<LobbySeat>();
|
||||||
const [status, setStatus] = useState<LobbyStatus>();
|
const [status, setStatus] = useState<LobbyStatus>();
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const inFlight = useRef(false);
|
const inFlight = useRef(false);
|
||||||
const finished = useRef(false);
|
const finished = useRef(false);
|
||||||
|
const done = status?.phase === 'finished' || status?.phase === 'expired';
|
||||||
const refreshLobbies = useCallback(() => {
|
|
||||||
online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
|
const refreshLobbies = useCallback(() => {
|
||||||
}, [modeId]);
|
online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
|
||||||
useEffect(() => {
|
}, [modeId]);
|
||||||
if (seat) return;
|
useEffect(() => {
|
||||||
refreshLobbies();
|
if (seat) return;
|
||||||
const t = setInterval(refreshLobbies, 4000);
|
refreshLobbies();
|
||||||
return () => clearInterval(t);
|
const t = setInterval(refreshLobbies, 4000);
|
||||||
}, [seat, refreshLobbies]);
|
return () => clearInterval(t);
|
||||||
|
}, [seat, refreshLobbies]);
|
||||||
const poll = useCallback(async () => {
|
|
||||||
if (!seat || inFlight.current) return;
|
const poll = useCallback(async () => {
|
||||||
inFlight.current = true;
|
if (!seat || inFlight.current) return;
|
||||||
try { setStatus(await online.status(seat)); setError(''); }
|
inFlight.current = true;
|
||||||
catch (e) { setError(message(e)); }
|
try { setStatus(await online.status(seat)); setError(''); }
|
||||||
finally { inFlight.current = false; }
|
catch (e) { setError(message(e)); }
|
||||||
}, [seat]);
|
finally { inFlight.current = false; }
|
||||||
useEffect(() => {
|
}, [seat]);
|
||||||
if (!seat) return;
|
useEffect(() => {
|
||||||
void poll();
|
if (!seat || done) return;
|
||||||
const t = setInterval(() => { void poll(); }, POLL_MS);
|
void poll();
|
||||||
return () => clearInterval(t);
|
const t = setInterval(() => { void poll(); }, POLL_MS);
|
||||||
}, [seat, poll]);
|
return () => clearInterval(t);
|
||||||
|
}, [seat, poll, done]);
|
||||||
useEffect(() => {
|
|
||||||
const st = status?.state;
|
// Once finished, stop polling and show results after a beat. The timer must survive later
|
||||||
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
|
// re-renders, so it is only cleared on unmount.
|
||||||
finished.current = true;
|
const finishTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||||
const names = st.lanes.map(l => l.topic.name);
|
useEffect(() => {
|
||||||
const t = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
|
const st = status?.state;
|
||||||
return () => clearTimeout(t);
|
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
|
||||||
}, [status, seat, onFinish]);
|
finished.current = true;
|
||||||
|
const names = st.lanes.map(l => l.topic.name);
|
||||||
const enter = async (fn: () => Promise<LobbySeat>) => {
|
finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
|
||||||
setBusy(true); setError('');
|
}, [status, seat, onFinish]);
|
||||||
try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
|
useEffect(() => () => clearTimeout(finishTimer.current), []);
|
||||||
};
|
|
||||||
const leave = async () => {
|
const enter = async (fn: () => Promise<LobbySeat>) => {
|
||||||
if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
|
setBusy(true); setError('');
|
||||||
onExit();
|
try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
|
||||||
};
|
};
|
||||||
const send = async (fn: () => Promise<LobbyStatus>) => {
|
const leave = async () => {
|
||||||
try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
|
if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
|
||||||
};
|
onExit();
|
||||||
|
};
|
||||||
// ----- lobby list -----
|
const send = async (fn: () => Promise<LobbyStatus>) => {
|
||||||
if (!seat) return <section className="play-panel online-lobby" aria-labelledby="online-title">
|
try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
|
||||||
<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>
|
// ----- lobby list -----
|
||||||
<h3 className="lobby-label">Open lobbies <button className="icon-button" onClick={refreshLobbies} aria-label="Refresh lobbies"><RefreshCw size={14} /></button></h3>
|
if (!seat) return <section className="play-panel online-lobby" aria-labelledby="online-title">
|
||||||
<div className="mode-list">
|
<div className="section-eyebrow">{mode.name.toUpperCase()} · ONLINE</div>
|
||||||
{lobbies === undefined ? <p className="muted small"><LoaderCircle className="spin" size={13} /> Loading…</p>
|
<h2 id="online-title">Play a person</h2>
|
||||||
: lobbies.length ? lobbies.map(l => <button key={l.lobbyId} className="mode" disabled={busy} onClick={() => enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
|
<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>
|
||||||
<span className="mode-icon"><Users size={18} /></span>
|
<h3 className="lobby-label">Open lobbies <button className="icon-button" onClick={refreshLobbies} aria-label="Refresh lobbies"><RefreshCw size={14} /></button></h3>
|
||||||
<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>
|
<div className="mode-list">
|
||||||
</button>)
|
{lobbies === undefined ? <p className="muted small"><LoaderCircle className="spin" size={13} /> Loading…</p>
|
||||||
: <p className="muted small">No one is waiting. Create a lobby and share this page with a friend.</p>}
|
: lobbies.length ? lobbies.map(l => <button key={l.lobbyId} className="mode" disabled={busy} onClick={() => enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
|
||||||
</div>
|
<span className="mode-icon"><Users size={18} /></span>
|
||||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
<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>
|
||||||
<div className="play-dock"><div className="play-actions">
|
</button>)
|
||||||
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> Back</button>
|
: <p className="muted small">No one is waiting. Create a lobby and share this page with a friend.</p>}
|
||||||
<button className="button dark play-cta" disabled={busy} onClick={() => enter(() => online.create(modeId, playerName, hostOrigin))}><Plus size={16} /> Create lobby</button>
|
</div>
|
||||||
</div></div>
|
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||||
</section>;
|
<div className="play-dock"><div className="play-actions">
|
||||||
|
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> Back</button>
|
||||||
const phase = status?.phase;
|
<button className="button dark play-cta" disabled={busy} onClick={() => enter(() => online.create(modeId, playerName, hostOrigin))}><Plus size={16} /> Create lobby</button>
|
||||||
// ----- match -----
|
</div></div>
|
||||||
if ((phase === 'playing' || phase === 'finished') && status?.state) {
|
</section>;
|
||||||
const view = viewFromPlayerView(status.state);
|
|
||||||
const legal = uiActions(status.legalActions ?? []);
|
const phase = status?.phase;
|
||||||
const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
|
// ----- match -----
|
||||||
const act = (a: UIAction) => {
|
if ((phase === 'playing' || phase === 'finished') && status?.state) {
|
||||||
if (a.type === 'concede') return void send(() => online.resign(seat));
|
const view = viewFromPlayerView(status.state);
|
||||||
return void send(() => online.act(seat, engineAction(a, seat.seat)));
|
const legal = uiActions(status.legalActions ?? []);
|
||||||
};
|
const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
|
||||||
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
|
const act = (a: UIAction) => {
|
||||||
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
|
if (a.type === 'concede') return void send(() => online.resign(seat));
|
||||||
}
|
return void send(() => online.act(seat, engineAction(a, seat.seat)));
|
||||||
|
};
|
||||||
// ----- draft -----
|
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
|
||||||
if (phase === 'drafting' && status?.draft) {
|
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
|
||||||
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);
|
// ----- draft -----
|
||||||
return <section className="play-panel" aria-labelledby="draft-title">
|
if (phase === 'drafting' && status?.draft) {
|
||||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · DRAFT</div>
|
const mine = status.draft.toPick === seat.seat;
|
||||||
<h2 id="draft-title">{mine ? 'Your pick' : 'Opponent is picking…'}</h2>
|
const toCard = (c: NonNullable<LobbyStatus['draft']>['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
|
||||||
<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>
|
faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
|
||||||
<div className="pool-grid">{status.draft.pool.map(p => <GameCardFace key={p.index} card={toCard(p.card)} size="deck"
|
return <section className="play-panel" aria-labelledby="draft-title">
|
||||||
selected={p.takenBy === seat.seat} dim={p.takenBy !== null && p.takenBy !== seat.seat}
|
<div className="section-eyebrow">{mode.name.toUpperCase()} · DRAFT</div>
|
||||||
onClick={mine && p.takenBy === null ? () => void send(() => online.pick(seat, p.index)) : undefined} />)}</div>
|
<h2 id="draft-title">{mine ? 'Your pick' : 'Opponent is picking…'}</h2>
|
||||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
<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="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}>Resign</button></div></div>
|
<div className="pool-grid">{status.draft.pool.map(p => <GameCardFace key={p.index} card={toCard(p.card)} size="deck"
|
||||||
</section>;
|
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>}
|
||||||
// ----- waiting / starting / expired -----
|
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}>Resign</button></div></div>
|
||||||
return <section className="play-panel" aria-labelledby="wait-title">
|
</section>;
|
||||||
<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.'
|
// ----- waiting / starting / expired -----
|
||||||
: <><LoaderCircle className="spin" size={14} /> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}</>}</p>
|
return <section className="play-panel" aria-labelledby="wait-title">
|
||||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
<div className="section-eyebrow">{mode.name.toUpperCase()} · LOBBY</div>
|
||||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {phase === 'expired' ? 'Back' : 'Cancel'}</button></div></div>
|
<h2 id="wait-title">{phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}</h2>
|
||||||
</section>;
|
<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>;
|
||||||
|
}
|
||||||
|
|||||||
+4
-3
@@ -115,14 +115,15 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Results from `me`'s point of view (winner stays an absolute seat; the screen compares it to `me`). */
|
/** Results from `me`'s point of view: in a ResultView, 0 always means "you" and 1 "your opponent". */
|
||||||
export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
|
export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
|
||||||
const opp: PlayerId = me === 0 ? 1 : 0;
|
const opp: PlayerId = me === 0 ? 1 : 0;
|
||||||
return {
|
return {
|
||||||
winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
|
winner: r.winner === null ? null : r.winner === me ? 0 : 1, turns: r.turns, reason: r.reason,
|
||||||
|
totalPower: [r.totalPower[me], r.totalPower[opp]],
|
||||||
lanes: r.lanePower.map((pw, i) => {
|
lanes: r.lanePower.map((pw, i) => {
|
||||||
const a = pw[me], b = pw[opp];
|
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 };
|
return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? 0 : 1 };
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+64
-64
@@ -1,64 +1,64 @@
|
|||||||
// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
|
// 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.
|
// peers' modes are opened on the peer's own site. Every response is untrusted input.
|
||||||
import type { Action, PlayerView } from '../../shared/game/index.ts';
|
import type { Action, PlayerView } from '../../shared/game/index.ts';
|
||||||
|
|
||||||
export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
|
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 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 = {
|
export type LobbyStatus = {
|
||||||
lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
|
lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
|
||||||
seat: 0 | 1 | null; players: { id: string; name: string }[];
|
seat: 0 | 1 | null; players: { id: string; name: string }[];
|
||||||
outcome: { winner: 0 | 1 | null; reason: string } | null;
|
outcome: { winner: 0 | 1 | null; reason: string } | null;
|
||||||
state?: PlayerView; legalActions?: Action[];
|
state?: PlayerView; legalActions?: Action[];
|
||||||
draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
|
draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
|
||||||
};
|
};
|
||||||
export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
|
export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
|
||||||
|
|
||||||
const MASTER_KEY = 'wikideck-player-master';
|
const MASTER_KEY = 'wikideck-player-master';
|
||||||
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||||
|
|
||||||
function masterSecret(): string {
|
function masterSecret(): string {
|
||||||
try {
|
try {
|
||||||
const existing = localStorage.getItem(MASTER_KEY);
|
const existing = localStorage.getItem(MASTER_KEY);
|
||||||
if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
|
if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
|
||||||
const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
||||||
localStorage.setItem(MASTER_KEY, fresh);
|
localStorage.setItem(MASTER_KEY, fresh);
|
||||||
return fresh;
|
return fresh;
|
||||||
} catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
|
} 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
|
* 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).
|
* 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> {
|
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']);
|
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))));
|
return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Host display names allow 1–24 letters, digits, spaces and _ . - */
|
/** Host display names allow 1–24 letters, digits, spaces and _ . - */
|
||||||
export function lobbyName(name: string | undefined): string {
|
export function lobbyName(name: string | undefined): string {
|
||||||
const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
|
const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
|
||||||
return clean || `Guest ${masterSecret().slice(0, 4)}`;
|
return clean || `Guest ${masterSecret().slice(0, 4)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function call<T>(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<T> {
|
async function call<T>(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<T> {
|
||||||
const res = await fetch(`/api/game/${path}`, {
|
const res = await fetch(`/api/game/${path}`, {
|
||||||
method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
|
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}` } : {}) },
|
headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
|
||||||
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
|
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
|
||||||
});
|
});
|
||||||
const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
|
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}.`);
|
if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
|
||||||
return data as T;
|
return data as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = (s: string) => encodeURIComponent(s);
|
const id = (s: string) => encodeURIComponent(s);
|
||||||
export const online = {
|
export const online = {
|
||||||
openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
|
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) } }),
|
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) } }),
|
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 }),
|
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 }),
|
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 }),
|
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 }),
|
resign: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
|
||||||
};
|
};
|
||||||
|
|||||||
+2
-1
@@ -67,8 +67,9 @@ export type UIAction = (
|
|||||||
| { type: 'concede' }
|
| { type: 'concede' }
|
||||||
) & { engine?: Action };
|
) & { engine?: Action };
|
||||||
|
|
||||||
|
/** Always from the viewer's side: 0 = you, 1 = your opponent, null = draw. */
|
||||||
export type ResultView = {
|
export type ResultView = {
|
||||||
winner: PlayerIndex | null; // null = draw
|
winner: PlayerIndex | null;
|
||||||
lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
|
lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
|
||||||
turns: number;
|
turns: number;
|
||||||
reason: MatchResult['reason'];
|
reason: MatchResult['reason'];
|
||||||
|
|||||||
+108
-106
@@ -1,106 +1,108 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
||||||
import { engine } from '../src/game/adapter.ts';
|
import { engine } from '../src/game/adapter.ts';
|
||||||
import { randomBot } from '../src/game/bots.ts';
|
import { randomBot } from '../src/game/bots.ts';
|
||||||
import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
|
import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
|
||||||
import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
|
import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
|
||||||
import { parseModeList } from '../src/game/useModes.ts';
|
import { parseModeList } from '../src/game/useModes.ts';
|
||||||
import type { PlayerIndex } from '../src/game/types.ts';
|
import type { PlayerIndex } from '../src/game/types.ts';
|
||||||
import type { TestnetBlock } from '../shared/testnet.ts';
|
import type { TestnetBlock } from '../shared/testnet.ts';
|
||||||
|
|
||||||
function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
|
function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
|
||||||
|
|
||||||
/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
|
/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
|
||||||
function playOut(seed: string) {
|
function playOut(seed: string) {
|
||||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
|
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
|
||||||
const r = rand(seed.length * 7919 + 1);
|
const r = rand(seed.length * 7919 + 1);
|
||||||
for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
|
for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
|
||||||
for (const p of [0, 1] as PlayerIndex[]) {
|
for (const p of [0, 1] as PlayerIndex[]) {
|
||||||
const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
|
const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
|
||||||
if (!legal.length) continue;
|
if (!legal.length) continue;
|
||||||
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
|
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
|
test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
|
||||||
assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
|
assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
|
||||||
assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
|
assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
|
||||||
assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
|
assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
|
test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
|
||||||
const pool = loanerPool();
|
const pool = loanerPool();
|
||||||
const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
|
const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
|
||||||
assert.match(deckWarning(heavy), /cost 2 or less/);
|
assert.match(deckWarning(heavy), /cost 2 or less/);
|
||||||
assert.equal(deckWarning(starterDeck()), '');
|
assert.equal(deckWarning(starterDeck()), '');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
|
test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
|
||||||
for (let i = 0; i < 40; i++) {
|
for (let i = 0; i < 40; i++) {
|
||||||
const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
|
const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
|
||||||
assert.ok(engine.isOver(a), `match ${i} finished`);
|
assert.ok(engine.isOver(a), `match ${i} finished`);
|
||||||
const ra = engine.result(a, 0);
|
const ra = engine.result(a, 0);
|
||||||
assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
|
assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
|
||||||
assert.deepEqual(ra, engine.result(b, 0));
|
assert.deepEqual(ra, engine.result(b, 0));
|
||||||
assert.equal(engine.result(a, 1).winner, ra.winner);
|
const rb = engine.result(a, 1);
|
||||||
}
|
assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result');
|
||||||
});
|
assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]);
|
||||||
|
}
|
||||||
test('my view never shows the opponent’s queued cards', () => {
|
});
|
||||||
// Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
|
|
||||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
|
test('my view never shows the opponent’s queued cards', () => {
|
||||||
for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
|
// Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
|
||||||
s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
|
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
|
||||||
const play = engine.legal(s, 1).find(a => a.type === 'play');
|
for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
|
||||||
assert.ok(play, 'some seed gives the opponent a turn-1 play');
|
s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
|
||||||
s = engine.apply(s, 1, play!);
|
const play = engine.legal(s, 1).find(a => a.type === 'play');
|
||||||
const mine = engine.view(s, 0);
|
assert.ok(play, 'some seed gives the opponent a turn-1 play');
|
||||||
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
|
s = engine.apply(s, 1, play!);
|
||||||
assert.equal(mine.oppQueued, 1);
|
const mine = engine.view(s, 0);
|
||||||
const theirs = engine.view(s, 1);
|
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
|
||||||
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
|
assert.equal(mine.oppQueued, 1);
|
||||||
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
|
const theirs = engine.view(s, 1);
|
||||||
});
|
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
|
||||||
|
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
|
||||||
test('unstage refunds energy, and illegal plays are explained', () => {
|
});
|
||||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
|
|
||||||
const v = engine.view(s, 0);
|
test('unstage refunds energy, and illegal plays are explained', () => {
|
||||||
const expensive = v.hand.find(c => c.cost > v.energy);
|
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
|
||||||
if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
|
const v = engine.view(s, 0);
|
||||||
const play = engine.legal(s, 0).find(a => a.type === 'play');
|
const expensive = v.hand.find(c => c.cost > v.energy);
|
||||||
if (play?.type === 'play') {
|
if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
|
||||||
s = engine.apply(s, 0, play);
|
const play = engine.legal(s, 0).find(a => a.type === 'play');
|
||||||
assert.ok(engine.view(s, 0).energy < v.energy);
|
if (play?.type === 'play') {
|
||||||
s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
|
s = engine.apply(s, 0, play);
|
||||||
assert.equal(engine.view(s, 0).energy, v.energy);
|
assert.ok(engine.view(s, 0).energy < v.energy);
|
||||||
}
|
s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
|
||||||
});
|
assert.equal(engine.view(s, 0).energy, v.energy);
|
||||||
|
}
|
||||||
test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
|
});
|
||||||
const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
|
|
||||||
statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
|
test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
|
||||||
const card = cardFromBlock(block);
|
const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
|
||||||
assert.equal(card.source, 'nft');
|
statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
|
||||||
assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
|
const card = cardFromBlock(block);
|
||||||
assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
|
assert.equal(card.source, 'nft');
|
||||||
const deck = [card, ...starterDeck().slice(1)];
|
assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
|
||||||
assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
|
assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
|
||||||
});
|
const deck = [card, ...starterDeck().slice(1)];
|
||||||
|
assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
|
||||||
test('peer mode lists are parsed defensively', () => {
|
});
|
||||||
const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
|
|
||||||
{ mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
|
test('peer mode lists are parsed defensively', () => {
|
||||||
{ mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
|
const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
|
||||||
{ mode: { name: 'no id' } }, 'junk', null,
|
{ mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
|
||||||
] }, { self: false, origin: 'http://192.168.1.32:3102' });
|
{ mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
|
||||||
assert.equal(modes.length, 1);
|
{ mode: { name: 'no id' } }, 'junk', null,
|
||||||
const [m] = modes;
|
] }, { self: false, origin: 'http://192.168.1.32:3102' });
|
||||||
assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
|
assert.equal(modes.length, 1);
|
||||||
assert.equal(m.ruleset.turns, 5);
|
const [m] = modes;
|
||||||
assert.ok(m.description.length <= 280);
|
assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
|
||||||
assert.equal(m.players, 3);
|
assert.equal(m.ruleset.turns, 5);
|
||||||
assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
|
assert.ok(m.description.length <= 280);
|
||||||
});
|
assert.equal(m.players, 3);
|
||||||
|
assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user