Files
wikideck/tests/ui-play.test.ts
claudeanderic 4f7a8a7c74 Night 1: Edit War card game, eom.dev accounts, peer-hosted modes, Android and iOS apps (#22)
Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`.

**What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`):
- **Edit War:**
  - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold
  - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default
  - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial
  - a landing page (fixes #3)
- **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1.
- **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`).
- **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`).
- **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`).
- **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged).

**Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs.

**Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely.

**Decisions for Eric** (see REPORT.md, Known issues and Next steps):
1. whether the live node should set `WIKIDECK_USER_AGENT`
2. the Xcode licence, which you should accept yourself
3. #49 in the fork, a bot change held after the freeze
4. on-chain host rewards (proposal only, in HOSTING.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#22

Co-authored-by: Claude <claude@eom.dev>
2026-11-17 17:40:58 +00:00

155 lines
8.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import { DEFAULT_RULESET } from '../shared/game/index.ts';
import { engine } from '../src/game/adapter.ts';
import { randomBot } from '../src/game/bots.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(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).filter(a => a.type !== 'concede');
if (!legal.length) continue;
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
}
}
return s;
}
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('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 <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
assert.deepEqual(ra, engine.result(b, 0));
const rb = engine.result(a, 1);
assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result');
assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]);
}
});
test('my view never shows the opponent’s queued cards', () => {
// Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
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, '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);
const theirs = engine.view(s, 1);
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
});
test('unstage refunds energy, and illegal plays are explained', () => {
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
const v = engine.view(s, 0);
const expensive = v.hand.find(c => c.cost > v.energy);
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?.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('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);
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: '' }), []);
});
test('bots get only the hidden-information view, never the full match state', () => {
const s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('v')], 'view-only');
const v = engine.view(s, 1);
assert.ok(v.engine?.view);
const json = JSON.stringify(v);
assert.ok(!json.includes('"rng"') && !json.includes('"seed"'), 'no RNG state or seed');
assert.ok(!('deck' in (v.engine!.view as object)), 'no deck order');
});
test('leaderboard parsers cap and sanitise host data', async () => {
const { parseHosts, parseLeaderboard } = await import('../src/game/Leaderboards.tsx');
const hosts = parseHosts({ hosts: [{ operator: 'x'.repeat(200), matchesHosted: 5, playersOnline: -3, self: true }, null, 'junk', ...Array(20).fill({ origin: 'http://n' })] });
assert.equal(hosts.length, 10);
assert.equal(hosts[0].operator.length, 60);
assert.equal(hosts[0].playersOnline, 0);
assert.equal(hosts[1].operator, 'http://n');
assert.deepEqual(parseLeaderboard({ entries: [{ name: '', wins: 2 }] }), [{ name: 'Anonymous', wins: 2, losses: 0, draws: 0, played: 0 }]);
assert.deepEqual(parseLeaderboard(42), []);
});
test('the final board shows scoring power, and queued cards preview their lane power', () => {
const s = playOut('final-board');
const v = engine.view(s, 0), r = engine.result(s, 0);
assert.ok(v.over);
v.lanes.forEach((l, i) => { assert.equal(l.myPower, r.lanes[i].myPower); assert.equal(l.theirPower, r.lanes[i].theirPower); });
let m = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('q')], 'queued-power');
const play = engine.legal(m, 0).find(a => a.type === 'play');
if (play?.type === 'play') {
m = engine.apply(m, 0, play);
const lane = engine.view(m, 0).lanes[play.lane];
const [q] = lane.staged;
const bonus = q.home === lane.stat ? DEFAULT_RULESET.onTopicBonus[q.cost] : 0;
assert.equal(q.power, q.basePower + q.trend + bonus);
}
});
test('results explain a tied Topic decided by the on-topic tie-break', async () => {
const { renderToStaticMarkup } = await import('react-dom/server');
const { createElement } = await import('react');
const { Results } = await import('../src/game/Results.tsx');
const html = renderToStaticMarkup(createElement(Results, { modeName: 'Standard', onRematch() {}, onLobby() {}, result: {
winner: 1, turns: 6, reason: 'topics', totalPower: [37, 42],
lanes: [{ name: 'Current Events', myPower: 13, theirPower: 13, winner: 1 }, { name: 'Archive', myPower: 10, theirPower: 10, winner: 0 },
{ name: 'Stub', myPower: 14, theirPower: 19, winner: 1 }] } }));
assert.equal(html.match(/Tie, decided by on-topic cards/g)?.length, 2);
});