forked from WikiDeck/wikideck
Play section: lobby, deck builder, match, results, tutorial
Mobile-first game UI in src/game/, built against a UI-side EngineAdapter. A temporary mock 3-lane engine (src/game/mock/) stands in until shared/game lands. Tap a card, then tap a lane; bottom thumb dock; bottom sheets instead of hover; full-screen match on phones. Lobby lists local and peer modes (GET /api/game/modes, parsed defensively) and shows the eom.dev login state through a stub hook for the SSO team. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+6
-5
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { ArrowDownLeft, ArrowLeftRight, ArrowRight, ArrowUpRight, BookOpen, Check, ChevronRight, CircleHelp,
|
||||
Copy, Cpu, Download, ExternalLink, Globe2, Layers3, LayoutDashboard, LoaderCircle,
|
||||
Pickaxe, Search, Shield, Sparkles, Wallet as WalletIcon, X } from 'lucide-react';
|
||||
Pickaxe, Search, Shield, Sparkles, Swords, Wallet as WalletIcon, X } from 'lucide-react';
|
||||
import { rarity } from '../shared/protocol.ts';
|
||||
import { CONSENSUS, NETWORK, isNftTrade, nftTransferMessage, testnetOwnerOf, transactionCardIds,
|
||||
type TestnetBlock, type TestnetSnapshot } from '../shared/testnet.ts';
|
||||
@@ -13,10 +13,11 @@ import { ThemePicker } from './ThemePicker.tsx';
|
||||
import { TradeDesk } from './TradeDesk.tsx';
|
||||
import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts';
|
||||
import { StateClient } from '../shared/rpc-client.ts';
|
||||
import { PlaySection } from './game/PlaySection.tsx';
|
||||
import './App.css';
|
||||
import './testnet.css';
|
||||
|
||||
type View = 'Discover' | 'My collection' | 'Block explorer' | 'Trade cards';
|
||||
type View = 'Discover' | 'Play' | 'My collection' | 'Block explorer' | 'Trade cards';
|
||||
const short = (s: string) => s ? `${s.slice(0, 6)}…${s.slice(-4)}` : '—';
|
||||
const asCard = (block: TestnetBlock): CardData => ({ article: block.article, hash: block.powHash, block });
|
||||
const message = (error: unknown) => error instanceof Error ? error.message : 'Request failed. Please try again.';
|
||||
@@ -161,8 +162,8 @@ export default function App() {
|
||||
<aside className="sidebar">
|
||||
<a href="#" className="brand" onClick={e => { e.preventDefault(); setView('Discover'); }}><span className="brand-mark" aria-hidden="true">W<span>✦</span></span>wikideck<span className="brand-dot">.</span></a>
|
||||
<div className="sidebar-label">YOUR NEXT DISCOVERY</div>
|
||||
<nav aria-label="Main navigation">{(['Discover', 'My collection', 'Block explorer', 'Trade cards'] as View[]).map((item, i) => {
|
||||
const Icon = [LayoutDashboard, Layers3, Globe2, ArrowLeftRight][i];
|
||||
<nav aria-label="Main navigation">{(['Discover', 'Play', 'My collection', 'Block explorer', 'Trade cards'] as View[]).map((item, i) => {
|
||||
const Icon = [LayoutDashboard, Swords, Layers3, Globe2, ArrowLeftRight][i];
|
||||
return <button key={item} aria-label={item} aria-current={view === item ? 'page' : undefined} className={`nav-item ${view === item ? 'active' : ''}`} onClick={() => { setView(item); setQuery(''); setCategory('All cards'); }}><Icon size={18} />{item}{item === 'My collection' && <span className="nav-count">{owned.length}</span>}</button>;
|
||||
})}</nav>
|
||||
<div className="sidebar-note"><span className="tiny-spark">✦</span><h3>Mine together.<br />Trade your way.</h3><p>Discover illustrated Wikipedia cards, build a deck around what you love, and find your collector community.</p><button onClick={() => setDialog('guide')}>How it works <ArrowUpRight size={15} /></button></div>
|
||||
@@ -195,7 +196,7 @@ export default function App() {
|
||||
<article><ArrowLeftRight size={22}/><div className="section-eyebrow">TRADE · PLAYER TO PLAYER</div><h2>Swap cards directly.</h2><p>Prepare a signed offer for another collector and exchange card bundles atomically when the trade is mined. No prices or checkout.</p><button className="text-button" onClick={()=>setView('Trade cards')}>Trade cards <ArrowRight size={14}/></button></article>
|
||||
</section>
|
||||
</>}
|
||||
{view === 'Trade cards' ? <TradeDesk wallet={wallet} snapshot={snapshot} rpcAvailable={rpcAvailable} onNotice={setToast} /> : view !== 'Block explorer' ? <section className="discover-section">
|
||||
{view === 'Play' ? <PlaySection owned={owned} /> : view === 'Trade cards' ? <TradeDesk wallet={wallet} snapshot={snapshot} rpcAvailable={rpcAvailable} onNotice={setToast} /> : view !== 'Block explorer' ? <section className="discover-section">
|
||||
<div className="section-heading"><div><div className="section-eyebrow">{view === 'My collection' ? 'YOUR PERSONAL ENCYCLOPEDIA' : 'AN ENCYCLOPEDIA, REIMAGINED'}</div><h2>{view === 'My collection' ? 'Your cabinet of curiosities' : 'A world of possible discoveries'}<span className="count-badge">{visibleCards.length}</span></h2><p>{view === 'My collection' ? 'Confirmed native NFT ownership. Pending transfers stay here until mined.' : snapshot?.blocks.length ? 'Recent native NFTs on this node’s canonical chain.' : 'Sample previews only; mined NFTs use random Wikipedia pages with pictures. The same page may be minted more than once.'}</p></div>{view === 'Discover' && <button className="text-button" onClick={() => setView('My collection')}>My collection <ArrowRight size={16} /></button>}</div>
|
||||
<div className="filter-bar"><div className="category-tabs">{['All cards', 'Nature', 'Space', 'Science', 'People', 'History', 'Culture'].map(c => <button key={c} className={category === c ? 'selected' : ''} onClick={() => setCategory(c)}>{c}</button>)}</div><label className="search-input"><Search size={15} /><input aria-label="Search cards" placeholder="Find a discovery…" value={query} onChange={e => setQuery(e.target.value)} /></label></div>
|
||||
{filtered.length ? <div className="card-grid">{filtered.map(c => <div className="card-wrap" key={c.block?.tokenId ?? c.hash}><Card card={c} onClick={() => { setSelected(c); setTransferError(''); }} /><div className="card-list-caption"><span>{c.block ? `Block #${c.block.height}` : 'Example discovery'}</span><span className="caption-dot" />{c.block && snapshot ? short(testnetOwnerOf(snapshot, c.block.tokenId) ?? '') : 'Not owned'}</div>{c.block && snapshot?.pendingTransfers.some(tx => transactionCardIds(tx).includes(c.block!.tokenId)) && <span className="pending-label">Transfer or trade pending mining</span>}</div>)}</div> : <div className="empty-state"><img className="empty-state-logo" src="/original-logo.svg" alt="Wikideck" /><h3>{query || category !== 'All cards' ? 'No discoveries here. Yet.' : 'Your first discovery is waiting.'}</h3><p>{query || category !== 'All cards' ? 'Try another search or explore a different category.' : 'Use the native miner or receive a mined transfer on this chain. Restore a backup to access an existing wallet.'}</p><button className="button dark" onClick={goMine}><Pickaxe size={16} /> Explore native mining</button></div>}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
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';
|
||||
|
||||
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 '';
|
||||
}
|
||||
|
||||
/** Soft advice (DESIGN.md s8): warn, never block, when the early curve is thin. */
|
||||
export function deckWarning(deck: UICard[]): string {
|
||||
const cheap = deck.filter(c => c.cost <= 2).length;
|
||||
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;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<UICard[]>(deck);
|
||||
const [filter, setFilter] = useState<'all' | 'starter' | 'nft'>('all');
|
||||
const inDeck = new Set(draft.map(c => c.id));
|
||||
const shown = pool.filter(c => filter === 'all' || c.source === filter).sort((a, b) => a.cost - b.cost || a.title.localeCompare(b.title));
|
||||
const curve = useMemo(() => [1, 2, 3, 4, 5, 6].map(n => draft.filter(c => Math.min(c.cost, 6) === n).length), [draft]);
|
||||
const nftCount = pool.filter(c => c.source === 'nft').length;
|
||||
const problem = deckProblem(draft, ruleset);
|
||||
const warning = deckWarning(draft);
|
||||
const toggle = (card: UICard) => {
|
||||
if (inDeck.has(card.id)) setDraft(d => d.filter(c => c.id !== card.id));
|
||||
else if (draft.length < ruleset.deckSize) setDraft(d => [...d, card]);
|
||||
};
|
||||
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>
|
||||
<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>
|
||||
<div className="deck-strip" aria-label="Cards in deck">
|
||||
{draft.length ? [...draft].sort((a, b) => a.cost - b.cost).map(c => <GameCard key={c.id} card={c} size="board" onClick={() => toggle(c)} label={`Remove ${c.title} from deck`} />)
|
||||
: <p className="muted">Empty. Add cards below or use the starter deck.</p>}
|
||||
</div>
|
||||
<div className="category-tabs deck-filter" role="tablist">
|
||||
{([['all', 'All'], ['starter', 'Loaner'], ['nft', `My NFTs (${nftCount})`]] as const).map(([k, label]) =>
|
||||
<button key={k} role="tab" aria-selected={filter === k} className={filter === k ? 'selected' : ''} onClick={() => setFilter(k)}>{label}</button>)}
|
||||
</div>
|
||||
{filter === 'nft' && !nftCount && <p className="muted">You don’t own any cards on this network yet. Mine a block or receive a transfer, and it shows up here.</p>}
|
||||
<div className="pool-grid">
|
||||
{shown.map(c => <GameCard key={c.id} card={c} size="deck" selected={inDeck.has(c.id)} dim={!inDeck.has(c.id) && full}
|
||||
onClick={() => toggle(c)} label={`${inDeck.has(c.id) ? 'Remove' : 'Add'} ${c.title}, cost ${c.cost}, power ${c.power}${c.keyword ? `, ${c.keyword.name}` : ''}`} />)}
|
||||
</div>
|
||||
<div className="play-dock">
|
||||
{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([])} 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>
|
||||
</div>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { BookOpen, Landmark, Leaf, Orbit, Palette, Users, Zap } from 'lucide-react';
|
||||
import type { UICard } from './types.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" />;
|
||||
};
|
||||
|
||||
/** Phone-readable card face: cost, power, one keyword, title. 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;
|
||||
}) {
|
||||
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}` : ''}`}>
|
||||
<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-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>}
|
||||
</Tag>;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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 type { GameMode, LaneView, ResultView, UIAction, UICard } from './types.ts';
|
||||
|
||||
const BOT_DELAY_MS = 450;
|
||||
|
||||
function seededRand(seed: string) {
|
||||
let h = 1779033703 ^ seed.length;
|
||||
for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 3432918353);
|
||||
return () => { h = Math.imul(h ^ (h >>> 16), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); return ((h ^= h >>> 16) >>> 0) / 4294967296; };
|
||||
}
|
||||
|
||||
type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
|
||||
|
||||
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 [selected, setSelected] = useState<string>();
|
||||
const [sheet, setSheet] = useState<Sheet>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [banner, setBanner] = useState('');
|
||||
const rand = useRef(seededRand(`${seed}:bot`));
|
||||
const view = engine.view(state, 0);
|
||||
const legal = useMemo(() => engine.legal(state, 0), [state]);
|
||||
const prevBoard = useRef(new Set<string>());
|
||||
const [fresh, setFresh] = useState(new Set<string>());
|
||||
|
||||
// Turn feedback: banner on turn change, and a short highlight on newly revealed cards.
|
||||
const lastTurn = useRef(view.turn);
|
||||
useEffect(() => {
|
||||
const ids = new Set(view.lanes.flatMap(l => [...l.mine, ...l.theirs].map(c => c.id)));
|
||||
const added = new Set([...ids].filter(id => !prevBoard.current.has(id)));
|
||||
prevBoard.current = ids;
|
||||
if (added.size) { setFresh(added); const t = setTimeout(() => setFresh(new Set()), 900); return () => clearTimeout(t); }
|
||||
}, [state]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (view.turn !== lastTurn.current && !view.over) {
|
||||
lastTurn.current = view.turn;
|
||||
setBanner(view.turn === view.maxTurns ? `Final turn · ${view.maxEnergy} energy` : `Turn ${view.turn} · ${view.maxEnergy} energy`);
|
||||
const t = setTimeout(() => setBanner(''), 1400);
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [view.turn, view.over, view.maxTurns, view.maxEnergy]);
|
||||
useEffect(() => { if (engine.isOver(state)) { const t = setTimeout(() => onFinish(engine.result(state, 0)), 900); return () => clearTimeout(t); } }, [state, onFinish]);
|
||||
|
||||
// The bot moves once the player has ended the turn (it never sees staged plays).
|
||||
useEffect(() => {
|
||||
if (!view.waitingForOpponent) return;
|
||||
const t = setTimeout(() => {
|
||||
setState((s: unknown) => {
|
||||
let cur = s;
|
||||
for (let guard = 0; guard < 40 && !engine.isOver(cur); guard++) {
|
||||
const acts = engine.legal(cur, 1);
|
||||
if (!acts.length) break;
|
||||
const choice = bot.choose(engine.view(cur, 1), acts.filter(a => a.type !== 'concede'), rand.current);
|
||||
try { cur = engine.apply(cur, 1, choice); } catch { cur = engine.apply(cur, 1, { type: 'endTurn' }); }
|
||||
if (choice.type === 'endTurn') break;
|
||||
}
|
||||
return cur;
|
||||
});
|
||||
}, BOT_DELAY_MS);
|
||||
return () => clearTimeout(t);
|
||||
}, [view.waitingForOpponent, state, bot]);
|
||||
|
||||
const act = (a: UIAction) => {
|
||||
try { setState((s: unknown) => 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);
|
||||
const playable = (cardId: string) => legal.some(a => a.type === 'play' && a.cardId === cardId);
|
||||
const sel = view.hand.find(c => c.id === selected);
|
||||
const tapLane = (lane: LaneView) => {
|
||||
if (sel && canPlay(sel.id, lane.index)) { act({ type: 'play', cardId: sel.id, lane: lane.index }); setSelected(undefined); }
|
||||
else setSheet({ kind: 'lane', lane });
|
||||
};
|
||||
const ending = view.waitingForOpponent;
|
||||
const lastEvent = view.log.at(-1);
|
||||
|
||||
return <section className="match" aria-label={`${mode.name} match`}>
|
||||
<header className="match-bar">
|
||||
<span className="match-turn"><Hourglass size={14} /> Turn <b>{view.turn}</b>/{view.maxTurns}</span>
|
||||
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{bot.name} bot · <Layers3 size={13} /> {view.oppHandCount} in hand</span>
|
||||
<button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>
|
||||
</header>
|
||||
{banner && <div className="turn-banner" role="status">{banner}</div>}
|
||||
|
||||
<div className="lanes" style={{ gridTemplateColumns: `repeat(${view.lanes.length}, minmax(0, 1fr))` }}>
|
||||
{view.lanes.map(lane => {
|
||||
const target = !!sel && canPlay(sel.id, lane.index);
|
||||
const lead = lane.myPower > lane.theirPower ? 'ahead' : lane.myPower < lane.theirPower ? 'behind' : 'even';
|
||||
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 ?? ''}`}>
|
||||
<span className="lane-score theirs">{lane.theirPower}</span>
|
||||
<span className="lane-name">{lane.modifier?.name ?? lane.name}</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>}
|
||||
</div>
|
||||
</div>;
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="play-dock match-dock">
|
||||
<p className="dock-note" role="status" aria-live="polite">
|
||||
{error ? <span className="dock-error">{error}</span>
|
||||
: ending ? <><LoaderCircle className="spin" size={14} /> Opponent is choosing…</>
|
||||
: sel ? <><Zap size={12} /> <b>{sel.title}</b>{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.</>
|
||||
: lastEvent}
|
||||
</p>
|
||||
<div className="hand" aria-label="Your hand">
|
||||
{view.hand.length ? view.hand.map(c => <GameCard key={c.id} card={c} selected={selected === c.id} dim={!playable(c.id)}
|
||||
onClick={ending ? undefined : () => setSelected(selected === c.id ? undefined : c.id)} />)
|
||||
: <span className="muted">No cards in hand.</span>}
|
||||
</div>
|
||||
<div className="dock-row">
|
||||
<span className="energy" aria-label={`${view.energy} of ${view.maxEnergy} energy left`}>
|
||||
{Array.from({ length: view.maxEnergy }, (_, i) => <i key={i} className={i < view.energy ? 'on' : ''} />)}
|
||||
<b>{view.energy}</b>
|
||||
</span>
|
||||
<span className="deck-count"><Layers3 size={13} /> {view.deckCount}</span>
|
||||
<button className="button dark end-turn" disabled={ending || view.over} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}>
|
||||
{ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
|
||||
<div className="sheet" role="dialog" aria-modal="true" aria-label="Details">
|
||||
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
|
||||
{sheet.kind === 'card' && <><div className="sheet-card"><GameCard card={sheet.card} /></div>
|
||||
<h3>{sheet.card.title}</h3><p className="muted">{sheet.side === 'mine' ? 'Your card' : 'Opponent card'} · {sheet.card.category} · cost {sheet.card.cost} · power {sheet.card.power}{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>}
|
||||
<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>}</>}
|
||||
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); act({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
|
||||
</div>
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { CircleHelp, Globe2, Layers3, Play, Server, Swords, UserRound } from 'lucide-react';
|
||||
import type { TestnetBlock } from '../../shared/testnet.ts';
|
||||
import { engine } from './adapter.ts';
|
||||
import { BOTS, type Bot } from './bots.ts';
|
||||
import { cardFromBlock, loanerPool, starterDeck } from './cards.ts';
|
||||
import { DeckBuilder, deckProblem } 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 { 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 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 */ } },
|
||||
};
|
||||
|
||||
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 [screen, setScreen] = useState<Screen>(() => store.get(TUTORIAL_KEY) ? 'lobby' : 'tutorial');
|
||||
const [modeId, setModeId] = useState('standard');
|
||||
const [bot, setBot] = useState<Bot>(BOTS[0]);
|
||||
const [savedIds, setSavedIds] = useState<string[] | null>(() => { try { return JSON.parse(store.get(DECK_KEY) ?? 'null'); } catch { return null; } });
|
||||
const [seed, setSeed] = useState('');
|
||||
const [result, setResult] = useState<ResultView>();
|
||||
const mode = modes.find(m => m.id === modeId) ?? modes[0];
|
||||
|
||||
// Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
|
||||
const deck = useMemo(() => {
|
||||
if (!savedIds) return starterDeck();
|
||||
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(), []);
|
||||
|
||||
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]);
|
||||
|
||||
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')}
|
||||
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 === 'results' && result) return <Results result={result} modeName={mode.name} onRematch={start} onLobby={() => setScreen('lobby')} />;
|
||||
|
||||
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>
|
||||
</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>
|
||||
|
||||
<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>
|
||||
</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>}
|
||||
</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>
|
||||
|
||||
<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>}
|
||||
|
||||
<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>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { ArrowLeft, RotateCcw, Trophy } from 'lucide-react';
|
||||
import type { ResultView } from './types.ts';
|
||||
|
||||
export function Results({ result, modeName, onRematch, onLobby }: { result: ResultView; modeName: string; onRematch: () => void; onLobby: () => void }) {
|
||||
const outcome = result.winner === null ? 'draw' : result.winner === 0 ? 'win' : 'loss';
|
||||
const won = result.lanes.filter(l => l.winner === 0).length;
|
||||
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>
|
||||
<h2 id="result-title">{outcome === 'win' ? 'Victory!' : outcome === 'loss' ? 'Defeat' : 'Draw'}</h2>
|
||||
<p className="muted">{result.reason === 'concede' ? (outcome === 'win' ? 'Your opponent conceded.' : 'You conceded.')
|
||||
: `You won ${won} of ${result.lanes.length} lanes.`}</p>
|
||||
<ol className="result-lanes">
|
||||
{result.lanes.map(l => <li key={l.name} className={l.winner === 0 ? 'won' : l.winner === 1 ? 'lost' : 'tied'}>
|
||||
<span>{l.name}</span><b>{l.myPower} – {l.theirPower}</b><small>{l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}</small>
|
||||
</li>)}
|
||||
</ol>
|
||||
<p className="muted small">Matches are off-chain. No card was moved or burned.</p>
|
||||
<div className="play-actions">
|
||||
<button className="button outline" onClick={onLobby}><ArrowLeft size={16} /> Lobby</button>
|
||||
<button className="button dark" onClick={onRematch}><RotateCcw size={16} /> Rematch</button>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useState } from 'react';
|
||||
import { ArrowLeft, ArrowRight, Check } from 'lucide-react';
|
||||
import { GameCard } from './GameCard.tsx';
|
||||
import { starterDeck } from './cards.ts';
|
||||
|
||||
const demo = starterDeck();
|
||||
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' },
|
||||
];
|
||||
|
||||
export function Tutorial({ onDone }: { onDone: () => void }) {
|
||||
const [i, setI] = useState(0);
|
||||
const step = STEPS[i];
|
||||
return <section className="play-panel tutorial" aria-labelledby="tutorial-title">
|
||||
<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 === '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>}
|
||||
</div>
|
||||
<p>{step.body}</p>
|
||||
<div className="play-actions">
|
||||
<button className="button outline" onClick={() => setI(i - 1)} disabled={i === 0}><ArrowLeft size={16} /> Back</button>
|
||||
{i < STEPS.length - 1
|
||||
? <button className="button dark" onClick={() => setI(i + 1)}>Next <ArrowRight size={16} /></button>
|
||||
: <button className="button dark" onClick={onDone}><Check size={16} /> Got it</button>}
|
||||
</div>
|
||||
<button className="text-button skip" onClick={onDone}>Skip tutorial</button>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// 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';
|
||||
|
||||
export const engine: EngineAdapter<any> = mockEngine;
|
||||
|
||||
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,
|
||||
};
|
||||
export const LOCAL_MODES: GameMode[] = [
|
||||
{ id: 'standard', name: 'Standard', description: STANDARD_RULESET.description, host: { kind: 'local' }, ruleset: STANDARD_RULESET },
|
||||
];
|
||||
@@ -0,0 +1,16 @@
|
||||
// AI opponents. ui-b owns the real easy/normal bots; 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. */
|
||||
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' };
|
||||
},
|
||||
};
|
||||
|
||||
export const BOTS: Bot[] = [randomBot];
|
||||
@@ -0,0 +1,54 @@
|
||||
import { rarity } from '../../shared/protocol.ts';
|
||||
import type { TestnetBlock } from '../../shared/testnet.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.' },
|
||||
};
|
||||
|
||||
// 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',
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function cardFromBlock(block: TestnetBlock): 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 };
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// 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' };
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,172 @@
|
||||
/* Play section. Mobile-first: 360px minimum, thumb-reachable bottom dock, no hover-only states. */
|
||||
.play-panel{max-width:760px;margin:0 auto 32px;padding:20px 16px 0;border:1px solid var(--theme-border);background:var(--ctp-mantle);border-radius:14px;color:var(--ctp-text)}
|
||||
.play-panel h2{font-size:26px;letter-spacing:-.6px;margin:4px 0 8px;display:flex;align-items:center;flex-wrap:wrap;gap:8px}
|
||||
.play-panel .count-badge{margin-left:0}
|
||||
.play-panel .count-badge.ok{color:var(--ctp-green);border-color:var(--ctp-green)}
|
||||
.play-panel .muted{font-size:13px;line-height:1.6;color:var(--ctp-subtext0)}
|
||||
.play-panel .muted.small,.small{font-size:11px}
|
||||
.play-panel .section-eyebrow{font-size:10px}
|
||||
.play-actions{display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end}
|
||||
.play-actions .button{min-height:48px;font-size:13px;padding:12px 16px;flex:1 1 auto}
|
||||
.play-actions .button.outline{flex:0 1 auto}
|
||||
.play-actions .button:disabled{opacity:.45;cursor:not-allowed}
|
||||
.play-dock{position:sticky;bottom:0;z-index:5;margin:18px -16px 0;padding:10px 16px calc(12px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 14px 14px}
|
||||
.dock-note{min-height:20px;margin:0 0 8px;font-size:12px;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px;line-height:1.35}
|
||||
.dock-error{color:var(--ctp-red)}
|
||||
.icon-button{display:inline-flex;align-items:center;justify-content:center;min-width:40px;min-height:40px;border-radius:8px;background:var(--ctp-surface0);color:var(--ctp-subtext1)}
|
||||
|
||||
/* Card faces */
|
||||
.gcard{position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid var(--ctp-surface1);border-radius:10px;padding:0;overflow:hidden;transition:transform .15s ease,border-color .15s ease,box-shadow .15s ease;--cat:var(--ctp-overlay1)}
|
||||
.gcard:disabled{cursor:default;opacity:1}
|
||||
.gcard.cat-space{--cat:var(--ctp-lavender)}.gcard.cat-nature{--cat:var(--ctp-green)}.gcard.cat-people{--cat:var(--ctp-peach)}
|
||||
.gcard.cat-science{--cat:var(--ctp-sky)}.gcard.cat-history{--cat:var(--ctp-yellow)}.gcard.cat-culture{--cat:var(--ctp-pink)}
|
||||
.gcard-art{display:flex;align-items:center;justify-content:center;height:46px;background:color-mix(in srgb,var(--cat) 28%,var(--ctp-surface0));color:var(--cat);position:relative;overflow:hidden}
|
||||
.gcard-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
|
||||
.gcard-art svg{position:relative}
|
||||
.gcard-cost,.gcard-power{position:absolute;top:4px;z-index:2;min-width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;box-shadow:0 1px 3px rgb(0 0 0/.35)}
|
||||
.gcard-cost{left:4px;background:var(--ctp-blue);color:var(--ctp-crust)}
|
||||
.gcard-power{right:4px;background:var(--ctp-peach);color:var(--ctp-crust);border-radius:6px}
|
||||
.gcard-power.up{background:var(--ctp-green)}.gcard-power.down{background:var(--ctp-red)}
|
||||
.gcard-title{font-size:12px;font-weight:700;line-height:1.2;padding:6px 7px 2px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em}
|
||||
.gcard-keyword{display:flex;align-items:center;gap:3px;margin:auto 6px 6px;font-size:10px;font-weight:700;color:var(--cat);text-transform:uppercase;letter-spacing:.4px}
|
||||
.gcard-nft{position:absolute;top:32px;right:4px;font-size:8px;font-weight:800;padding:1px 4px;border-radius:3px;background:var(--ctp-mauve);color:var(--ctp-crust)}
|
||||
.gcard-hand,.gcard-deck{width:88px;min-height:118px;flex:0 0 auto}
|
||||
.gcard-deck{width:auto}
|
||||
.gcard-board{width:100%;min-height:0;border-radius:7px;border-width:1px;flex-direction:row;align-items:center}
|
||||
.gcard-board .gcard-art{width:22px;height:30px;flex:0 0 22px}
|
||||
.gcard-board .gcard-art img{display:none}
|
||||
.gcard-board .gcard-cost{display:none}
|
||||
.gcard-board .gcard-power{position:static;margin:0 3px 0 auto;min-width:22px;height:22px;font-size:12px;flex:0 0 auto;box-shadow:none}
|
||||
.gcard-board .gcard-title{font-size:10px;padding:2px 4px;min-height:0;-webkit-line-clamp:1;display:block;white-space:nowrap;text-overflow:ellipsis;flex:1 1 auto;min-width:0}
|
||||
.gcard.is-selected{border-color:var(--theme-accent);box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-6px)}
|
||||
.gcard-board.is-selected{transform:none;border-style:dashed;box-shadow:none;opacity:.85}
|
||||
.gcard.is-dim{opacity:.45}
|
||||
.gcard.is-fresh{animation:gcard-reveal .45s ease-out}
|
||||
@keyframes gcard-reveal{0%{transform:scale(.6) rotateY(90deg);opacity:0}100%{transform:none;opacity:1}}
|
||||
.gcard:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
|
||||
|
||||
/* Lobby */
|
||||
.lobby-head{display:flex;justify-content:space-between;align-items:flex-start;gap:10px;flex-wrap:wrap}
|
||||
.account-chip{display:flex;align-items:center;gap:8px;padding:6px 10px;border-radius:999px;background:var(--ctp-surface0);font-size:12px;color:var(--ctp-subtext1)}
|
||||
.account-chip img{width:22px;height:22px;border-radius:50%}
|
||||
.account-chip .text-button{font-size:11px;padding:4px 0;color:var(--theme-accent)}
|
||||
.account-chip .text-button:disabled{color:var(--ctp-overlay1);cursor:default}
|
||||
.lobby-label{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:20px 0 8px;display:flex;gap:8px;align-items:center}
|
||||
.mode-list{display:grid;gap:8px}
|
||||
.mode{display:flex;gap:12px;align-items:flex-start;text-align:left;padding:12px;border-radius:10px;border:1.5px solid var(--theme-border);background:var(--ctp-base);color:var(--ctp-text);min-height:56px}
|
||||
.mode.selected{border-color:var(--theme-accent);background:color-mix(in srgb,var(--theme-accent) 10%,var(--ctp-base))}
|
||||
.mode-icon{flex:0 0 36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;background:var(--ctp-surface0);color:var(--theme-accent)}
|
||||
.mode-copy{display:flex;flex-direction:column;gap:2px;min-width:0}
|
||||
.mode-copy b{font-size:14px}.mode-copy small{font-size:12px;color:var(--ctp-subtext0);line-height:1.4}
|
||||
.mode-copy .mode-host{color:var(--ctp-overlay2);font-size:11px}
|
||||
.play-panel .category-tabs{display:flex;gap:6px;flex-wrap:wrap}
|
||||
.play-panel .category-tabs button{font-size:13px;padding:10px 14px;min-height:40px;border:1px solid var(--theme-border)}
|
||||
.deck-summary{width:100%;display:flex;align-items:center;gap:14px;padding:12px;border-radius:10px;border:1.5px solid var(--theme-border);background:var(--ctp-base);color:var(--ctp-text);text-align:left}
|
||||
.deck-summary>span:nth-child(2){display:flex;flex-direction:column;flex:1;font-size:14px}
|
||||
.deck-summary small{color:var(--ctp-subtext0);font-size:12px}
|
||||
.deck-fan{display:flex;flex:0 0 auto}
|
||||
.fan-chip{width:30px;height:42px;border-radius:6px;margin-left:-12px;display:flex;align-items:center;justify-content:center;border:1.5px solid var(--ctp-surface1);background:color-mix(in srgb,var(--cat) 30%,var(--ctp-surface0));color:var(--cat);transform:rotate(calc(var(--i,0)*4deg - 6deg));--cat:var(--ctp-overlay1)}
|
||||
.fan-chip:first-child{margin-left:0}
|
||||
.fan-chip.cat-space{--cat:var(--ctp-lavender)}.fan-chip.cat-nature{--cat:var(--ctp-green)}.fan-chip.cat-people{--cat:var(--ctp-peach)}.fan-chip.cat-science{--cat:var(--ctp-sky)}.fan-chip.cat-history{--cat:var(--ctp-yellow)}.fan-chip.cat-culture{--cat:var(--ctp-pink)}
|
||||
.play-cta{font-size:15px!important}
|
||||
.engine-note{text-align:center;padding-bottom:10px}
|
||||
|
||||
/* Deck builder */
|
||||
.deck-curve{display:flex;gap:6px;align-items:flex-end;height:70px;margin:10px 0}
|
||||
.deck-curve>div{flex:1;display:flex;flex-direction:column;align-items:center;height:100%;justify-content:flex-end;gap:2px;font-size:10px;color:var(--ctp-subtext0)}
|
||||
.deck-curve span{width:100%;max-width:34px;background:var(--theme-accent);border-radius:4px 4px 0 0;min-height:2px;transition:height .2s}
|
||||
.deck-strip{display:grid;grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:5px;margin-bottom:14px}
|
||||
.pool-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(96px,1fr));gap:10px;margin-top:12px}
|
||||
.pool-grid .gcard.is-selected{transform:none}
|
||||
|
||||
/* Match */
|
||||
.match{max-width:760px;margin:0 auto 24px;display:flex;flex-direction:column;border:1px solid var(--theme-border);border-radius:14px;background:var(--ctp-mantle);color:var(--ctp-text);position:relative}
|
||||
.match-bar{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 10px;border-bottom:1px solid var(--theme-border);font-size:12px;color:var(--ctp-subtext1)}
|
||||
.match-bar>span{display:inline-flex;align-items:center;gap:5px}
|
||||
.match-turn b{font-size:16px;color:var(--ctp-text)}
|
||||
.turn-banner{position:absolute;top:56px;left:50%;transform:translateX(-50%);z-index:8;background:var(--theme-accent);color:var(--ctp-crust);padding:8px 18px;border-radius:999px;font-weight:800;font-size:14px;white-space:nowrap;animation:banner-in 1.4s ease both;pointer-events:none}
|
||||
@keyframes banner-in{0%{opacity:0;transform:translate(-50%,-8px)}15%,80%{opacity:1;transform:translate(-50%,0)}100%{opacity:0}}
|
||||
.lanes{display:grid;gap:6px;padding:8px}
|
||||
.lane{display:flex;flex-direction:column;gap:4px;min-width:0;border-radius:10px;padding:4px;background:var(--ctp-base);border:1.5px solid transparent;transition:border-color .15s,background .15s}
|
||||
.lane.is-target{border-color:var(--theme-accent);background:color-mix(in srgb,var(--theme-accent) 12%,var(--ctp-base))}
|
||||
.lane.is-blocked{opacity:.6}
|
||||
.lane-side{display:flex;flex-direction:column;gap:3px;min-height:120px}
|
||||
.lane-side.theirs{justify-content:flex-end}
|
||||
.lane-plate{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:4px;padding:8px 4px;border-radius:8px;background:var(--ctp-surface0);color:var(--ctp-text);min-height:52px}
|
||||
.lane-name{font-size:10px;line-height:1.2;text-align:center;color:var(--ctp-subtext1);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
|
||||
.lane-score{font-weight:800;font-size:17px;min-width:24px;text-align:center}
|
||||
.lane-score.theirs{color:var(--ctp-red)}.lane-score.mine{color:var(--ctp-green)}
|
||||
.lane-plate.ahead{box-shadow:inset 0 -3px 0 var(--ctp-green)}.lane-plate.behind{box-shadow:inset 0 3px 0 var(--ctp-red)}
|
||||
.lane-drop{border:1.5px dashed var(--theme-accent);border-radius:7px;color:var(--theme-accent);font-size:11px;font-weight:700;text-align:center;padding:6px 2px}
|
||||
.match-dock{margin:0;border-radius:0 0 14px 14px;padding-inline:10px}
|
||||
.hand{display:flex;gap:8px;overflow-x:auto;padding:8px 2px 6px;scroll-snap-type:x proximity;-webkit-overflow-scrolling:touch}
|
||||
.hand .gcard{scroll-snap-align:start}
|
||||
.dock-row{display:flex;align-items:center;gap:12px;margin-top:4px}
|
||||
.energy{display:flex;align-items:center;gap:3px}
|
||||
.energy i{width:10px;height:18px;border-radius:3px;background:var(--ctp-surface1)}
|
||||
.energy i.on{background:var(--ctp-blue)}
|
||||
.energy b{font-size:18px;margin-left:5px;color:var(--ctp-blue)}
|
||||
.deck-count{display:inline-flex;gap:4px;align-items:center;font-size:12px;color:var(--ctp-subtext0)}
|
||||
.end-turn{margin-left:auto;min-height:52px!important;min-width:132px;font-size:15px!important}
|
||||
.end-turn:disabled{opacity:.55}
|
||||
|
||||
/* Bottom sheet (details instead of hover tooltips) */
|
||||
.sheet-backdrop{position:fixed;inset:0;z-index:40;background:var(--theme-scrim,rgb(0 0 0/.5));display:flex;align-items:flex-end;justify-content:center}
|
||||
.sheet{position:relative;width:100%;max-width:520px;background:var(--ctp-mantle);color:var(--ctp-text);border-radius:16px 16px 0 0;padding:22px 18px calc(18px + env(safe-area-inset-bottom));animation:sheet-up .18s ease-out;max-height:80vh;overflow:auto}
|
||||
.sheet h3{font-size:20px;margin:6px 0}
|
||||
.sheet p{font-size:14px;line-height:1.55}
|
||||
.sheet-card{display:flex;justify-content:center}
|
||||
.sheet-card .gcard{width:120px;min-height:150px}
|
||||
@keyframes sheet-up{from{transform:translateY(40px);opacity:0}to{transform:none;opacity:1}}
|
||||
|
||||
/* Results */
|
||||
.results{text-align:center}
|
||||
.results h2{justify-content:center;font-size:34px}
|
||||
.results .section-eyebrow{justify-content:center}
|
||||
.result-mark{margin:8px auto 14px;width:64px;height:64px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:var(--ctp-surface0);color:var(--ctp-overlay2)}
|
||||
.results.win .result-mark{background:var(--ctp-yellow);color:var(--ctp-crust);animation:pop .4s ease-out}
|
||||
.results.loss .result-mark{color:var(--ctp-red)}
|
||||
@keyframes pop{0%{transform:scale(.4)}70%{transform:scale(1.1)}100%{transform:none}}
|
||||
.result-lanes{list-style:none;padding:0;display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:18px 0}
|
||||
.result-lanes li{display:flex;flex-direction:column;gap:2px;padding:12px 4px;border-radius:10px;background:var(--ctp-base);border:1.5px solid var(--theme-border)}
|
||||
.result-lanes li.won{border-color:var(--ctp-green)}.result-lanes li.lost{border-color:var(--ctp-red)}
|
||||
.result-lanes b{font-size:20px}.result-lanes small,.result-lanes span{font-size:11px;color:var(--ctp-subtext0)}
|
||||
|
||||
/* Tutorial */
|
||||
.tutorial p{font-size:14px;line-height:1.6}
|
||||
.tutorial-visual{min-height:150px;display:flex;align-items:center;justify-content:center;margin:12px 0;padding:12px;border-radius:12px;background:var(--ctp-base)}
|
||||
.tut-lanes{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;width:100%}
|
||||
.tut-lanes div{display:flex;flex-direction:column;align-items:center;padding:16px 4px;border-radius:8px;background:var(--ctp-surface0);font-size:12px}
|
||||
.tut-lanes b{font-size:18px}.tut-lanes .won{box-shadow:inset 0 -3px 0 var(--ctp-green)}.tut-lanes .lost{box-shadow:inset 0 3px 0 var(--ctp-red)}
|
||||
.tut-card{display:flex;align-items:center;gap:14px;flex-wrap:wrap;justify-content:center}
|
||||
.tut-card ul{list-style:none;padding:0;margin:0;font-size:13px;line-height:1.9}
|
||||
.tut-energy{display:flex;align-items:flex-end;gap:8px;height:90px}
|
||||
.tut-energy span{width:26px;border-radius:4px 4px 0 0;background:var(--ctp-blue);color:var(--ctp-crust);font-weight:800;display:flex;justify-content:center;align-items:flex-start;font-size:12px}
|
||||
.tut-lane-target{padding:22px 16px;border:2px dashed var(--theme-accent);border-radius:10px;color:var(--theme-accent);font-weight:700;display:flex;flex-direction:column;gap:4px;text-align:center}
|
||||
.tut-lane-target small{font-weight:400;color:var(--ctp-subtext0)}
|
||||
.tut-facedown{width:60px;height:84px;border-radius:8px;background:repeating-linear-gradient(45deg,var(--ctp-surface0) 0 6px,var(--ctp-surface1) 6px 12px);display:flex;align-items:center;justify-content:center;font-size:22px;font-weight:800;color:var(--ctp-overlay2)}
|
||||
.tutorial .skip{display:block;margin:6px auto 12px}
|
||||
|
||||
@media(min-width:700px){
|
||||
.gcard-hand{width:104px;min-height:136px}
|
||||
.gcard-art{height:58px}
|
||||
.lane-side{min-height:150px}
|
||||
.gcard-board .gcard-title{font-size:11px}
|
||||
.play-panel{padding:26px 26px 0}.play-dock{margin-inline:-26px;padding-inline:26px}
|
||||
}
|
||||
@media(max-width:400px){
|
||||
.lanes{gap:4px;padding:6px 4px}
|
||||
.lane{padding:3px}
|
||||
.lane-score{font-size:15px;min-width:18px}
|
||||
.gcard-board .gcard-art{display:none}
|
||||
.end-turn{min-width:112px}
|
||||
}
|
||||
.gcard-board .gcard-power{order:3}
|
||||
/* Phones: the match takes the whole screen so the board and the thumb dock both fit. */
|
||||
@media(max-width:760px){
|
||||
.match{position:fixed;inset:0;z-index:30;margin:0;max-width:none;border:0;border-radius:0;padding-top:env(safe-area-inset-top);overflow:hidden}
|
||||
.match .lanes{flex:1 1 auto;overflow-y:auto;align-content:start}
|
||||
.match-dock{position:static;border-radius:0}
|
||||
.lane-side{min-height:84px}
|
||||
}
|
||||
.deck-warning{color:var(--ctp-yellow)}
|
||||
@@ -0,0 +1,94 @@
|
||||
// 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.
|
||||
|
||||
export type PlayerIndex = 0 | 1;
|
||||
|
||||
/** A card as the deck builder and match screen display it: at most 3 numbers and 1 keyword. */
|
||||
export type UICard = {
|
||||
id: string; // unique within a match/deck (instance id)
|
||||
pageId: number;
|
||||
title: string;
|
||||
category: string;
|
||||
image?: string;
|
||||
cost: number;
|
||||
power: number; // current power (including modifiers on board)
|
||||
basePower: number;
|
||||
keyword?: { id: string; name: string; text: string };
|
||||
source: 'starter' | 'nft';
|
||||
tokenId?: string;
|
||||
rarity?: string;
|
||||
};
|
||||
|
||||
export type LaneView = {
|
||||
index: number;
|
||||
name: string;
|
||||
modifier?: { name: string; text: string };
|
||||
revealed: boolean;
|
||||
mine: UICard[];
|
||||
theirs: UICard[];
|
||||
staged: UICard[]; // my plays this turn, not yet revealed
|
||||
myPower: number;
|
||||
theirPower: number;
|
||||
capacity: number;
|
||||
};
|
||||
|
||||
export type MatchView = {
|
||||
me: PlayerIndex;
|
||||
turn: number;
|
||||
maxTurns: number;
|
||||
energy: number; // remaining this turn
|
||||
maxEnergy: number;
|
||||
hand: UICard[];
|
||||
deckCount: number;
|
||||
oppHandCount: number;
|
||||
oppDeckCount: number;
|
||||
lanes: LaneView[];
|
||||
log: string[]; // newest last
|
||||
waitingForOpponent: boolean;
|
||||
over: boolean;
|
||||
};
|
||||
|
||||
export type UIAction =
|
||||
| { type: 'play'; cardId: string; lane: number }
|
||||
| { type: 'unstage'; cardId: string }
|
||||
| { type: 'endTurn' }
|
||||
| { type: 'concede' };
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
export type GameMode = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
host: { kind: 'local' } | { kind: 'peer'; name: string; url: string };
|
||||
ruleset: Ruleset;
|
||||
players?: 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;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// 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 };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
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 };
|
||||
const str = (v: unknown, max = 120) => (typeof v === 'string' ? v.slice(0, max) : 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) } }];
|
||||
});
|
||||
}
|
||||
|
||||
export function useModes() {
|
||||
const [remote, setRemote] = useState<GameMode[]>([]);
|
||||
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'); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
return { modes: [...LOCAL_MODES, ...remote], status };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { engine, STANDARD_RULESET } 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 type { PlayerIndex } from '../src/game/types.ts';
|
||||
|
||||
function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
|
||||
|
||||
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++) {
|
||||
for (const p of [0, 1] as PlayerIndex[]) {
|
||||
const legal = engine.legal(s, p);
|
||||
if (!legal.length) continue;
|
||||
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal.filter(a => a.type !== 'concede'), 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('random legal play always terminates within the turn cap and is deterministic', () => {
|
||||
for (let i = 0; i < 60; 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.deepEqual(ra, engine.result(b, 0));
|
||||
const rb = engine.result(a, 1);
|
||||
if (ra.winner !== null) assert.equal(rb.winner, ra.winner);
|
||||
}
|
||||
});
|
||||
|
||||
test('opponent staged plays stay hidden until reveal', () => {
|
||||
let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], 'hidden');
|
||||
const play = engine.legal(s, 1).find(a => a.type === 'play');
|
||||
assert.ok(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);
|
||||
});
|
||||
|
||||
test('illegal plays are rejected and unstage refunds energy', () => {
|
||||
let s = engine.createMatch(STANDARD_RULESET, [starterDeck(), starterDeck()], '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 }));
|
||||
const play = engine.legal(s, 0).find(a => a.type === 'play');
|
||||
if (play && 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 });
|
||||
assert.equal(engine.view(s, 0).energy, v.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,
|
||||
] });
|
||||
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'), []);
|
||||
});
|
||||
Reference in New Issue
Block a user