forked from WikiDeck/wikideck
Play: wire the real shared/game engine (DESIGN v1 Edit War)
Replace the mock with an adapter over shared/game/index.ts: Topics with stats and hidden Portals, home-stat icons and on-topic hints, queued plays with undo, interleaved reveal log, engine deck validation, loaner starter decks, interim NFT derivation (cost-capped). Lobby reads the modes API (self + peers) and links to peer hosts; the account chip uses the SSO hook; the floating account button hides during a match. MatchView.engine / UIAction.engine expose engine state for ui-b's bots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,15 +2,12 @@ import { useMemo, useState } from 'react';
|
||||
import { Check, RotateCcw, Trash2 } from 'lucide-react';
|
||||
import { GameCard } from './GameCard.tsx';
|
||||
import { starterDeck } from './cards.ts';
|
||||
import type { Ruleset, UICard } from './types.ts';
|
||||
import { validateDeck, type Ruleset } from '../../shared/game/index.ts';
|
||||
import type { UICard } from './types.ts';
|
||||
|
||||
export function deckProblem(deck: UICard[], ruleset: Ruleset): string {
|
||||
if (deck.length !== ruleset.deckSize) return `A deck needs exactly ${ruleset.deckSize} cards (${deck.length} now).`;
|
||||
const counts = new Map<number, number>();
|
||||
for (const c of deck) counts.set(c.pageId, (counts.get(c.pageId) ?? 0) + 1);
|
||||
const over = [...counts].find(([, n]) => n > ruleset.maxCopies);
|
||||
if (over) return `At most ${ruleset.maxCopies} copies of the same article.`;
|
||||
return '';
|
||||
return validateDeck(ruleset, deck.map(c => c.game))[0] ?? '';
|
||||
}
|
||||
|
||||
/** Soft advice (DESIGN.md s8): warn, never block, when the early curve is thin. */
|
||||
@@ -19,8 +16,8 @@ export function deckWarning(deck: UICard[]): string {
|
||||
return cheap < 4 ? `Only ${cheap} card${cheap === 1 ? '' : 's'} cost 2 or less. Aim for at least 4 so you have early plays.` : '';
|
||||
}
|
||||
|
||||
export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
|
||||
pool: UICard[]; deck: UICard[]; ruleset: Ruleset; onSave: (deck: UICard[]) => void; onCancel: () => void;
|
||||
export function DeckBuilder({ pool, deck, ruleset, modeName, onSave, onCancel }: {
|
||||
modeName: string; pool: UICard[]; deck: UICard[]; ruleset: Ruleset; onSave: (deck: UICard[]) => void; onCancel: () => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<UICard[]>(deck);
|
||||
const [filter, setFilter] = useState<'all' | 'starter' | 'nft'>('all');
|
||||
@@ -37,7 +34,7 @@ export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
|
||||
const full = draft.length >= ruleset.deckSize;
|
||||
|
||||
return <section className="play-panel deck-builder" aria-labelledby="deck-title">
|
||||
<div className="section-eyebrow">DECK BUILDER · {ruleset.name.toUpperCase()}</div>
|
||||
<div className="section-eyebrow">DECK BUILDER · {modeName.toUpperCase()}</div>
|
||||
<h2 id="deck-title">Your deck <span className={`count-badge ${problem ? '' : 'ok'}`}>{draft.length} / {ruleset.deckSize}</span></h2>
|
||||
<p className="muted">Tap a card to add it or take it out. Loaner cards are free previews, not NFTs; nothing you do here moves a card on-chain.</p>
|
||||
<div className="deck-curve" aria-label="Cost curve">{curve.map((n, i) => <div key={i}><span style={{ height: `${Math.min(100, n * 22)}%` }} /><b>{i + 1}{i === 5 ? '+' : ''}</b><small>{n}</small></div>)}</div>
|
||||
@@ -58,7 +55,7 @@ export function DeckBuilder({ pool, deck, ruleset, onSave, onCancel }: {
|
||||
{problem ? <p className="dock-note" role="status">{problem}</p>
|
||||
: warning && <p className="dock-note deck-warning" role="status">{warning}</p>}
|
||||
<div className="play-actions">
|
||||
<button className="button outline" onClick={() => setDraft(starterDeck())}><RotateCcw size={16} /> Starter</button>
|
||||
<button className="button outline" onClick={() => setDraft(starterDeck(ruleset))}><RotateCcw size={16} /> Starter</button>
|
||||
<button className="button outline" onClick={() => setDraft([])} aria-label="Clear deck"><Trash2 size={16} /></button>
|
||||
<button className="button outline" onClick={onCancel}>Cancel</button>
|
||||
<button className="button dark" disabled={!!problem} onClick={() => onSave(draft)}><Check size={16} /> Save deck</button>
|
||||
|
||||
+17
-5
@@ -1,13 +1,23 @@
|
||||
import { BookOpen, Landmark, Leaf, Orbit, Palette, Users, Zap } from 'lucide-react';
|
||||
import type { UICard } from './types.ts';
|
||||
import { BookOpen, ChevronDown, ChevronUp, Eye, Globe2, Landmark, Leaf, Library, Orbit, Palette, Users, Zap } from 'lucide-react';
|
||||
import type { Stat, UICard } from './types.ts';
|
||||
import { STAT_LABEL } from './rulesText.ts';
|
||||
|
||||
const ICONS: Record<string, typeof Leaf> = { Space: Orbit, Nature: Leaf, People: Users, Science: BookOpen, History: Landmark, Culture: Palette };
|
||||
export const CategoryIcon = ({ category, size = 14 }: { category: string; size?: number }) => {
|
||||
const Icon = ICONS[category] ?? Palette;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
const STAT_ICONS: Record<Stat, typeof Eye> = { attention: Eye, depth: Library, reach: Globe2 };
|
||||
export const StatIcon = ({ stat, size = 12 }: { stat: Stat; size?: number }) => {
|
||||
const Icon = STAT_ICONS[stat];
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
/** Phone-readable card face: cost, power, one keyword, title. Nothing needs hover. */
|
||||
export function cardLabel(card: UICard) {
|
||||
return `${card.title}, cost ${card.cost}, power ${card.power}, home stat ${STAT_LABEL[card.home]}${card.trend ? `, trending ${card.trend > 0 ? 'up' : 'down'}` : ''}${card.onTopic ? ', on-topic' : ''}${card.keyword ? `, ${card.keyword.name}: ${card.keyword.text}` : ''}`;
|
||||
}
|
||||
|
||||
/** Phone-readable card face (DESIGN §1.9): cost, power, home-stat icon, trend arrow, one keyword. Nothing needs hover. */
|
||||
export function GameCard({ card, size = 'hand', selected, dim, onClick, label, fresh }: {
|
||||
card: UICard; size?: 'hand' | 'board' | 'deck'; selected?: boolean; dim?: boolean; fresh?: boolean;
|
||||
onClick?: () => void; label?: string;
|
||||
@@ -15,14 +25,16 @@ export function GameCard({ card, size = 'hand', selected, dim, onClick, label, f
|
||||
const buffed = card.power > card.basePower, nerfed = card.power < card.basePower;
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
return <Tag {...(onClick ? { type: 'button' as const, onClick, 'aria-pressed': selected } : { role: 'img' })}
|
||||
className={`gcard gcard-${size} cat-${card.category.toLowerCase()} ${selected ? 'is-selected' : ''} ${dim ? 'is-dim' : ''} ${fresh ? 'is-fresh' : ''}`}
|
||||
aria-label={label ?? `${card.title}, cost ${card.cost}, power ${card.power}${card.keyword ? `, ${card.keyword.name}: ${card.keyword.text}` : ''}`}>
|
||||
className={`gcard gcard-${size} cat-${card.category.toLowerCase()} ${selected ? 'is-selected' : ''} ${dim ? 'is-dim' : ''} ${fresh ? 'is-fresh' : ''} ${card.onTopic ? 'is-on-topic' : ''}`}
|
||||
aria-label={label ?? cardLabel(card)}>
|
||||
<span className="gcard-cost" aria-hidden="true">{card.cost}</span>
|
||||
<span className={`gcard-power ${buffed ? 'up' : nerfed ? 'down' : ''}`} aria-hidden="true">{card.power}</span>
|
||||
<span className="gcard-art" aria-hidden="true">
|
||||
{card.image ? <img src={card.image} alt="" loading="lazy" referrerPolicy="no-referrer" onError={e => { e.currentTarget.style.display = 'none'; }} /> : null}
|
||||
<CategoryIcon category={card.category} size={size === 'board' ? 12 : 18} />
|
||||
</span>
|
||||
<span className="gcard-home" aria-hidden="true" title={STAT_LABEL[card.home]}><StatIcon stat={card.home} size={size === 'board' ? 10 : 12} />
|
||||
{card.trend > 0 && <ChevronUp size={11} className="trend up" />}{card.trend < 0 && <ChevronDown size={11} className="trend down" />}</span>
|
||||
<span className="gcard-title">{card.title}</span>
|
||||
{card.keyword && size !== 'board' && <span className="gcard-keyword"><Zap size={10} aria-hidden="true" />{card.keyword.name}</span>}
|
||||
{card.source === 'nft' && size !== 'board' && <span className="gcard-nft">NFT</span>}
|
||||
|
||||
+18
-12
@@ -2,7 +2,9 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Flag, Hourglass, Layers3, LoaderCircle, X, Zap } from 'lucide-react';
|
||||
import { engine } from './adapter.ts';
|
||||
import type { Bot } from './bots.ts';
|
||||
import { GameCard } from './GameCard.tsx';
|
||||
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';
|
||||
|
||||
const BOT_DELAY_MS = 450;
|
||||
@@ -18,7 +20,7 @@ type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: '
|
||||
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<unknown>(() => engine.createMatch(mode.ruleset, [deck, opponentDeck], seed));
|
||||
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('');
|
||||
@@ -51,7 +53,7 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
useEffect(() => {
|
||||
if (!view.waitingForOpponent) return;
|
||||
const t = setTimeout(() => {
|
||||
setState((s: unknown) => {
|
||||
setState((s: MatchState) => {
|
||||
let cur = s;
|
||||
for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
|
||||
const acts = engine.legal(cur, 1);
|
||||
@@ -67,7 +69,7 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
}, [view.waitingForOpponent, state, bot]);
|
||||
|
||||
const act = (a: UIAction) => {
|
||||
try { setState((s: unknown) => engine.apply(s, 0, a)); setError(''); }
|
||||
try { setState((s: MatchState) => engine.apply(s, 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);
|
||||
@@ -83,7 +85,7 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
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} in hand</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>}
|
||||
@@ -91,21 +93,23 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
<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.myPower > lane.theirPower ? 'ahead' : lane.myPower < lane.theirPower ? 'behind' : 'even';
|
||||
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}` : `${lane.name} lane: you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? ''}`}>
|
||||
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">{lane.modifier?.name ?? lane.name}</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">Play here</span>}
|
||||
{target && <span className={`lane-drop ${onTopic ? 'on-topic' : ''}`}>{onTopic ? `On-topic +${topicBonus}` : 'Play here'}</span>}
|
||||
</div>
|
||||
</div>;
|
||||
})}
|
||||
@@ -139,11 +143,13 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
<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}{sheet.card.power !== sheet.card.basePower ? ` (base ${sheet.card.basePower})` : ''}</p>
|
||||
<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>{sheet.lane.name} lane</h3>{sheet.lane.modifier && <p><b>{sheet.lane.modifier.name}.</b> {sheet.lane.modifier.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: {sel.cost > view.energy ? 'not enough energy' : 'this lane is full'}.</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></>}
|
||||
|
||||
+53
-37
@@ -1,31 +1,31 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { CircleHelp, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
|
||||
import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
|
||||
import type { TestnetBlock } from '../../shared/testnet.ts';
|
||||
import { engine } from './adapter.ts';
|
||||
import { Avatar } from '../auth/LoginButton.tsx';
|
||||
import { BOTS, type Bot } from './bots.ts';
|
||||
import { cardFromBlock, loanerPool, starterDeck } from './cards.ts';
|
||||
import { DeckBuilder, deckProblem } from './DeckBuilder.tsx';
|
||||
import { cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
|
||||
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
|
||||
import { CategoryIcon } from './GameCard.tsx';
|
||||
import { MatchScreen } from './MatchScreen.tsx';
|
||||
import { Results } from './Results.tsx';
|
||||
import { Tutorial } from './Tutorial.tsx';
|
||||
import type { GameMode, ResultView, UICard } from './types.ts';
|
||||
import type { GameMode, ResultView } from './types.ts';
|
||||
import { useAccount } from './useAccount.ts';
|
||||
import { useModes } from './useModes.ts';
|
||||
import './play.css';
|
||||
|
||||
type Screen = 'lobby' | 'deck' | 'match' | 'results' | 'tutorial';
|
||||
const DECK_KEY = 'wikideck-play-deck';
|
||||
const TUTORIAL_KEY = 'wikideck-play-tutorial-seen';
|
||||
const DECK_KEY = 'wikideck-play-deck-v1';
|
||||
const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
|
||||
const store = {
|
||||
get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
|
||||
set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* storage unavailable */ } },
|
||||
};
|
||||
const playsHere = (m: GameMode) => m.host.kind === 'local' || m.host.self;
|
||||
|
||||
export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
|
||||
const pool = useMemo(() => [...loanerPool(), ...owned.map(cardFromBlock)], [owned]);
|
||||
const { modes, status } = useModes();
|
||||
const { account, available: ssoAvailable, login, logout } = useAccount();
|
||||
const account = useAccount();
|
||||
const [screen, setScreen] = useState<Screen>(() => store.get(TUTORIAL_KEY) ? 'lobby' : 'tutorial');
|
||||
const [modeId, setModeId] = useState('standard');
|
||||
const [bot, setBot] = useState<Bot>(BOTS[0]);
|
||||
@@ -33,65 +33,81 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
|
||||
const [seed, setSeed] = useState('');
|
||||
const [result, setResult] = useState<ResultView>();
|
||||
const mode = modes.find(m => m.id === modeId) ?? modes[0];
|
||||
const rules = mode.ruleset;
|
||||
const pool = useMemo(() => [...loanerPool(rules), ...owned.map(b => cardFromBlock(b, rules))], [owned, rules]);
|
||||
|
||||
// Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
|
||||
const deck = useMemo(() => {
|
||||
if (!savedIds) return starterDeck();
|
||||
if (!savedIds) return starterDeck(rules);
|
||||
const byId = new Map(pool.map(c => [c.id, c]));
|
||||
return savedIds.flatMap(id => byId.get(id) ?? []);
|
||||
}, [savedIds, pool]);
|
||||
const problem = deckProblem(deck, mode.ruleset);
|
||||
const opponentDeck = useMemo(() => starterDeck(), []);
|
||||
}, [savedIds, pool, rules]);
|
||||
const problem = deckProblem(deck, rules);
|
||||
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 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');
|
||||
return () => document.documentElement.classList.remove('wd-in-match');
|
||||
}, [screen]);
|
||||
|
||||
if (screen === 'tutorial') return <Tutorial onDone={() => { store.set(TUTORIAL_KEY, '1'); setScreen('lobby'); }} />;
|
||||
if (screen === 'deck') return <DeckBuilder pool={pool} deck={deck} ruleset={mode.ruleset} onCancel={() => setScreen('lobby')}
|
||||
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={opponentDeck} bot={bot} seed={seed} onFinish={finish} />;
|
||||
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')} />;
|
||||
|
||||
const remote = mode.host.kind === 'peer' && !mode.host.self ? mode.host : null;
|
||||
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>
|
||||
<div className="account-chip">{account
|
||||
? <>{account.avatar ? <img src={account.avatar} alt="" /> : <UserRound size={15} />}<span>{account.name}</span>{logout && <button className="text-button" onClick={logout}>Log out</button>}</>
|
||||
: <><UserRound size={15} /><span>Guest</span><button className="text-button" disabled={!ssoAvailable} onClick={login} title={ssoAvailable ? undefined : 'eom.dev sign-in is coming soon'}>{ssoAvailable ? 'Sign in with eom.dev' : 'eom.dev sign-in soon'}</button></>}
|
||||
<div className="account-chip" aria-label="eom.dev account">{account
|
||||
? <><Avatar name={account.name || account.username} seed={account.sub} /><span>{account.name || account.username}</span></>
|
||||
: <><UserRound size={15} /><span>Guest</span></>}
|
||||
</div>
|
||||
</div>
|
||||
<p className="muted">Three lanes, six turns, win two lanes. New here? You already have a loaner starter deck. Matches never move or burn your cards.</p>
|
||||
<p className="muted">Three Topics, six turns: win two Topics. Each Topic is judged on one Wikipedia stat, and cards are stronger on their home stat. New here? You already have a loaner starter deck. Matches never move or burn your cards.</p>
|
||||
|
||||
<h3 className="lobby-label">Mode</h3>
|
||||
<div className="mode-list" role="radiogroup" aria-label="Game mode">
|
||||
{modes.map(m => <button key={m.id} role="radio" aria-checked={m.id === mode.id} className={`mode ${m.id === mode.id ? 'selected' : ''}`} onClick={() => setModeId(m.id)}>
|
||||
<span className="mode-icon">{m.host.kind === 'local' ? <Swords size={18} /> : <Server size={18} />}</span>
|
||||
<span className="mode-copy"><b>{m.name}</b><small>{m.description}</small>
|
||||
<small className="mode-host">{m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}{m.players !== undefined ? ` · ${m.players} playing` : ''}</small></span>
|
||||
<span className="mode-copy"><b>{m.name}</b>{m.description && <small>{m.description}</small>}
|
||||
<small className="mode-host">{m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}
|
||||
{m.players !== undefined ? ` · ${m.players} online` : ''}{m.matchesPlayed !== undefined ? ` · ${m.matchesPlayed} played` : ''}</small></span>
|
||||
</button>)}
|
||||
{status === 'loading' && <p className="muted small"><Globe2 size={13} /> Looking for peer-hosted modes…</p>}
|
||||
{status === 'unavailable' && <p className="muted small"><Globe2 size={13} /> No peer-hosted modes on this node yet.</p>}
|
||||
{status === 'unavailable' && <p className="muted small"><Globe2 size={13} /> No peer-hosted modes reachable from this node.</p>}
|
||||
</div>
|
||||
{mode.host.kind === 'peer' && <p className="muted small">Peer modes use their host’s rules. For now the match runs in your browser{engine.mock ? ' on the preview engine' : ''}.</p>}
|
||||
|
||||
<h3 className="lobby-label">Opponent</h3>
|
||||
<div className="category-tabs">{BOTS.map(b => <button key={b.id} className={bot.id === b.id ? 'selected' : ''} onClick={() => setBot(b)}>{b.name} bot</button>)}</div>
|
||||
{remote ? <>
|
||||
<p className="muted small">This mode runs on {remote.name}’s node. Open it there to play; your eom.dev account works on every node.</p>
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<button className="button outline" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /> How to play</button>
|
||||
{remote.url ? <a className="button dark play-cta" href={remote.url} target="_blank" rel="noopener noreferrer">Play on {remote.name} <ExternalLink size={16} /></a>
|
||||
: <button className="button dark play-cta" disabled>Host address unavailable</button>}
|
||||
</div></div>
|
||||
</> : <>
|
||||
<h3 className="lobby-label">Opponent</h3>
|
||||
<div className="category-tabs">{BOTS.map(b => <button key={b.id} className={bot.id === b.id ? 'selected' : ''} onClick={() => setBot(b)}>{b.name} bot</button>)}</div>
|
||||
|
||||
<h3 className="lobby-label">Deck <span className="count-badge">{deck.length}</span></h3>
|
||||
<button className="deck-summary" onClick={() => setScreen('deck')} aria-label="Edit deck">
|
||||
<span className="deck-fan" aria-hidden="true">{deck.slice(0, 4).map(c => <span key={c.id} className={`fan-chip cat-${c.category.toLowerCase()}`}><CategoryIcon category={c.category} size={14} /></span>)}</span>
|
||||
<span><b>{savedIds ? 'Your deck' : 'Starter deck'}</b><small>{deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners</small></span>
|
||||
<Layers3 size={18} />
|
||||
</button>
|
||||
{problem && <p className="dock-error small">{problem} Edit your deck to play {mode.name}.</p>}
|
||||
<h3 className="lobby-label">Deck <span className="count-badge">{deck.length}</span></h3>
|
||||
<button className="deck-summary" onClick={() => setScreen('deck')} aria-label="Edit deck">
|
||||
<span className="deck-fan" aria-hidden="true">{deck.slice(0, 4).map(c => <span key={c.id} className={`fan-chip cat-${c.category.toLowerCase()}`}><CategoryIcon category={c.category} size={14} /></span>)}</span>
|
||||
<span><b>{savedIds ? 'Your deck' : 'Starter deck'}</b><small>{deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners</small></span>
|
||||
<Layers3 size={18} />
|
||||
</button>
|
||||
{problem ? <p className="dock-error small">{problem} Edit your deck to play {mode.name}.</p>
|
||||
: warning && <p className="deck-warning small">{warning}</p>}
|
||||
|
||||
<div className="play-dock">
|
||||
<div className="play-actions">
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<button className="button outline" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /> How to play</button>
|
||||
<button className="button dark play-cta" disabled={!!problem} onClick={start}><Play size={16} /> Play vs {bot.name}</button>
|
||||
</div>
|
||||
</div>
|
||||
{engine.mock && <p className="muted small engine-note">Preview rules engine. The final rules arrive with the game engine.</p>}
|
||||
</div></div>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ export function Results({ result, modeName, onRematch, onLobby }: { result: Resu
|
||||
const outcome = result.winner === null ? 'draw' : result.winner === 0 ? 'win' : 'loss';
|
||||
const won = result.lanes.filter(l => l.winner === 0).length;
|
||||
const lost = result.lanes.filter(l => l.winner === 1).length;
|
||||
const tiebreak = result.reason === 'lanes' && won === lost;
|
||||
const tiebreak = result.reason === 'totalPower';
|
||||
return <section className={`play-panel results ${outcome}`} aria-labelledby="result-title">
|
||||
<div className="result-mark" aria-hidden="true"><Trophy size={34} /></div>
|
||||
<div className="section-eyebrow">{modeName.toUpperCase()} · {result.turns} TURNS</div>
|
||||
|
||||
+24
-18
@@ -1,22 +1,27 @@
|
||||
import { useState } from 'react';
|
||||
import { ArrowLeft, ArrowRight, Check } from 'lucide-react';
|
||||
import { GameCard } from './GameCard.tsx';
|
||||
import { GameCard, StatIcon } from './GameCard.tsx';
|
||||
import { starterDeck } from './cards.ts';
|
||||
import type { Stat } from './types.ts';
|
||||
|
||||
const demo = starterDeck();
|
||||
const pick = (cost: number) => demo.find(c => c.cost === cost) ?? demo[0];
|
||||
const TOPICS: [string, Stat, string][] = [['Current Events', 'attention', '9 – 5'], ['Archive', 'depth', '4 – 7'], ['Translations', 'reach', '6 – 3']];
|
||||
const STEPS = [
|
||||
{ title: 'Win two of three lanes', body: 'The board has three lanes. When the last turn ends, whoever has more power in a lane wins it. Win two lanes to win the match.',
|
||||
show: 'lanes' },
|
||||
{ title: 'Every card shows three things', body: 'The top-left number is cost: the energy it takes to play. The top-right number is power. The label at the bottom is its keyword: tap any card on the board to read what it does.',
|
||||
show: 'card' },
|
||||
{ title: 'Energy grows each turn', body: 'You get 1 energy on turn 1, 2 on turn 2, and so on up to 6. Energy you don’t spend is lost. Big famous articles cost more, so weigh them against cheaper cards.',
|
||||
show: 'energy' },
|
||||
{ title: 'Tap a card, then tap a lane', body: 'Tap a card in your hand to pick it up, then tap a lane to play it there. Tap a played card again before ending the turn to take it back. Each lane holds up to 4 of your cards.',
|
||||
show: 'play' },
|
||||
{ title: 'Both players reveal together', body: 'Plays stay face down until both players press End turn. Then everything is revealed and keywords trigger. Your opponent can’t see what you planned, so bluff!',
|
||||
show: 'reveal' },
|
||||
{ title: 'Lanes have portals', body: 'Each lane has a Wiki portal that changes the rules there, for example “Science cards here get +2 power.” Read the portal under each lane name.',
|
||||
show: 'portal' },
|
||||
{ title: 'Win two of three Topics', show: 'lanes',
|
||||
body: 'The board has three Topics (lanes). After turn 6, whoever has more power in a Topic leads it. Lead two Topics to win. If that’s tied, total power decides.' },
|
||||
{ title: 'Every card shows a few things', show: 'card',
|
||||
body: 'Top left is cost: the energy it takes to play. Top right is power. The small icon is the card’s home stat, and the word at the bottom is its keyword. Tap any card on the board to read what it does.' },
|
||||
{ title: 'Play on-topic for a bonus', show: 'stats',
|
||||
body: 'Each Topic is judged on one Wikipedia stat: Attention (readers), Depth (article length) or Reach (languages). A card whose home stat matches gets extra power there. The lane says “On-topic +N” when you pick a matching card.' },
|
||||
{ title: 'Energy grows each turn', show: 'energy',
|
||||
body: 'You get 1 energy on turn 1, 2 on turn 2, up to 6. You can carry 1 unspent energy to the next turn. Famous articles cost more, but they aren’t more efficient: it’s a trade-off.' },
|
||||
{ title: 'Tap a card, then tap a Topic', show: 'play',
|
||||
body: 'Tap a card in your hand to pick it up, then tap a Topic to queue it there. Tap a queued card to take it back. Each Topic holds 3 of your cards. Press End turn when you’re done.' },
|
||||
{ title: 'Reveals take turns', show: 'reveal',
|
||||
body: 'Both players plan in secret. Then the cards reveal one at a time, alternating, starting with whoever has initiative (it swaps every turn). Some keywords care about what’s already there, so order matters.' },
|
||||
{ title: 'Portals change the rules', show: 'portal',
|
||||
body: 'Each Topic hides a Portal that reveals on turn 2, 3 or 4. Portals bend that Topic’s rules, for example “Only 2 cards per player fit here.” Tap a Topic to read its Portal.' },
|
||||
];
|
||||
|
||||
export function Tutorial({ onDone }: { onDone: () => void }) {
|
||||
@@ -26,12 +31,13 @@ export function Tutorial({ onDone }: { onDone: () => void }) {
|
||||
<div className="section-eyebrow">HOW TO PLAY · {i + 1} / {STEPS.length}</div>
|
||||
<h2 id="tutorial-title">{step.title}</h2>
|
||||
<div className="tutorial-visual" aria-hidden="true">
|
||||
{step.show === 'lanes' && <div className="tut-lanes">{['Left', 'Middle', 'Right'].map((n, k) => <div key={n} className={k === 1 ? 'lost' : 'won'}><span>{n}</span><b>{k === 1 ? '4 – 7' : k === 0 ? '9 – 5' : '6 – 3'}</b></div>)}</div>}
|
||||
{step.show === 'card' && <div className="tut-card"><GameCard card={demo[3]} /><ul><li><b>2</b> cost</li><li><b>3</b> power</li><li><b>Rally</b> keyword</li></ul></div>}
|
||||
{step.show === 'lanes' && <div className="tut-lanes">{TOPICS.map(([n, stat, score], k) => <div key={n} className={k === 1 ? 'lost' : 'won'}><StatIcon stat={stat} size={14} /><span>{n}</span><b>{score}</b></div>)}</div>}
|
||||
{step.show === 'card' && <div className="tut-card"><GameCard card={pick(3)} /><ul><li><b>{pick(3).cost}</b> cost</li><li><b>{pick(3).power}</b> power</li><li><StatIcon stat={pick(3).home} /> home stat</li><li><b>{pick(3).keyword?.name}</b> keyword</li></ul></div>}
|
||||
{step.show === 'stats' && <div className="tut-lanes">{TOPICS.map(([, stat]) => <div key={stat} className={stat === 'depth' ? 'won' : ''}><StatIcon stat={stat} size={18} /><span>{stat[0].toUpperCase() + stat.slice(1)}</span>{stat === 'depth' && <b>+1</b>}</div>)}</div>}
|
||||
{step.show === 'energy' && <div className="tut-energy">{[1, 2, 3, 4, 5, 6].map(n => <span key={n} style={{ height: `${n * 10 + 10}px` }}>{n}</span>)}</div>}
|
||||
{step.show === 'play' && <div className="tut-card"><GameCard card={demo[0]} selected /><ArrowRight size={22} /><div className="tut-lane-target">Middle</div></div>}
|
||||
{step.show === 'reveal' && <div className="tut-card"><div className="tut-facedown">?</div><div className="tut-facedown">?</div><ArrowRight size={22} /><GameCard card={demo[6]} size="deck" /></div>}
|
||||
{step.show === 'portal' && <div className="tut-lane-target portal">Portal: Science<small>Science cards here get +2 power.</small></div>}
|
||||
{step.show === 'play' && <div className="tut-card"><GameCard card={pick(1)} selected /><ArrowRight size={22} /><div className="tut-lane-target">Archive<small>On-topic +1</small></div></div>}
|
||||
{step.show === 'reveal' && <div className="tut-card"><div className="tut-facedown">1</div><div className="tut-facedown">2</div><div className="tut-facedown">3</div><ArrowRight size={22} /><GameCard card={pick(4)} size="deck" /></div>}
|
||||
{step.show === 'portal' && <div className="tut-lane-target portal">Stub<small>Only 2 cards per player fit here.</small></div>}
|
||||
</div>
|
||||
<p>{step.body}</p>
|
||||
<div className="play-actions">
|
||||
|
||||
+110
-10
@@ -1,13 +1,113 @@
|
||||
// The single place the Play UI touches an engine. Swap mockEngine for the shared/game adapter here.
|
||||
import { mockEngine } from './mock/engine.ts';
|
||||
import type { EngineAdapter, GameMode, Ruleset } from './types.ts';
|
||||
// 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,
|
||||
} from '../../shared/game/index.ts';
|
||||
import { toUICard } from './cards.ts';
|
||||
import { portalInfo, STAT_LABEL } from './rulesText.ts';
|
||||
import type { GameMode, LaneView, MatchView, ResultView, UIAction, UICard } from './types.ts';
|
||||
|
||||
export const engine: EngineAdapter<any> = mockEngine;
|
||||
export const STANDARD_RULESET: Ruleset = DEFAULT_RULESET;
|
||||
export const LOCAL_MODES: GameMode[] = [{
|
||||
id: 'standard', name: 'Standard', host: { kind: 'local' }, ruleset: DEFAULT_RULESET,
|
||||
description: 'Three Topics, six turns. Win two Topics.',
|
||||
}];
|
||||
|
||||
export const STANDARD_RULESET: Ruleset = {
|
||||
id: 'standard', name: 'Standard', description: 'Three lanes, six turns. Win two lanes.',
|
||||
maxTurns: 6, deckSize: 12, handSize: 3, laneCount: 3, laneCapacity: 4, maxCopies: 2,
|
||||
function toUI(a: Action): UIAction {
|
||||
switch (a.type) {
|
||||
case 'play': return { type: 'play', cardId: a.cardId, lane: a.lane, engine: a };
|
||||
case 'undo': return { type: 'unstage', cardId: a.cardId, engine: a };
|
||||
case 'concede': return { type: 'concede', engine: a };
|
||||
default: return { type: 'endTurn', engine: a };
|
||||
}
|
||||
}
|
||||
function toEngine(a: UIAction, player: PlayerId): Action {
|
||||
if (a.engine) return { ...a.engine, player } as Action;
|
||||
switch (a.type) {
|
||||
case 'play': return { type: 'play', player, cardId: a.cardId, lane: a.lane };
|
||||
case 'unstage': return { type: 'undo', player, cardId: a.cardId };
|
||||
case 'concede': return { type: 'concede', player };
|
||||
default: return { type: 'commit', player };
|
||||
}
|
||||
}
|
||||
|
||||
function logLine(e: LogEvent, me: PlayerId, title: (id: string) => string): string | null {
|
||||
const who = (p: PlayerId) => (p === me ? 'You' : 'Opponent');
|
||||
switch (e.t) {
|
||||
case 'turnStart': return `Turn ${e.turn}. ${e.initiative === me ? 'You reveal first.' : 'Opponent reveals first.'}`;
|
||||
case 'portalRevealed': return `Portal revealed: ${e.topic.name}.`;
|
||||
case 'underdog': return `${who(e.player)} got the underdog bonus.`;
|
||||
case 'reveal': return `${who(e.player)} played ${title(e.cardId)}.`;
|
||||
case 'fizzle': return `${who(e.player)}: ${title(e.cardId)} fizzled (no room) and went back to hand.`;
|
||||
case 'effect': return `${e.source}: ${e.text}`;
|
||||
case 'concede': return `${who(e.player)} ${e.afk ? 'timed out' : 'conceded'}.`;
|
||||
case 'matchOver': return 'Match over.';
|
||||
default: return null; // draws are private
|
||||
}
|
||||
}
|
||||
|
||||
export const engine = {
|
||||
name: 'shared/game v1', mock: false,
|
||||
createMatch(ruleset: Ruleset, decks: [UICard[], UICard[]], seed: string): MatchState {
|
||||
return createMatch(ruleset, [decks[0].map(c => c.game), decks[1].map(c => c.game)], seed);
|
||||
},
|
||||
legal(state: MatchState, player: PlayerId): UIAction[] {
|
||||
if (isOver(state)) return [];
|
||||
const acts = legalActions(state, player).map(toUI);
|
||||
return acts.length ? [...acts, { type: 'concede', engine: { type: 'concede', player } }] : acts;
|
||||
},
|
||||
apply(state: MatchState, player: PlayerId, action: UIAction): MatchState {
|
||||
return applyAction(state, toEngine(action, player));
|
||||
},
|
||||
problem(state: MatchState, player: PlayerId, action: UIAction): string | null {
|
||||
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, { power, onTopic: allOnTopic || c.card.home === stat });
|
||||
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 },
|
||||
};
|
||||
},
|
||||
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 };
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
export const LOCAL_MODES: GameMode[] = [
|
||||
{ id: 'standard', name: 'Standard', description: STANDARD_RULESET.description, host: { kind: 'local' }, ruleset: STANDARD_RULESET },
|
||||
];
|
||||
|
||||
+3
-3
@@ -1,15 +1,15 @@
|
||||
// AI opponents. ui-b owns the real easy/normal bots; this file is the plug-in point.
|
||||
// AI opponents. ui-b owns the real easy/normal bots in src/game/ai/; this file is the plug-in point.
|
||||
import type { MatchView, UIAction } from './types.ts';
|
||||
|
||||
export type Bot = { id: string; name: string; choose(view: MatchView, legal: UIAction[], rand: () => number): UIAction };
|
||||
|
||||
/** Placeholder: plays random affordable cards into random open lanes, then ends the turn. */
|
||||
/** Fallback: queues random affordable plays, then commits. */
|
||||
export const randomBot: Bot = {
|
||||
id: 'random', name: 'Random',
|
||||
choose(_view, legal, rand) {
|
||||
const plays = legal.filter(a => a.type === 'play');
|
||||
if (plays.length && rand() < 0.85) return plays[Math.floor(rand() * plays.length)];
|
||||
return { type: 'endTurn' };
|
||||
return legal.find(a => a.type === 'endTurn') ?? { type: 'endTurn' };
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
+31
-42
@@ -1,54 +1,43 @@
|
||||
import { rarity } from '../../shared/protocol.ts';
|
||||
import type { TestnetBlock } from '../../shared/testnet.ts';
|
||||
import { DEFAULT_RULESET, previewPool, starterDeck as engineStarterDeck, type Faction, type GameCard, type Ruleset, type Stat } from '../../shared/game/index.ts';
|
||||
import { keywordInfo } from './rulesText.ts';
|
||||
import type { UICard } from './types.ts';
|
||||
|
||||
export const CATEGORIES = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const;
|
||||
|
||||
/** Mock keywords, one per category. The real list comes from shared/game (DESIGN.md). */
|
||||
export const MOCK_KEYWORDS: Record<string, { id: string; name: string; text: string }> = {
|
||||
Space: { id: 'orbit', name: 'Orbit', text: 'On reveal: +1 power to your other cards in this lane.' },
|
||||
Nature: { id: 'grow', name: 'Grow', text: 'At the end of each turn: +1 power.' },
|
||||
People: { id: 'rally', name: 'Rally', text: 'On reveal: +2 power if you already have a card here.' },
|
||||
Science: { id: 'cite', name: 'Cite', text: 'On reveal: draw a card.' },
|
||||
History: { id: 'legacy', name: 'Legacy', text: 'On reveal: +2 power if played on turn 1–3.' },
|
||||
Culture: { id: 'viral', name: 'Viral', text: 'On reveal: +3 power if you are behind in this lane.' },
|
||||
export const CATEGORIES: Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'];
|
||||
const FACTION_KEYWORD: Record<Faction, string> = {
|
||||
Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
|
||||
};
|
||||
|
||||
// Curated loaner cards: offline previews, not NFTs. Same power budget as an average owned deck.
|
||||
const LOANERS: [number, string, string, number, number][] = [
|
||||
[19331, 'Moon', 'Space', 1, 2], [22780, 'Octopus', 'Nature', 1, 2], [23053, 'Periodic table', 'Science', 1, 1],
|
||||
[736, 'Albert Einstein', 'People', 2, 3], [13692, 'History of writing', 'History', 2, 2], [18978754, 'Jazz', 'Culture', 2, 3],
|
||||
[26751, 'Saturn', 'Space', 3, 4], [9228, 'Earth', 'Nature', 3, 4], [5180, 'Chemistry', 'Science', 3, 3],
|
||||
[14532, 'Isaac Newton', 'People', 4, 6], [13275, 'Roman Empire', 'History', 4, 5], [20484, 'Music', 'Culture', 5, 8],
|
||||
[1966, 'Ancient Egypt', 'History', 5, 7], [33083, 'Volcano', 'Nature', 6, 10],
|
||||
];
|
||||
|
||||
|
||||
export function starterDeck(): UICard[] {
|
||||
return LOANERS.slice(0, 12).map(([pageId, title, category, cost, power], i) => ({
|
||||
id: `starter-${i}`, pageId, title, category, cost, power, basePower: power,
|
||||
keyword: MOCK_KEYWORDS[category], source: 'starter',
|
||||
}));
|
||||
}
|
||||
export function loanerPool(): UICard[] {
|
||||
return LOANERS.map(([pageId, title, category, cost, power], i) => ({
|
||||
id: `starter-${i}`, pageId, title, category, cost, power, basePower: power,
|
||||
keyword: MOCK_KEYWORDS[category], source: 'starter',
|
||||
}));
|
||||
export function toUICard(card: GameCard, rules: Ruleset = DEFAULT_RULESET, extra: Partial<UICard> = {}): UICard {
|
||||
return { id: card.cardId, pageId: card.pageId, title: card.title, category: card.faction, cost: card.cost,
|
||||
power: card.power, basePower: card.power, home: card.home, trend: card.trend, keyword: keywordInfo(card.keyword, rules),
|
||||
source: card.source === 'owned' ? 'nft' : 'starter', rarity: card.rarity, game: card, ...extra };
|
||||
}
|
||||
|
||||
/** The default loaner deck for new players (engine starterDeck; DESIGN §2). */
|
||||
export const starterDeck = (rules: Ruleset = DEFAULT_RULESET) => engineStarterDeck(1).map(c => toUICard(c, rules));
|
||||
/** The bot's deck: a different loaner deck per match seed. */
|
||||
export const opponentDeck = (seed: string, rules: Ruleset = DEFAULT_RULESET) => engineStarterDeck(`bot:${seed}`).map(c => toUICard(c, rules));
|
||||
export const loanerPool = (rules: Ruleset = DEFAULT_RULESET) => previewPool().map(c => toUICard(c, rules));
|
||||
|
||||
/**
|
||||
* Mock NFT → card mapping (cost from overall stat level, power scales with cost: a sidegrade).
|
||||
* Replaced by the engine's cardFromNft() once it lands; never trust raw snapshot stats for power.
|
||||
* Owned NFT → GameCard for local practice matches. INTERIM: a simplified DESIGN §1 derivation (absolute
|
||||
* thresholds instead of percentiles) until engine-b's derive.ts lands; hosted matches derive on the host.
|
||||
* Cost only moves a card along the curve; power comes from powerByCost, so forged stats never buy efficiency.
|
||||
*/
|
||||
export function cardFromBlock(block: TestnetBlock): UICard {
|
||||
export function cardFromBlock(block: TestnetBlock, rules: Ruleset = DEFAULT_RULESET): UICard {
|
||||
const s = block.statsSnapshot?.stats;
|
||||
const avg = s ? ((s.attention ?? 30) + s.depth + s.reach) / 3 : 50;
|
||||
const cost = Math.max(1, Math.min(6, Math.round((avg - 20) / 12)));
|
||||
const tier = rarity(block.powHash);
|
||||
const power = cost * 2 - (cost > 3 ? 1 : 0) + (tier === 'Legendary' ? 1 : 0);
|
||||
const category = CATEGORIES.includes(block.article.category as never) ? block.article.category : 'Culture';
|
||||
return { id: `nft-${block.tokenId}`, pageId: block.article.pageId, title: block.article.title, category,
|
||||
image: block.article.image, cost, power, basePower: power, keyword: MOCK_KEYWORDS[category],
|
||||
source: 'nft', tokenId: block.tokenId, rarity: tier };
|
||||
const scores: [Stat, number | null][] = [['depth', s?.depth ?? null], ['reach', s?.reach ?? null], ['attention', s?.attention ?? null]];
|
||||
const known = scores.filter((x): x is [Stat, number] => x[1] !== null);
|
||||
const fame = known.length ? known.reduce((a, [, v]) => a + v, 0) / known.length : 50;
|
||||
const cost = Math.min(Math.min(6, 1 + [35, 45, 55, 65, 75].filter(t => fame >= t).length), rules.uncheckedCostCap);
|
||||
const home = known.reduce((best, cur) => (cur[1] > best[1] ? cur : best), known[0] ?? ['depth', 0])[0];
|
||||
const faction = (CATEGORIES.includes(block.article.category as Faction) ? block.article.category : 'Culture') as Faction;
|
||||
const kw = FACTION_KEYWORD[faction];
|
||||
const keyword = cost === 1 || !rules.keywordsEnabled.includes(kw) ? null : kw;
|
||||
const power = rules.powerByCost[cost] + (cost === 1 ? rules.vanillaBonus : 0);
|
||||
const card: GameCard = { cardId: block.tokenId, pageId: block.article.pageId, title: block.article.title, faction,
|
||||
rarity: rarity(block.powHash), cost, power, home, trend: 0, keyword, source: 'owned', check: 'unchecked' };
|
||||
return toUICard(card, rules, { image: block.article.image, tokenId: block.tokenId });
|
||||
}
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
// Stand-in 3-lane engine so the UI can be built before shared/game lands. Deterministic from a seed.
|
||||
// Not the real rules: DESIGN.md / shared/game are authoritative.
|
||||
import type { EngineAdapter, LaneView, MatchView, PlayerIndex, ResultView, Ruleset, UIAction, UICard } from '../types.ts';
|
||||
|
||||
type Player = { deck: UICard[]; hand: UICard[]; energy: number; staged: { card: UICard; lane: number }[]; ended: boolean };
|
||||
type Modifier = { name: string; text: string; category?: string; bonus: number };
|
||||
type Lane = { name: string; modifier: Modifier; cards: [UICard[], UICard[]]; playedTurn: Record<string, number> };
|
||||
export type MockState = {
|
||||
ruleset: Ruleset; rng: number; turn: number; first: PlayerIndex;
|
||||
players: [Player, Player]; lanes: Lane[]; log: string[]; over: boolean; conceded?: PlayerIndex;
|
||||
};
|
||||
|
||||
const LANE_POOL: Modifier[] = [
|
||||
{ name: 'Portal: Science', text: 'Science cards here get +2 power.', category: 'Science', bonus: 2 },
|
||||
{ name: 'Portal: Space', text: 'Space cards here get +2 power.', category: 'Space', bonus: 2 },
|
||||
{ name: 'Portal: Nature', text: 'Nature cards here get +2 power.', category: 'Nature', bonus: 2 },
|
||||
{ name: 'Portal: People', text: 'People cards here get +2 power.', category: 'People', bonus: 2 },
|
||||
{ name: 'Portal: History', text: 'History cards here get +2 power.', category: 'History', bonus: 2 },
|
||||
{ name: 'Featured article', text: 'Every card here gets +1 power.', bonus: 1 },
|
||||
{ name: 'Stub', text: 'No effect. A blank page.', bonus: 0 },
|
||||
];
|
||||
const LANE_NAMES = ['Left', 'Middle', 'Right'];
|
||||
|
||||
function hashSeed(seed: string): number {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
|
||||
return h >>> 0;
|
||||
}
|
||||
function next(state: { rng: number }): number { // mulberry32
|
||||
let t = (state.rng = (state.rng + 0x6d2b79f5) >>> 0);
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
}
|
||||
function shuffle<T>(state: { rng: number }, items: T[]): T[] {
|
||||
const a = [...items];
|
||||
for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(next(state) * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
|
||||
return a;
|
||||
}
|
||||
const bonusFor = (lane: Lane, card: UICard) => !lane.modifier.category || lane.modifier.category === card.category ? lane.modifier.bonus : 0;
|
||||
const lanePower = (lane: Lane, p: PlayerIndex) => lane.cards[p].reduce((sum, c) => sum + c.power + bonusFor(lane, c), 0);
|
||||
const other = (p: PlayerIndex): PlayerIndex => (p === 0 ? 1 : 0);
|
||||
|
||||
function draw(player: Player) { const card = player.deck.shift(); if (card) player.hand.push(card); }
|
||||
|
||||
function reveal(s: MockState) {
|
||||
const order: PlayerIndex[] = [s.first, other(s.first)];
|
||||
for (const p of order) {
|
||||
for (const { card, lane: li } of s.players[p].staged) {
|
||||
const lane = s.lanes[li];
|
||||
const hadCard = lane.cards[p].length > 0;
|
||||
lane.cards[p].push(card);
|
||||
lane.playedTurn[card.id] = s.turn;
|
||||
const k = card.keyword?.id;
|
||||
if (k === 'orbit') lane.cards[p].forEach(c => { if (c !== card) c.power += 1; });
|
||||
if (k === 'rally' && hadCard) card.power += 2;
|
||||
if (k === 'cite') draw(s.players[p]);
|
||||
if (k === 'legacy' && s.turn <= 3) card.power += 2;
|
||||
if (k === 'viral' && lanePower(lane, p) < lanePower(lane, other(p))) card.power += 3;
|
||||
s.log.push(`${p === 0 ? 'P1' : 'P2'} played ${card.title} → ${lane.name}${card.power !== card.basePower ? ` (${card.keyword?.name} ${card.power - card.basePower >= 0 ? '+' : ''}${card.power - card.basePower})` : ''}`);
|
||||
}
|
||||
s.players[p].staged = [];
|
||||
}
|
||||
for (const lane of s.lanes) for (const p of [0, 1] as PlayerIndex[])
|
||||
for (const c of lane.cards[p]) if (c.keyword?.id === 'grow') c.power += 1;
|
||||
}
|
||||
|
||||
function endRound(s: MockState) {
|
||||
reveal(s);
|
||||
if (s.turn >= s.ruleset.maxTurns) { s.over = true; s.log.push('Final turn complete.'); return; }
|
||||
s.turn += 1;
|
||||
s.first = other(s.first);
|
||||
for (const p of s.players) { draw(p); p.energy = Math.min(s.turn, 6); p.ended = false; }
|
||||
s.log.push(`Turn ${s.turn}.`);
|
||||
}
|
||||
|
||||
export const mockEngine: EngineAdapter<MockState> = {
|
||||
name: 'mock lanes v0', mock: true,
|
||||
createMatch(ruleset, decks, seed) {
|
||||
const rng = { rng: hashSeed(seed) };
|
||||
const tag = (deck: UICard[], p: number) => deck.map((c, i) => ({ ...c, id: `p${p}-${i}-${c.id}`, power: c.basePower }));
|
||||
const players = decks.map((d, p) => {
|
||||
const deck = shuffle(rng, tag(d, p));
|
||||
return { deck: deck.slice(ruleset.handSize), hand: deck.slice(0, ruleset.handSize), energy: 1, staged: [], ended: false };
|
||||
}) as unknown as [Player, Player];
|
||||
const mods = shuffle(rng, LANE_POOL).slice(0, ruleset.laneCount);
|
||||
const lanes = mods.map((modifier, i) => ({ name: LANE_NAMES[i] ?? `Lane ${i + 1}`, modifier, cards: [[], []] as [UICard[], UICard[]], playedTurn: {} }));
|
||||
const first = (next(rng) < 0.5 ? 0 : 1) as PlayerIndex;
|
||||
return { ruleset, rng: rng.rng, turn: 1, first, players, lanes, log: ['Turn 1.'], over: false };
|
||||
},
|
||||
legal(s, p) {
|
||||
if (s.over) return [];
|
||||
const me = s.players[p];
|
||||
if (me.ended) return [];
|
||||
const acts: UIAction[] = [{ type: 'endTurn' }, { type: 'concede' }];
|
||||
for (const { card } of me.staged) acts.push({ type: 'unstage', cardId: card.id });
|
||||
for (const card of me.hand) if (card.cost <= me.energy)
|
||||
s.lanes.forEach((lane, li) => {
|
||||
const used = lane.cards[p].length + me.staged.filter(x => x.lane === li).length;
|
||||
if (used < s.ruleset.laneCapacity) acts.push({ type: 'play', cardId: card.id, lane: li });
|
||||
});
|
||||
return acts;
|
||||
},
|
||||
apply(prev, p, action) {
|
||||
const s: MockState = structuredClone(prev);
|
||||
const me = s.players[p];
|
||||
if (s.over || me.ended) throw new Error('Not your turn');
|
||||
if (action.type === 'concede') { s.over = true; s.conceded = p; s.log.push(`${p === 0 ? 'P1' : 'P2'} conceded.`); return s; }
|
||||
if (action.type === 'play') {
|
||||
const ok = mockEngine.legal(prev, p).some(a => a.type === 'play' && a.cardId === action.cardId && a.lane === action.lane);
|
||||
if (!ok) throw new Error('Illegal play');
|
||||
const i = me.hand.findIndex(c => c.id === action.cardId);
|
||||
const [card] = me.hand.splice(i, 1);
|
||||
me.energy -= card.cost;
|
||||
me.staged.push({ card, lane: action.lane });
|
||||
} else if (action.type === 'unstage') {
|
||||
const i = me.staged.findIndex(x => x.card.id === action.cardId);
|
||||
if (i < 0) throw new Error('Not staged');
|
||||
const [{ card }] = me.staged.splice(i, 1);
|
||||
me.energy += card.cost;
|
||||
me.hand.push(card);
|
||||
} else if (action.type === 'endTurn') {
|
||||
me.ended = true;
|
||||
if (s.players.every(x => x.ended)) endRound(s);
|
||||
}
|
||||
return s;
|
||||
},
|
||||
view(s, p): MatchView {
|
||||
const me = s.players[p], them = s.players[other(p)];
|
||||
const lanes: LaneView[] = s.lanes.map((lane, i) => {
|
||||
const withBonus = (c: UICard) => ({ ...c, power: c.power + bonusFor(lane, c) });
|
||||
return { index: i, name: lane.name, modifier: { name: lane.modifier.name, text: lane.modifier.text }, revealed: true,
|
||||
mine: lane.cards[p].map(withBonus), theirs: lane.cards[other(p)].map(withBonus),
|
||||
staged: me.staged.filter(x => x.lane === i).map(x => withBonus(x.card)),
|
||||
myPower: lanePower(lane, p), theirPower: lanePower(lane, other(p)), capacity: s.ruleset.laneCapacity };
|
||||
});
|
||||
return { me: p, turn: s.turn, maxTurns: s.ruleset.maxTurns, energy: me.energy, maxEnergy: Math.min(s.turn, 6),
|
||||
hand: me.hand, deckCount: me.deck.length, oppHandCount: them.hand.length, oppDeckCount: them.deck.length,
|
||||
lanes, log: s.log.slice(-30), waitingForOpponent: me.ended && !s.over, over: s.over };
|
||||
},
|
||||
isOver: s => s.over,
|
||||
result(s, p): ResultView {
|
||||
const lanes = s.lanes.map(l => {
|
||||
const a = lanePower(l, p), b = lanePower(l, other(p));
|
||||
return { name: l.name, myPower: a, theirPower: b, winner: a === b ? null : a > b ? p : other(p) };
|
||||
});
|
||||
if (s.conceded !== undefined) return { winner: other(s.conceded), lanes, turns: s.turn, reason: 'concede' };
|
||||
const mine = lanes.filter(l => l.winner === p).length, theirs = lanes.filter(l => l.winner === other(p)).length;
|
||||
let winner: PlayerIndex | null = mine > theirs ? p : theirs > mine ? other(p) : null;
|
||||
if (winner === null) { // tiebreak: total power
|
||||
const ta = lanes.reduce((x, l) => x + l.myPower, 0), tb = lanes.reduce((x, l) => x + l.theirPower, 0);
|
||||
winner = ta === tb ? null : ta > tb ? p : other(p);
|
||||
}
|
||||
return { winner, lanes, turns: s.turn, reason: 'lanes' };
|
||||
},
|
||||
};
|
||||
@@ -171,3 +171,13 @@
|
||||
.lane-side{min-height:84px}
|
||||
}
|
||||
.deck-warning{color:var(--ctp-yellow)}
|
||||
html.wd-in-match .auth-wrap{display:none}
|
||||
.gcard-home{position:absolute;top:30px;left:5px;z-index:2;display:flex;align-items:center;gap:1px;padding:2px 4px;border-radius:999px;background:var(--ctp-crust);color:var(--ctp-subtext1);font-size:10px}
|
||||
.gcard-home .trend.up{color:var(--ctp-green)}.gcard-home .trend.down{color:var(--ctp-red)}
|
||||
.gcard.is-on-topic .gcard-home{background:var(--ctp-green);color:var(--ctp-crust)}
|
||||
.gcard-board .gcard-home{position:static;order:2;margin-left:2px;padding:2px 3px;flex:0 0 auto}
|
||||
.lane-name{display:flex;flex-direction:column;align-items:center;gap:2px}
|
||||
.lane-name small{font-size:9px;color:var(--ctp-overlay1)}
|
||||
.lane-drop.on-topic{border-color:var(--ctp-green);color:var(--ctp-green);background:color-mix(in srgb,var(--ctp-green) 10%,transparent)}
|
||||
.sheet h3{display:flex;align-items:center;gap:8px}
|
||||
@media(max-width:400px){.gcard-board .gcard-home{display:none}.gcard-board.is-on-topic{box-shadow:inset 3px 0 0 var(--ctp-green)}}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// Display names and one-line reminder text (DESIGN §10.2, §10.3). The engine registry wins when it
|
||||
// has an entry; this table covers keywords and Portals whose registry entry hasn't landed yet.
|
||||
import { KEYWORDS, PORTALS, type Ruleset, type Stat } from '../../shared/game/index.ts';
|
||||
|
||||
const KW: Record<string, [string, string]> = {
|
||||
viral: ['Viral', 'On reveal: +{amount} power for each other card you revealed earlier this turn (max +{cap}).'],
|
||||
rising: ['Rising', 'End of turn: +{amount} power (max +{cap} total).'],
|
||||
local: ['Local', 'Ongoing: +{amount} power while on-topic.'],
|
||||
encyclopedic: ['Encyclopedic', 'On reveal: +{amount} power if there are no other cards here.'],
|
||||
nostalgic: ['Nostalgic', 'On reveal: +{amount} power if you are losing here.'],
|
||||
translated: ['Translated', 'On reveal: +{amount} power to your most recent card in each other Topic.'],
|
||||
edition: ['Edition', '+{amount} power for each other copy of this article on your side.'],
|
||||
obscure: ['Obscure', 'Your opponent sees this face down until the match ends.'],
|
||||
wildcard: ['Wildcard', 'On reveal: its home stat becomes this Topic’s stat.'],
|
||||
};
|
||||
const PORTAL: Record<string, [string, string]> = {
|
||||
'main-page': ['Main Page', 'At scoring, each card here gets +1 power.'],
|
||||
trending: ['Trending', 'Trend arrows count double here.'],
|
||||
'featured-article': ['Featured Article', 'At scoring, whoever has the single strongest card here gets +2.'],
|
||||
stub: ['Stub', 'Only 2 cards per player fit here.'],
|
||||
interwiki: ['Interwiki', '+1 here if you have a card in all 3 Topics.'],
|
||||
disambiguation: ['Disambiguation', 'Every card here counts as on-topic.'],
|
||||
};
|
||||
const fill = (text: string, params: Record<string, number> = {}) => text.replace(/\{(\w+)\}/g, (_, k) => String(params[k] ?? k));
|
||||
|
||||
export const STAT_LABEL: Record<Stat, string> = { attention: 'Attention', depth: 'Depth', reach: 'Reach' };
|
||||
export const STAT_HINT: Record<Stat, string> = {
|
||||
attention: 'how many people read it', depth: 'how long the article is', reach: 'how many languages it’s in',
|
||||
};
|
||||
|
||||
export function keywordInfo(id: string | null, rules?: Ruleset) {
|
||||
if (!id) return undefined;
|
||||
const reg = KEYWORDS[id], fb = KW[id];
|
||||
return { id, name: reg?.name ?? fb?.[0] ?? id, text: fill(reg?.text ?? fb?.[1] ?? '', rules?.keywordParams[id]) };
|
||||
}
|
||||
export function portalInfo(portalId: string | null, topicId: string, rules?: Ruleset) {
|
||||
if (!portalId) return undefined;
|
||||
const reg = PORTALS[portalId], fb = PORTAL[portalId];
|
||||
return { name: reg?.name ?? fb?.[0] ?? portalId, text: fill(reg?.text ?? fb?.[1] ?? '', rules?.portalParams[topicId] ?? rules?.portalParams[portalId]) };
|
||||
}
|
||||
+32
-40
@@ -1,34 +1,43 @@
|
||||
// UI-side contract for the Play section. Screens consume only these view models, so swapping the
|
||||
// mock engine for shared/game touches adapter.ts alone.
|
||||
// UI-side view models for the Play section. Screens consume only these; adapter.ts maps the
|
||||
// shared/game engine (docs/game/ENGINE_API.md) onto them.
|
||||
import type { Action, GameCard, MatchResult, MatchState, PlayerId, Ruleset, Stat } from '../../shared/game/index.ts';
|
||||
|
||||
export type PlayerIndex = 0 | 1;
|
||||
export type PlayerIndex = PlayerId;
|
||||
export type { Stat };
|
||||
|
||||
/** A card as the deck builder and match screen display it: at most 3 numbers and 1 keyword. */
|
||||
/** A card as the deck builder and match screen show it (DESIGN §1.9): cost, power, home icon, trend, one keyword. */
|
||||
export type UICard = {
|
||||
id: string; // unique within a match/deck (instance id)
|
||||
pageId: number;
|
||||
id: string; // engine cardId
|
||||
pageId: number | null;
|
||||
title: string;
|
||||
category: string;
|
||||
category: string; // faction
|
||||
image?: string;
|
||||
cost: number;
|
||||
power: number; // current power (including modifiers on board)
|
||||
power: number; // current lane power on the board, base power elsewhere
|
||||
basePower: number;
|
||||
home: Stat;
|
||||
trend: -1 | 0 | 1;
|
||||
onTopic?: boolean; // on the board: the Topic's stat matches home (or Disambiguation)
|
||||
keyword?: { id: string; name: string; text: string };
|
||||
source: 'starter' | 'nft';
|
||||
tokenId?: string;
|
||||
rarity?: string;
|
||||
game: GameCard;
|
||||
};
|
||||
|
||||
export type LaneView = {
|
||||
index: number;
|
||||
name: string;
|
||||
modifier?: { name: string; text: string };
|
||||
name: string; // Topic name
|
||||
stat: Stat;
|
||||
modifier?: { name: string; text: string }; // revealed Portal
|
||||
portalNote?: string; // e.g. "Portal reveals on turn 3"
|
||||
revealed: boolean;
|
||||
mine: UICard[];
|
||||
theirs: UICard[];
|
||||
staged: UICard[]; // my plays this turn, not yet revealed
|
||||
staged: UICard[]; // my queued plays this turn, not yet revealed
|
||||
myPower: number;
|
||||
theirPower: number;
|
||||
leader: 'you' | 'opponent' | null;
|
||||
capacity: number;
|
||||
};
|
||||
|
||||
@@ -36,59 +45,42 @@ export type MatchView = {
|
||||
me: PlayerIndex;
|
||||
turn: number;
|
||||
maxTurns: number;
|
||||
energy: number; // remaining this turn
|
||||
energy: number; // left this turn
|
||||
maxEnergy: number;
|
||||
hand: UICard[];
|
||||
deckCount: number;
|
||||
oppHandCount: number;
|
||||
oppDeckCount: number;
|
||||
oppQueued: number;
|
||||
lanes: LaneView[];
|
||||
log: string[]; // newest last
|
||||
log: string[]; // newest last, this seat's events only
|
||||
waitingForOpponent: boolean;
|
||||
over: boolean;
|
||||
/** For bots that reuse shared/bots (ui-b): the full state and this seat. Never render it. */
|
||||
engine?: { state: MatchState; seat: PlayerId };
|
||||
};
|
||||
|
||||
export type UIAction =
|
||||
export type UIAction = (
|
||||
| { type: 'play'; cardId: string; lane: number }
|
||||
| { type: 'unstage'; cardId: string }
|
||||
| { type: 'endTurn' }
|
||||
| { type: 'concede' };
|
||||
| { type: 'concede' }
|
||||
) & { engine?: Action };
|
||||
|
||||
export type ResultView = {
|
||||
winner: PlayerIndex | null; // null = draw
|
||||
lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
|
||||
turns: number;
|
||||
reason: 'lanes' | 'concede' | 'turnCap';
|
||||
};
|
||||
|
||||
export type Ruleset = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
maxTurns: number;
|
||||
deckSize: number;
|
||||
handSize: number;
|
||||
laneCount: number;
|
||||
laneCapacity: number;
|
||||
maxCopies: number;
|
||||
reason: MatchResult['reason'];
|
||||
totalPower: [number, number];
|
||||
};
|
||||
|
||||
export type GameMode = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
host: { kind: 'local' } | { kind: 'peer'; name: string; url: string };
|
||||
host: { kind: 'local' } | { kind: 'peer'; name: string; url: string; self: boolean };
|
||||
ruleset: Ruleset;
|
||||
players?: number;
|
||||
matchesPlayed?: number;
|
||||
};
|
||||
|
||||
export interface EngineAdapter<S = unknown> {
|
||||
readonly name: string;
|
||||
readonly mock: boolean;
|
||||
createMatch(ruleset: Ruleset, decks: [UICard[], UICard[]], seed: string): S;
|
||||
legal(state: S, player: PlayerIndex): UIAction[];
|
||||
apply(state: S, player: PlayerIndex, action: UIAction): S;
|
||||
view(state: S, player: PlayerIndex): MatchView;
|
||||
isOver(state: S): boolean;
|
||||
result(state: S, player: PlayerIndex): ResultView;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// eom.dev login state. The SSO team (#7) owns the real OIDC client; until it lands this reports
|
||||
// signed-out and the lobby shows a disabled "Sign in" chip. Swap this hook's body for theirs.
|
||||
export type Account = { name: string; avatar?: string } | null;
|
||||
export function useAccount(): { account: Account; available: boolean; login?: () => void; logout?: () => void } {
|
||||
return { account: null, available: false };
|
||||
}
|
||||
// eom.dev login state from the SSO module (src/auth, #7).
|
||||
import { useAccount as useAuthAccount } from '../auth/LoginButton.tsx';
|
||||
export const useAccount = () => useAuthAccount();
|
||||
|
||||
+43
-24
@@ -1,29 +1,35 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { DEFAULT_RULESET, parseRuleset, type Ruleset } from '../../shared/game/index.ts';
|
||||
import { LOCAL_MODES } from './adapter.ts';
|
||||
import type { GameMode } from './types.ts';
|
||||
|
||||
// Peer-hosted modes come from this node's GET /api/game/modes (owned by the modes team, #6).
|
||||
// The shape is read defensively: anything malformed is skipped, and the built-in mode is always present.
|
||||
type Remote = { id?: unknown; name?: unknown; description?: unknown; host?: unknown; hostedBy?: unknown; url?: unknown; players?: unknown; ruleset?: unknown };
|
||||
// Modes API (modes team, #6 / docs/game/HOSTING.md §3): GET /api/game/modes for this node and
|
||||
// GET /api/game/network/modes for configured peers. Everything a peer sends is untrusted: strings are
|
||||
// length-capped and rendered as React text only, and rules go through the engine's strict parseRuleset.
|
||||
const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.slice(0, max) : undefined);
|
||||
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : undefined);
|
||||
const obj = (v: unknown): Record<string, unknown> | undefined => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined);
|
||||
|
||||
export function parseModes(data: unknown): GameMode[] {
|
||||
const list = Array.isArray(data) ? data : Array.isArray((data as { modes?: unknown })?.modes) ? (data as { modes: unknown[] }).modes : [];
|
||||
const base = LOCAL_MODES[0].ruleset;
|
||||
return list.slice(0, 50).flatMap((raw): GameMode[] => {
|
||||
if (!raw || typeof raw !== 'object') return [];
|
||||
const m = raw as Remote;
|
||||
const id = str(m.id, 64), name = str(m.name, 60);
|
||||
if (!id || !name) return [];
|
||||
const host = m.host as { name?: unknown; url?: unknown; kind?: unknown } | string | undefined;
|
||||
const hostName = str(typeof host === 'string' ? host : host?.name) ?? str(m.hostedBy) ?? 'this node';
|
||||
const r = (m.ruleset ?? {}) as Record<string, unknown>;
|
||||
const num = (k: string, lo: number, hi: number) => typeof r[k] === 'number' && r[k] >= lo && r[k] <= hi ? r[k] as number : (base as Record<string, unknown>)[k] as number;
|
||||
return [{ id: `remote:${id}`, name, description: str(m.description, 280) ?? '',
|
||||
host: { kind: 'peer', name: hostName, url: str(typeof host === 'object' ? host?.url : m.url, 200) ?? '' },
|
||||
players: typeof m.players === 'number' ? m.players : undefined,
|
||||
ruleset: { ...base, id, name, maxTurns: num('maxTurns', 3, 12), deckSize: num('deckSize', 6, 30),
|
||||
handSize: num('handSize', 1, 7), laneCount: num('laneCount', 1, 3), laneCapacity: num('laneCapacity', 1, 6), maxCopies: num('maxCopies', 1, 4) } }];
|
||||
function rulesFor(rules: unknown): Ruleset | undefined {
|
||||
const overrides = obj(rules);
|
||||
try { return parseRuleset({ ...DEFAULT_RULESET, ...(overrides ?? {}) }); } catch { return undefined; }
|
||||
}
|
||||
|
||||
/** Parse a ModeList ({ host, modes: [{ mode, stats }] }). Malformed entries are skipped. */
|
||||
export function parseModeList(data: unknown, where: { self: boolean; origin: string }): GameMode[] {
|
||||
const list = obj(data);
|
||||
const host = obj(list?.host);
|
||||
const operator = str(host?.operator, 60) ?? str(host?.origin, 80) ?? (where.self ? 'this node' : where.origin);
|
||||
const origin = str(host?.origin, 200) ?? where.origin;
|
||||
const modes = Array.isArray(list?.modes) ? list!.modes as unknown[] : [];
|
||||
return modes.slice(0, 16).flatMap((entry): GameMode[] => {
|
||||
const e = obj(entry), m = obj(e?.mode), stats = obj(e?.stats);
|
||||
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) ?? '',
|
||||
host: { kind: 'peer', name: operator, url: /^https?:\/\//.test(origin) ? origin : '', self: where.self },
|
||||
ruleset, players: num(stats?.playersOnline), matchesPlayed: num(stats?.matchesPlayed) }];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,10 +38,23 @@ export function useModes() {
|
||||
const [status, setStatus] = useState<'loading' | 'ok' | 'unavailable'>('loading');
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
fetch('/api/game/modes', { cache: 'no-store', signal: AbortSignal.timeout(8000) })
|
||||
.then(r => r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable')))
|
||||
.then(d => { if (active) { setRemote(parseModes(d)); setStatus('ok'); } })
|
||||
.catch(() => { if (active) setStatus('unavailable'); });
|
||||
const get = (path: string) => fetch(path, { cache: 'no-store', signal: AbortSignal.timeout(8000) })
|
||||
.then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable'))));
|
||||
Promise.allSettled([get('/api/game/modes'), get('/api/game/network/modes')]).then(([self, net]) => {
|
||||
if (!active) return;
|
||||
const found: GameMode[] = [];
|
||||
if (self.status === 'fulfilled') found.push(...parseModeList(self.value, { self: true, origin: '' }));
|
||||
if (net.status === 'fulfilled') {
|
||||
const peers = obj(net.value)?.peers;
|
||||
if (Array.isArray(peers)) for (const p of peers.slice(0, 16)) {
|
||||
const peer = obj(p);
|
||||
if (peer?.ok && peer.list) found.push(...parseModeList(peer.list, { self: false, origin: str(peer.origin, 200) ?? '' }));
|
||||
}
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
setRemote(found.filter(m => !seen.has(m.id) && seen.add(m.id)));
|
||||
setStatus(self.status === 'fulfilled' || net.status === 'fulfilled' ? 'ok' : 'unavailable');
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
return { modes: [...LOCAL_MODES, ...remote], status };
|
||||
|
||||
+64
-37
@@ -1,63 +1,77 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { engine, STANDARD_RULESET } from '../src/game/adapter.ts';
|
||||
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
||||
import { engine } from '../src/game/adapter.ts';
|
||||
import { randomBot } from '../src/game/bots.ts';
|
||||
import { loanerPool, starterDeck } from '../src/game/cards.ts';
|
||||
import { deckProblem } from '../src/game/DeckBuilder.tsx';
|
||||
import { parseModes } from '../src/game/useModes.ts';
|
||||
import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
|
||||
import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
|
||||
import { parseModeList } from '../src/game/useModes.ts';
|
||||
import type { PlayerIndex } from '../src/game/types.ts';
|
||||
import type { TestnetBlock } from '../shared/testnet.ts';
|
||||
|
||||
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. */
|
||||
function playOut(seed: string) {
|
||||
let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], seed);
|
||||
const r = rand(seed.length * 7919);
|
||||
for (let steps = 0; steps < 500 && !engine.isOver(s); steps++) {
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
|
||||
const r = rand(seed.length * 7919 + 1);
|
||||
for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
|
||||
for (const p of [0, 1] as PlayerIndex[]) {
|
||||
const legal = engine.legal(s, p);
|
||||
const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
|
||||
if (!legal.length) continue;
|
||||
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal.filter(a => a.type !== 'concede'), r));
|
||||
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
test('starter deck is a legal Standard deck', () => {
|
||||
assert.equal(deckProblem(starterDeck(), STANDARD_RULESET), '');
|
||||
assert.match(deckProblem(starterDeck().slice(1), STANDARD_RULESET), /exactly 12/);
|
||||
const pool = loanerPool();
|
||||
assert.match(deckProblem([...Array(12)].map(() => pool[0]), STANDARD_RULESET), /copies/);
|
||||
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(opponentDeck('x'), DEFAULT_RULESET), '');
|
||||
assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
|
||||
});
|
||||
|
||||
test('random legal play always terminates within the turn cap and is deterministic', () => {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
|
||||
const pool = loanerPool();
|
||||
const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
|
||||
assert.match(deckWarning(heavy), /cost 2 or less/);
|
||||
assert.equal(deckWarning(starterDeck()), '');
|
||||
});
|
||||
|
||||
test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
|
||||
assert.ok(engine.isOver(a), `match ${i} finished`);
|
||||
const ra = engine.result(a, 0);
|
||||
assert.ok(ra.turns <= STANDARD_RULESET.maxTurns);
|
||||
assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
|
||||
assert.deepEqual(ra, engine.result(b, 0));
|
||||
const rb = engine.result(a, 1);
|
||||
if (ra.winner !== null) assert.equal(rb.winner, ra.winner);
|
||||
assert.equal(engine.result(a, 1).winner, ra.winner);
|
||||
}
|
||||
});
|
||||
|
||||
test('opponent staged plays stay hidden until reveal', () => {
|
||||
let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'hidden');
|
||||
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');
|
||||
for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
|
||||
s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
|
||||
const play = engine.legal(s, 1).find(a => a.type === 'play');
|
||||
assert.ok(play);
|
||||
assert.ok(play, 'some seed gives the opponent a turn-1 play');
|
||||
s = engine.apply(s, 1, play!);
|
||||
const mine = engine.view(s, 0);
|
||||
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
|
||||
assert.equal(engine.view(s, 1).lanes.flatMap(l => l.staged).length, 1);
|
||||
assert.equal(mine.oppQueued, 1);
|
||||
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('illegal plays are rejected and unstage refunds energy', () => {
|
||||
let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'energy');
|
||||
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);
|
||||
const expensive = v.hand.find(c => c.cost > v.energy);
|
||||
if (expensive) assert.throws(() => engine.apply(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
|
||||
if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
|
||||
const play = engine.legal(s, 0).find(a => a.type === 'play');
|
||||
if (play && play.type === 'play') {
|
||||
if (play?.type === 'play') {
|
||||
s = engine.apply(s, 0, play);
|
||||
assert.ok(engine.view(s, 0).energy < v.energy);
|
||||
s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
|
||||
@@ -65,15 +79,28 @@ test('illegal plays are rejected and unstage refunds energy', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('peer mode parsing is defensive and clamps rulesets', () => {
|
||||
const modes = parseModes({ modes: [
|
||||
{ id: 'trending', name: 'Trending', description: 'x'.repeat(1000), host: { name: 'node-b', url: 'http://n' }, ruleset: { maxTurns: 99, laneCount: 2 } },
|
||||
{ name: 'no id' }, 'junk', null,
|
||||
] });
|
||||
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;
|
||||
const card = cardFromBlock(block);
|
||||
assert.equal(card.source, 'nft');
|
||||
assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
|
||||
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 } },
|
||||
{ mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
|
||||
{ mode: { name: 'no id' } }, 'junk', null,
|
||||
] }, { self: false, origin: 'http://192.168.1.32:3102' });
|
||||
assert.equal(modes.length, 1);
|
||||
assert.equal(modes[0].host.kind, 'peer');
|
||||
assert.equal(modes[0].ruleset.maxTurns, STANDARD_RULESET.maxTurns);
|
||||
assert.equal(modes[0].ruleset.laneCount, 2);
|
||||
assert.ok(modes[0].description.length <= 280);
|
||||
assert.deepEqual(parseModes('nope'), []);
|
||||
const [m] = modes;
|
||||
assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
|
||||
assert.equal(m.ruleset.turns, 5);
|
||||
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