Merge pull request '[sim-balance] Duel bot adapter on the real engine and DUEL_BALANCE.md (#64)' (#84) from night2/sim-balance/duel-adapter into night/2026-11-17
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
# WikiDeck Duel: balance report
|
||||
|
||||
**Owner:** sim-balance (issue #64). **Rules:** `docs/game/DUEL_DESIGN.md`, `docs/night2/BRIEF.md`.
|
||||
Every proposal here is **data only**: ruleset keys (`shared/duel` ruleset) or derivation table values (`DERIVE_RULES`). No code changes are proposed in this file.
|
||||
|
||||
## How to reproduce
|
||||
|
||||
```
|
||||
# Node 24 (node:24-alpine on r350/inspiron). At most 4 workers on r350 (Night 1 ran out of memory).
|
||||
npx tsx scripts/sim/duel-run.ts --engine duel --matches 3000 --workers 4 --mix default \
|
||||
--out ../sim-out/duel --label base --sha $(git rev-parse --short HEAD)
|
||||
# Ruleset overrides as JSON (shallow-merged into the duel ruleset):
|
||||
npx tsx scripts/sim/duel-run.ts --engine duel --rules '{"startingLife":18}' --label life18 ...
|
||||
```
|
||||
|
||||
- **Card pool:** the 236 real cards in `docs/game/card-sample.json`, derived by duel-cards (`shared/duel/sample.ts`, `docs/game/duel-card-sample.json`). No chain, no network.
|
||||
- **Decks:** 120 decks of exactly 40 unique cards (each NFT once), sampled without replacement (`scripts/sim/duel-decks.ts`). Half are uniform random; the rest are skewed archetypes: Figure-, Doctrine-, Event-, Location- and Institution-heavy, low curve and high curve.
|
||||
- **Bots** (`shared/bots/duel-bots.ts`): `heuristic` (greedy plays on a material evaluation, rule-based attacks and blocks), `mc`/`mc-lite` (shallow Monte Carlo over heuristic rollouts, re-sampling hidden cards on every rollout, so it is not clairvoyant), `greedy` (one-ply) and `random`. Bots see only `viewFor` of their seat.
|
||||
- **Balance stats use bot-symmetric games only** (both seats the same bot). Mixed pairs measure skill.
|
||||
- **Card win rate** = win rate of the seat that played the card, in games where only one side played it. It has a positive baseline (winners play more cards), so compare cards against each other and against the "all plays" baseline, not against 50%.
|
||||
- **Minutes** are a model, not a measurement: 10 s per turn plus 4 s per atomic action (each play, attacker toggle, block and confirm).
|
||||
- **Connected pair rate** = share of all 27,730 sample pairs with any Connected tier (`connectedTier`).
|
||||
|
||||
## Targets
|
||||
| Metric | Target | Source |
|
||||
|---|---|---|
|
||||
| First-player win rate | 48–54% | DUEL_DESIGN §2.6 (issue #64 asks 48–52%) |
|
||||
| Median game length | 8–12 turns each, 8–15 minutes | issue #64 |
|
||||
| Stalls | < 5% reach turn 20 each | DUEL_DESIGN §2.6 |
|
||||
| Connected | 15–30% of pairs | BRIEF |
|
||||
| Famous cards | bigger and pricier, not strictly better: fame vs win rate r ≈ 0 within a cost | BRIEF |
|
||||
|
||||
## Balance v1 (00:05, from the v1 runs below)
|
||||
|
||||
**Ship as ruleset defaults (`DEFAULT_DUEL_RULESET`, data only):**
|
||||
|
||||
| Key | From | To | Why |
|
||||
|---|---|---|---|
|
||||
| `secondPlayerCitations` | 0 | **1** | First player 60.1% → **54.7%** [53–57] (v1-cand, n≈2700). The edge is tempo, and this is the only lever that moved it. |
|
||||
| `turnCap` | null | **40** (20 each) | Games past 20 turns each 3.4% → **0%**. 3.9% of games are decided at the cap; median and p90 unchanged (8 / 12). |
|
||||
|
||||
v1-cand (both changes, 3000 matches, engine 4623930 + duel-cards 067de83): first player 54.7% [53–57], turns each 6 / 8 / 12, est. minutes median 7.9 / p90 13.5, 0 library-outs, Connected 17.2% of pairs.
|
||||
|
||||
The first-player rate sits at the top edge of DUEL_DESIGN's 48–54% band (issue #64 asked for 48–52%). `secondPlayerCitations: 2` was not tested; duel-design prefers to accept ~54% over a 2-Citation swing.
|
||||
|
||||
**Landed:** duel-core set both as `DEFAULT_DUEL_RULESET` values on `engine-wip` 0eb80d2. night-review's random-play soak there (300 matches) gives a first-player rate of 51.0%, down from 62.7%, with 0 leaks, exact replay, and `turnCap` ending forced stalls at turn 40. duel-design recorded both in DUEL_DESIGN v1.3 (#66).
|
||||
|
||||
**Not shipped, with the evidence:**
|
||||
- Second seat +1 opening card: no effect (60.7%); the mulligan and the 7-card hand limit absorb it.
|
||||
- `garrisonStep` 15: Location-heavy decks +4 pts, but games get longer (p90 14, 4.5% past 20 turns).
|
||||
- `territoryCap` 3, `locationsPerTurn` 2, `stubMax` 1, `startingLife` 16/24: ≤ ±3 pts on first player or Location decks.
|
||||
- `libraryEmpty: reshuffle`: games stretch out (the run didn't finish in 9 min); BRIEF keeps the MTG rule.
|
||||
- `firstPlayerDraws: true`: worsens the edge (+1.7 pts).
|
||||
|
||||
**Open for v1.1: Locations.** Location-heavy decks win ~17–21% in every variant, and Location cards are the weakest type (47–48%). The T2 rider "When this enters, draw a card" (v1-cand-ld) raises the Location card to 51.7% but does **not** help Location-heavy decks (16.5%), pushes the first player back to 58.4%, and brings back library-outs (117 of 3000). It needs another lever first, e.g. the conditional version ("if you already control 2 or more Locations") or a Location body (`garrisonStep`) change, tested together with spc1. Since random collections are ~32% Locations, this matters for real players.
|
||||
|
||||
**Healthy, leave alone:** Connected (17.2% of pairs, fires on 28% of plays, inside 15–30%). Famous cards are bigger, not strictly better: fame vs card win rate r = 0.10–0.20 overall, ≈0 or negative within a cost. Keywords all net positive; Featured strongest, kept per duel-design.
|
||||
|
||||
## Frozen head (01:15)
|
||||
|
||||
**Not run.** At the 01:15 freeze `night/2026-11-17` was still at 2af2e7f: no PR had merged all night (night-lead unreachable, see #53), so there was no frozen head containing the duel engine. The reference result is therefore **v1-cand at engine-wip 4623930 + duel-cards 067de83 (not frozen head)**. At 01:16 the newest unmerged heads were: engine-wip 0eb80d2 (balance v1 as defaults), duel-cards 5076299, duel-adapter d97cbc2. Once they merge, re-run with no overrides:
|
||||
```
|
||||
npx tsx scripts/sim/duel-run.ts --engine duel --workers 4 --mix fast --matches 3000 --label frozen --sha $(git rev-parse --short HEAD)
|
||||
```
|
||||
|
||||
## Results
|
||||
|
||||
### v1 runs: engine-wip 4623930 + duel-cards 067de83 (Doctrines working)
|
||||
Run by ui-duel on inspiron-3670 with this harness (duel-adapter acd2c49/7102239), Node 24, 4 workers, `--mix fast`, 120 decks. Not yet the frozen head; see "Frozen head" below.
|
||||
|
||||
| Run | Overrides | n | First player (sym) | Turns each p10/med/p90 | >20 turns each | Library-out | Loc-heavy | Doc-heavy | Fig-heavy |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| v1-base | `{}` | 3000 | **60.1%** [58–62] | 6 / 8 / 12 | 3.4% | 2.0% | 20.5% | 42.8% | 66.6% |
|
||||
| v1-spc1 | `{"secondPlayerCitations":1}` | 1500 | **54.4%** [52–57] | 6 / 8 / 12 | 3.9% | 2.2% | 20.8% | 45.9% | 63.0% |
|
||||
| v1-extra1 | second seat +1 opening card (sim-only hook) | 1500 | 60.7% [58–63] | 6 / 8 / 12 | 3.6% | 2.3% | 16.8% | 52.9% | 64.7% |
|
||||
| v1-garr15 | derive `garrisonStep` 15 | 1500 | 58.5% [56–61] | 6 / 8 / 14 | 4.5% | 2.3% | 24.9% | 45.3% | 65.3% |
|
||||
| v1-terr3 | `{"territoryCap":3}` | 1500 | 59.7% [57–62] | 6 / 8 / 12 | 3.0% | 1.9% | 21.3% | 49.4% | 64.7% |
|
||||
| v1-cap40 | `{"turnCap":40}` | 1500 | 60.2% [58–63] | 6 / 8 / 12 | 0.0% | 0 (turnCap 3.1%) | 19.8% | 48.3% | 65.9% |
|
||||
| **v1-cand** (3000) | `{"secondPlayerCitations":1,"turnCap":40}` | 3000 | **54.7%** [53–57] | 6 / 8 / 12 | 0.0% | 0 (turnCap 3.9%) | 17.9% | 41.7% | 64.2% |
|
||||
| v1-cand-ld (3000) | v1-cand + every Location "When this enters, draw a card" | 3000 | 58.4% [57–60] | 6 / 8 / 12 | 0.0% | 3.9% (turnCap 0.4%) | 16.5% | 39.0% | 62.5% |
|
||||
| v1-combo | garr15 + `{"secondPlayerCitations":1,"territoryCap":3,"turnCap":40}` | 1500 | **52.8%** [50–55] | 6 / 8 / 13 | 0.0% | 0 (turnCap 4.4%) | 21.3% | 43.0% | 61.8% |
|
||||
|
||||
Card type WR (seat that played it), v1-base → v1-combo: Doctrine 55.8 → 56.4, Event 51.1 → 51.8, Figure 58.8 → 58.4, Institution 53.1 → 52.8, Location 48.1 → 48.0. Est. minutes v1-combo 5.6 / 8.4 / 14.9.
|
||||
|
||||
v1-base other numbers: est. minutes 5.4 / 7.9 / 13.2; Connected 17.2% of pairs, 28.1% of plays (6.96 per game); fame vs card WR r = 0.20 (top vs bottom decile 62.1% vs 53.6%, both above the played-card baseline); card type WR Doctrine 55.8%, Event 51.1%, Location 48.1%.
|
||||
|
||||
### Old-tree sweep (engine 5cd0ffb + duel-cards ae14bc7, Doctrines inert): relative effects only
|
||||
| Run | Overrides | First player | Turns each p10/med/p90 | >20 turns | Loc-heavy | Doc-heavy | Fig-heavy |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| alpha-base (4000) | `{}` | 57.8% [56–59] | 6 / 8 / 21 | 10.3% | 23.2% | 29.5% | 73.1% |
|
||||
| p1draws | `{"firstPlayerDraws":true}` | 59.5% [57–62] | 6 / 8 / 19 | 9.4% | 24 | 27 | 74 |
|
||||
| life24 | `{"startingLife":24}` | 55.0% [52–58] | 6 / 9 / 24 | 12.2% | 21.8% | 29.7% | 72.3% |
|
||||
| life16 | `{"startingLife":16}` | 57.3% [55–60] | 5 / 8 / 16 | 7.7% | 27.9% | 29.1% | 68.2% |
|
||||
| terr3 | `{"territoryCap":3}` | 56.0% [53–59] | 6 / 8 / 18 | 9.3% | 23.9% | 30.2% | 71.1% |
|
||||
| loc2 | `{"locationsPerTurn":2}` | 55.1% [52–58] | 6 / 8 / 20 | 9.8% | 24.4% | 29.1% | 71.1% |
|
||||
| stub1 | `{"stubMax":1}` | 55.0% [52–58] | 6 / 8 / 17 | 7.7% | 20.3% | 30.8% | 68.2% |
|
||||
| reshuffle | `{"libraryEmpty":"reshuffle"}` | stopped after 9 min: games stretch out | | | | | |
|
||||
|
||||
### Baseline, engine alpha (duel-core `engine-wip` 5cd0ffb + duel-cards ae14bc7, merged locally). Not the frozen head.
|
||||
|
||||
> **Superseded:** at duel-cards ae14bc7 Doctrines attached but gave no ±k (fixed in 067de83). Doctrine numbers below are therefore wrong, and everything else is slightly off. See the v1 runs.
|
||||
4000 matches, `--mix fast` (90% heuristic mirrors, 5% heuristic vs random, 5% heuristic vs greedy), 120 decks, 0 engine errors.
|
||||
|
||||
| Metric | Value | Target |
|
||||
|---|---|---|
|
||||
| First-player win rate | **57.8%** [56–59] | 48–52% |
|
||||
| Turns each p10 / median / p90 | 6 / **8** / 21 | 8–12 |
|
||||
| Est. minutes p10 / median / p90 | 5.6 / 8.6 / 20.3 | 8–15 |
|
||||
| Games past 20 turns each | **10.3%** | < 5% |
|
||||
| Library-out losses | 7.2% (70% of the long games) | |
|
||||
| Connected pair rate / fires per play | 17.2% / 28% | 15–30% |
|
||||
| Fame vs card WR within each cost | r = −0.24, −0.65, −0.54, +0.12, −0.14, +0.07 (costs 1–6) | ≈ 0 |
|
||||
| heuristic vs greedy / random | 72.9% / 95.1% | |
|
||||
|
||||
**Findings**
|
||||
1. **First-player edge is tempo.** 68.5% in games under 7 turns each, 57% at 7–9, ~54% in longer games. `firstPlayerDraws: true` raises it to 59.5% (1500 matches), so the edge needs compensation for the second seat, not a draw change.
|
||||
2. **Deck composition dominates.** Win rate vs decks without the tag: Figure-heavy 73%, random 67%, high-curve 46%, Event-heavy 44%, Institution-heavy 37%, low-curve 35%, Doctrine-heavy 30%, Location-heavy **23%**. By card type (seat that played it): Figure 58.8%, Institution 51.3%, Event 50.2%, Doctrine 47.3%, Location 47.1%. Every one of the 8 bottom cards is a Location: past the 2-Territory cap a Location is only a 0/1–0/4 Garrison. Random collections are ~32% Locations (75 of 236), so this matters for real players, who can't choose what they mine.
|
||||
3. **Famous cards are not strictly better.** Within a cost, fame and win rate are uncorrelated or negative (the keyword tax). Cost-6 cards win 61% when played, but that includes a survivorship effect (you only reach 6 Citations in longer games you're still in).
|
||||
4. **Keywords are all net positive.** When played: Featured 67.6%, Multilingual 67.6%, Well-sourced 59.6%, Protected 59.2%, Translated 59.0%, Legacy 58.6%, Stub 58.2%, Local 54.6%, none 48.6%. Featured is the strongest relative to its tax.
|
||||
5. **Long games** are not mainly Location decks: past 20 turns each in 16% of low-curve games, 13% random, 11% Location-heavy, 3% Event-, Institution-heavy and high-curve. Boards stall and decks run out.
|
||||
|
||||
Caveats: the heuristic bot may under-use Doctrines and Events, and may be too cautious to attack into walls (the MC-mirror check was stopped, see below), so the Doctrine/Event numbers and the stall rate are upper bounds on the problem.
|
||||
|
||||
The sweep on r350 was stopped at 23:00 when r350 ran out of memory; ui-duel re-ran it on inspiron (tables above).
|
||||
@@ -0,0 +1,68 @@
|
||||
// DuelSim binding for duel-core's shared/duel engine, with the 236 sample cards derived by duel-cards.
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { DuelCard, DuelEngineApi, DuelRuleset } from '../../shared/duel/index.ts';
|
||||
import { connectedTierOf, duelMetrics, makeDuelAdapter } from '../../shared/bots/duel-adapter.ts';
|
||||
import type { DuelSim } from './duel-sim-types.ts';
|
||||
import type { PoolCard } from './duel-decks.ts';
|
||||
|
||||
export interface DuelPoolCard extends PoolCard { title: string; card: DuelCard }
|
||||
|
||||
const FIXTURE = fileURLToPath(new URL('../../docs/game/duel-card-sample.json', import.meta.url));
|
||||
|
||||
/** The duel engine's functions, whether engine.ts exports them one by one or as an object. */
|
||||
async function loadApi(): Promise<DuelEngineApi> {
|
||||
const mod = '../../shared/duel/engine.ts';
|
||||
const m = await import(mod) as Record<string, any>;
|
||||
const obj = Object.values(m).find(v => v && typeof v === 'object' && typeof v.createDuel === 'function' && typeof v.statsOf === 'function');
|
||||
return (obj ?? m) as DuelEngineApi;
|
||||
}
|
||||
|
||||
async function loadCards(sampleFile: string): Promise<DuelCard[]> {
|
||||
try {
|
||||
const mod = '../../shared/duel/sample.ts';
|
||||
const { deriveSample } = await import(mod) as { deriveSample: (c: unknown[], r?: unknown) => DuelCard[] };
|
||||
const raw = JSON.parse(readFileSync(sampleFile, 'utf8')).cards;
|
||||
// SIM_DERIVE: JSON patch over duel-cards' DERIVE_RULES (data-only derivation tuning).
|
||||
if (!process.env.SIM_DERIVE) return deriveSample(raw);
|
||||
const d = await import('../../shared/duel/derive.ts' as string) as { DERIVE_RULES: Record<string, unknown> };
|
||||
return deriveSample(raw, { ...d.DERIVE_RULES, ...JSON.parse(process.env.SIM_DERIVE) });
|
||||
} catch (e) {
|
||||
if (process.env.SIM_DERIVE || !existsSync(FIXTURE)) throw e;
|
||||
return JSON.parse(readFileSync(FIXTURE, 'utf8')).cards as DuelCard[];
|
||||
}
|
||||
}
|
||||
|
||||
export async function makeDuelSim(sampleFile: string, overrides: Record<string, unknown> = {}): Promise<DuelSim<any, any, DuelPoolCard>> {
|
||||
const api = await loadApi();
|
||||
const rs = await import('../../shared/duel/ruleset.ts') as { mergeDuelRuleset: (o: unknown) => DuelRuleset };
|
||||
const rules = rs.mergeDuelRuleset(overrides);
|
||||
let cards = await loadCards(sampleFile);
|
||||
// SIM_LOCATION_DRAW=n: experiment for duel-design's T2 rider ("When this enters, draw n cards") on every Location.
|
||||
const locDraw = Number(process.env.SIM_LOCATION_DRAW ?? 0);
|
||||
if (locDraw > 0) cards = cards.map(c => (c.type === 'Location' ? { ...c, effects: [...c.effects, { trigger: 'onEnter', op: 'draw', amount: locDraw, target: 'controller' } as DuelCard['effects'][number]] } : c));
|
||||
const pool: DuelPoolCard[] = cards.map(c => ({
|
||||
id: c.cardId, title: c.title, type: c.type, portal: c.portal, cost: c.cost, keywords: [...c.keywords],
|
||||
fame: (c as any).basis?.fame, card: c,
|
||||
}));
|
||||
const engine = makeDuelAdapter(api, { rules, pool: cards });
|
||||
// SIM_SECOND_EXTRA=n: experiment for a proposed ruleset key. The second seat starts with n extra cards
|
||||
// (moved from its library top before mulligans). Sim-only; the engine has no such key yet.
|
||||
const extra = Number(process.env.SIM_SECOND_EXTRA ?? 0);
|
||||
if (extra > 0) {
|
||||
const create = engine.createMatch;
|
||||
engine.createMatch = (r, d, seed) => {
|
||||
const s = create(r, d, seed);
|
||||
const second = (1 - s.firstSeat) as 0 | 1;
|
||||
const p = s.players[second];
|
||||
p.hand.push(...p.library.splice(0, extra));
|
||||
return s;
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: 'duel', engine, lens: engine.lens, pool,
|
||||
deckPayload: cs => cs.map(c => c.card),
|
||||
metrics: duelMetrics,
|
||||
connected: (a, b) => connectedTierOf(a.card, b.card, rules.connectedTiers),
|
||||
};
|
||||
}
|
||||
@@ -55,6 +55,7 @@ export function playDuel<S, A>(sim: DuelSim<S, A>, decks: [SimDeck, SimDeck], bo
|
||||
export const DUEL_MIXES: Record<string, [string, string, number][]> = {
|
||||
default: [['heuristic', 'heuristic', 0.7], ['mc-lite', 'mc-lite', 0.06], ['heuristic', 'mc-lite', 0.08], ['random', 'heuristic', 0.06], ['greedy', 'heuristic', 0.05], ['random', 'random', 0.05]],
|
||||
fast: [['heuristic', 'heuristic', 0.9], ['random', 'heuristic', 0.05], ['greedy', 'heuristic', 0.05]],
|
||||
mirror: [['mc-lite', 'mc-lite', 1]],
|
||||
skill: [['heuristic', 'mc', 0.4], ['random', 'heuristic', 0.2], ['greedy', 'heuristic', 0.2], ['heuristic', 'mc-lite', 0.2]],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// EngineAdapter + DuelLens over duel-core's shared/duel engine (DuelEngineApi, docs/game/DUEL_API.md),
|
||||
// for the duel bots (shared/bots/duel-bots.ts) and the balance sim (scripts/sim/duel-run.ts). Pure, no I/O:
|
||||
// the engine module and the card pool are passed in.
|
||||
import type {
|
||||
CardInstance, ConnectedTier, DuelAction, DuelCard, DuelEngineApi, DuelRuleset, DuelState, Permanent, PlayerView, Seat,
|
||||
} from '../duel/index.ts';
|
||||
import type { EngineAdapter, Rng } from './types.ts';
|
||||
import { duelEvaluate, type DuelLens, type LensAction, type LensCreature } from './duel-bots.ts';
|
||||
|
||||
/** What a duel bot sees: its seat's view, its own decklist (players know their deck) and its legal actions. */
|
||||
export interface DuelObservation { view: PlayerView; deck: DuelCard[]; legal: DuelAction[] }
|
||||
|
||||
const KW_VALUE: Record<string, number> = { Featured: 1, Protected: 0.4, 'Well-sourced': 0.5, Legacy: 0.5, Stub: 0.5, Multilingual: 0.4, Translated: 0.2, Local: 0.2, Trending: 0.3 };
|
||||
|
||||
/** Connected test between two cards (DUEL_API "Connected"), for the pairwise pool rate. */
|
||||
export function connectedTierOf(a: DuelCard, b: DuelCard, tiers: readonly ConnectedTier[]): ConnectedTier | null {
|
||||
if (a.cardId === b.cardId || !a.connect || !b.connect) return null;
|
||||
const meets = <T>(x: readonly T[], y: readonly T[]) => x.some(v => y.includes(v));
|
||||
for (const t of tiers) {
|
||||
if (t === 'Linked' && ((b.pageId !== null && a.connect.links.includes(b.pageId)) || (a.pageId !== null && b.connect.links.includes(a.pageId)))) return t;
|
||||
if (t === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return t;
|
||||
if (t === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return t;
|
||||
if (t === 'Kin' && meets(a.connect.p31.filter(q => q !== 'Q5' && q !== 'Q16521'), b.connect.p31)) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function makeDuelLens(api: DuelEngineApi): DuelLens<DuelState, DuelAction> {
|
||||
const stats = (s: DuelState, p: Permanent) => { try { return api.statsOf(s, p.uid); } catch { return { power: p.card.power ?? 0, toughness: p.card.toughness ?? 0 }; } };
|
||||
const blocker = (p: Permanent) => p.card.type === 'Figure' || (p.card.type === 'Location' && (p.card.toughness ?? 0) > 0);
|
||||
return {
|
||||
phase: s => (s.phase === 'over' ? 'other' : s.phase),
|
||||
life: (s, seat) => s.players[seat].life,
|
||||
handSize: (s, seat) => s.players[seat].hand.length,
|
||||
creatures: (s, seat): LensCreature[] => s.battlefield.filter(p => p.controller === seat && blocker(p)).map(p => {
|
||||
const { power, toughness } = stats(s, p);
|
||||
const left = Math.max(0, toughness - p.damage);
|
||||
const kw = (p.card.keywords ?? []).reduce((t, k) => t + (KW_VALUE[k] ?? 0), 0);
|
||||
const fig = p.card.type === 'Figure';
|
||||
return { uid: p.uid, power, toughness: left, tapped: p.tapped, canAttack: fig && !p.tapped && !p.sick, canBlock: !p.tapped, value: fig ? power + left * 0.8 + 0.5 + kw : left * 0.5 };
|
||||
}),
|
||||
attackers: s => s.combat.attackers,
|
||||
blocks: s => Object.entries(s.combat.blocks) as [string, string][],
|
||||
decode: (s, a): LensAction => {
|
||||
switch (a.type) {
|
||||
case 'play': {
|
||||
const c = s.players[s.active].hand.find(h => h.uid === a.uid)?.card;
|
||||
return { kind: 'play', cost: c?.cost ?? 0, cardType: c?.type ?? '?' };
|
||||
}
|
||||
case 'toggleAttacker': return { kind: 'attack', uid: a.uid, on: true };
|
||||
case 'confirmAttack': return { kind: 'confirmAttack' };
|
||||
case 'block': return { kind: 'block', blocker: a.blocker, attacker: a.attacker };
|
||||
case 'confirmBlocks': return { kind: 'confirmBlocks' };
|
||||
case 'endPhase': return { kind: 'endMain' };
|
||||
case 'keep': return { kind: 'keep' };
|
||||
case 'mulligan': return { kind: 'mulligan' };
|
||||
default: return { kind: 'other' };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function shuffled<T>(xs: T[], rng: Rng): T[] {
|
||||
const a = [...xs];
|
||||
for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
|
||||
return a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild a full DuelState from a seat's observation (a determinization). Hidden zones are sampled:
|
||||
* our library from our decklist minus every card we can see, the opponent's hand and library from `pool`
|
||||
* minus everything visible. Permanent modifiers are recovered exactly from the view's current
|
||||
* power/toughness (whatever statsOf doesn't recompute goes into permPower/permToughness).
|
||||
*/
|
||||
export function stateFromObservation(api: DuelEngineApi, obs: DuelObservation, seat: Seat, rng: Rng, pool: readonly DuelCard[]): DuelState {
|
||||
const v = obs.view, o = (1 - seat) as Seat;
|
||||
const seen = new Set<string>();
|
||||
const mark = (c: DuelCard) => seen.add(c.cardId);
|
||||
v.you.hand.forEach(h => mark(h.card));
|
||||
v.you.graveyard.forEach(g => mark(g.card));
|
||||
v.opponent.graveyard.forEach(g => mark(g.card));
|
||||
v.battlefield.forEach(p => mark(p.card));
|
||||
const ownLeft = shuffled(obs.deck.filter(c => !seen.has(c.cardId) && !v.battlefield.some(p => p.card.cardId === c.cardId && p.owner === seat)), rng);
|
||||
const oppPool = shuffled(pool.filter(c => !seen.has(c.cardId) && !obs.deck.some(d => d.cardId === c.cardId)), rng);
|
||||
let k = 0;
|
||||
const hidden = (owner: Seat, card: DuelCard): CardInstance => ({ uid: `${owner}:h${k++}`, owner, card });
|
||||
const take = (n: number) => Array.from({ length: n }, (_, i) => hidden(o, oppPool[i % Math.max(1, oppPool.length)] ?? obs.deck[0]));
|
||||
const oppHand = take(v.opponent.handSize);
|
||||
const oppLib = Array.from({ length: v.opponent.librarySize }, (_, i) => hidden(o, oppPool[(v.opponent.handSize + i) % Math.max(1, oppPool.length)] ?? obs.deck[0]));
|
||||
const myLib = Array.from({ length: v.you.librarySize }, (_, i) => hidden(seat, ownLeft[i % Math.max(1, ownLeft.length)] ?? obs.deck[0]));
|
||||
const side = (sv: PlayerView['opponent'], hand: CardInstance[], library: CardInstance[]) => {
|
||||
const territory = Math.min(v.rules.territoryCap, v.battlefield.filter(p => p.controller === sv.seat && p.card.type === 'Location').reduce((t, p) => t + (p.card.territory ?? 0), 0));
|
||||
return {
|
||||
life: sv.life, citations: sv.citations, baseCitations: Math.max(0, sv.maxCitations - territory), library, hand, graveyard: sv.graveyard,
|
||||
mulligansTaken: sv.mulligansTaken, ready: sv.ready, locationsThisTurn: 0, bankSeconds: sv.bankSeconds, timeouts: 0, fatigue: 0,
|
||||
};
|
||||
};
|
||||
const players = [] as unknown as DuelState['players'];
|
||||
players[seat] = side(v.you, v.you.hand, myLib);
|
||||
players[o] = side(v.opponent, oppHand, oppLib);
|
||||
// Locations played this turn aren't in the view: if we hold an affordable Location that isn't legal to play, assume one was played.
|
||||
if (v.active === seat && v.phase === 'main') {
|
||||
const legalUids = new Set(obs.legal.flatMap(a => (a.type === 'play' ? [a.uid] : [])));
|
||||
players[seat].locationsThisTurn = v.you.hand.some(h => h.card.type === 'Location' && h.card.cost <= v.you.citations && !legalUids.has(h.uid)) ? 1 : 0;
|
||||
}
|
||||
const battlefield: Permanent[] = v.battlefield.map((p, i) => ({
|
||||
uid: p.uid, owner: p.owner, controller: p.controller, card: p.card, tapped: p.tapped, sick: p.sick, damage: p.damage, counters: p.counters,
|
||||
permPower: 0, permToughness: 0, tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], attachedTo: p.attachedTo,
|
||||
shielded: false, entered: i, connectedLogged: true,
|
||||
}));
|
||||
const s: DuelState = {
|
||||
engine: 'duel', rules: v.rules, seed: 'assumed', rng: Math.floor(rng() * 2 ** 32) >>> 0, turn: v.turn, active: v.active,
|
||||
firstSeat: v.active, phase: v.phase, players, battlefield, combat: structuredClone(v.combat), log: [], result: v.result,
|
||||
version: v.version, nextToken: 100000 + v.version, nextEntry: battlefield.length,
|
||||
};
|
||||
for (const p of battlefield) {
|
||||
const want = v.battlefield.find(x => x.uid === p.uid)!;
|
||||
try {
|
||||
const got = api.statsOf(s, p.uid);
|
||||
p.permPower = want.power - got.power;
|
||||
p.permToughness = want.toughness - got.toughness;
|
||||
} catch { /* keep zero */ }
|
||||
const extra = want.keywords.filter(kw => !(p.card.keywords ?? []).includes(kw));
|
||||
if (extra.length) p.permKeywords = extra;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export interface DuelAdapterOptions { rules: DuelRuleset; pool: readonly DuelCard[] }
|
||||
|
||||
export function makeDuelAdapter(api: DuelEngineApi, opts: DuelAdapterOptions): EngineAdapter<DuelState, DuelAction> & { lens: DuelLens<DuelState, DuelAction> } {
|
||||
const lens = makeDuelLens(api);
|
||||
const decks = new WeakMap<DuelState, [DuelCard[], DuelCard[]]>();
|
||||
const deckOf = new Map<string, [DuelCard[], DuelCard[]]>();
|
||||
const adapter: EngineAdapter<DuelState, DuelAction> & { lens: typeof lens } = {
|
||||
name: 'duel',
|
||||
lens,
|
||||
rulesets: () => [opts.rules.version],
|
||||
decks: () => [],
|
||||
createMatch: (_r, specs, seed) => {
|
||||
const d: [DuelCard[], DuelCard[]] = [specs[0].payload as DuelCard[], specs[1].payload as DuelCard[]];
|
||||
const s = api.createDuel(opts.rules, d, String(seed));
|
||||
decks.set(s, d); deckOf.set(s.seed, d);
|
||||
return s;
|
||||
},
|
||||
toAct: s => api.toAct(s) ?? s.active,
|
||||
legalActions: (s, seat) => api.legalActions(s, seat),
|
||||
applyAction: (s, a) => api.applyAction(s, api.toAct(s) ?? s.active, a),
|
||||
isOver: s => api.isOver(s),
|
||||
result: s => { const r = api.result(s); return { winner: r?.winner ?? null, reason: r?.reason }; },
|
||||
turn: s => s.turn,
|
||||
evaluate: (s, seat) => duelEvaluate(lens, s, seat),
|
||||
cardsOf: (s, a) => (a.type === 'play' ? [s.players[api.toAct(s) ?? s.active].hand.find(h => h.uid === a.uid)?.card.cardId ?? a.uid] : []),
|
||||
actionKind: a => a.type,
|
||||
firstSeat: s => s.firstSeat,
|
||||
observe: (s, seat): DuelObservation => ({ view: api.viewFor(s, seat), deck: (deckOf.get(s.seed) ?? decks.get(s) ?? [[], []])[seat], legal: api.legalActions(s, seat) }),
|
||||
assume: (obs, seat, rng) => stateFromObservation(api, obs as DuelObservation, seat, rng, opts.pool),
|
||||
};
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/** Per-match numbers from the omniscient log, for DUEL_BALANCE.md. */
|
||||
export function duelMetrics(s: DuelState): Record<string, number> {
|
||||
const m: Record<string, number> = { connectedFires: 0, plays: 0, rivalries: 0, destroyed: 0, mulligans: 0, tokens: 0, discards: 0 };
|
||||
for (const e of s.log) {
|
||||
if (e.kind === 'connected') m.connectedFires++;
|
||||
else if (e.kind === 'deploy' || e.kind === 'cast' || e.kind === 'adopt') m.plays++;
|
||||
else if (e.kind === 'rivalry') m.rivalries++;
|
||||
else if (e.kind === 'destroyed') m.destroyed++;
|
||||
else if (e.kind === 'mulligan') m.mulligans++;
|
||||
else if (e.kind === 'tokenCreated') m.tokens++;
|
||||
else if (e.kind === 'discard') m.discards++;
|
||||
}
|
||||
m.lifeLeft = s.result?.winner != null ? s.players[s.result.winner].life : 0;
|
||||
return m;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { mulberry32 } from '../shared/bots/index.ts';
|
||||
import { makeDuelBot, DUEL_BOT_NAMES } from '../shared/bots/duel-bots.ts';
|
||||
import { deckSet } from '../scripts/sim/duel-decks.ts';
|
||||
import { playDuel } from '../scripts/sim/duel-run.ts';
|
||||
|
||||
const hasEngine = existsSync(new URL('../shared/duel/engine.ts', import.meta.url));
|
||||
const SAMPLE = fileURLToPath(new URL('../docs/game/card-sample.json', import.meta.url));
|
||||
|
||||
test('duel adapter: bots play legal actions on shared/duel and matches end', { skip: !hasEngine && 'shared/duel/engine.ts not merged yet' }, async () => {
|
||||
const { makeDuelSim } = await import('../scripts/sim/duel-core-sim.ts');
|
||||
const sim = await makeDuelSim(SAMPLE);
|
||||
const decks = deckSet(sim.pool, 4, 3);
|
||||
assert.equal(decks[0].cards.length, 40);
|
||||
for (const name of DUEL_BOT_NAMES) {
|
||||
const bot = makeDuelBot(name, sim.engine, sim.lens);
|
||||
let s = sim.engine.createMatch('duel', [{ id: 'a', tags: [], payload: sim.deckPayload(decks[0].cards) }, { id: 'b', tags: [], payload: sim.deckPayload(decks[1].cards) }], 9);
|
||||
const rng = mulberry32(4);
|
||||
for (let i = 0; i < (name.startsWith('mc') ? 150 : 1500) && !sim.engine.isOver(s); i++) {
|
||||
const seat = sim.engine.toAct(s);
|
||||
const legal = sim.engine.legalActions(s, seat);
|
||||
const a = bot(sim.engine.observe!(s, seat), seat, rng);
|
||||
assert.ok(legal.some(x => JSON.stringify(x) === JSON.stringify(a)), `${name} chose an illegal action`);
|
||||
s = sim.engine.applyAction(s, a);
|
||||
}
|
||||
}
|
||||
const r1 = playDuel(sim, [decks[2], decks[3]], ['heuristic', 'heuristic'], 21);
|
||||
const r2 = playDuel(sim, [decks[2], decks[3]], ['heuristic', 'heuristic'], 21);
|
||||
assert.equal(r1.truncated, false);
|
||||
assert.deepEqual({ ...r1, ms: 0 }, { ...r2, ms: 0 });
|
||||
});
|
||||
|
||||
test('duel adapter: determinization keeps the visible state and the view', { skip: !hasEngine && 'shared/duel/engine.ts not merged yet' }, async () => {
|
||||
const { makeDuelSim } = await import('../scripts/sim/duel-core-sim.ts');
|
||||
const sim = await makeDuelSim(SAMPLE);
|
||||
const decks = deckSet(sim.pool, 2, 8);
|
||||
let s = sim.engine.createMatch('duel', [{ id: 'a', tags: [], payload: sim.deckPayload(decks[0].cards) }, { id: 'b', tags: [], payload: sim.deckPayload(decks[1].cards) }], 5);
|
||||
const bot = makeDuelBot('heuristic', sim.engine, sim.lens);
|
||||
const rng = mulberry32(1);
|
||||
for (let i = 0; i < 120 && !sim.engine.isOver(s); i++) { const seat = sim.engine.toAct(s); s = sim.engine.applyAction(s, bot(sim.engine.observe!(s, seat), seat, rng)); }
|
||||
const seat = sim.engine.toAct(s);
|
||||
const obs = sim.engine.observe!(s, seat) as any;
|
||||
const guess = sim.engine.assume!(obs, seat, rng) as any;
|
||||
assert.equal(guess.players[seat].hand.length, s.players[seat].hand.length);
|
||||
assert.equal(guess.players[1 - seat].hand.length, s.players[1 - seat].hand.length);
|
||||
assert.equal(guess.players[seat].library.length, s.players[seat].library.length);
|
||||
assert.equal(sim.engine.evaluate(guess, seat).toFixed(6), sim.engine.evaluate(s, seat).toFixed(6), 'material eval sees only public info');
|
||||
});
|
||||
Reference in New Issue
Block a user