Preview combat odds with isolated engine simulations

This commit is contained in:
coyotte508 2026-10-18 14:09:31 +02:00
commit 0a42937aa2
15 changed files with 774 additions and 6 deletions

View file

@ -354,7 +354,9 @@ fn attacker_wins(game: &mut Game, mut c: Combat) {
c.defender_position(),
None,
);
capture_position(game, &mut c.stats);
if game.context != crate::game::GameContext::CombatPreview {
capture_position(game, &mut c.stats);
}
end_combat_and_store_stats(game, CombatEnd::new(CombatResult::AttackerWins, c));
}
@ -419,7 +421,9 @@ fn restrict_defenders_after_battle(game: &mut Game, s: &CombatStats) {
pub(crate) fn end_combat(game: &mut Game, s: CombatStats) {
current_action_log_mut(game).combat_stats = Some(s.clone());
on_end_combat(game, s);
if game.context != crate::game::GameContext::CombatPreview {
on_end_combat(game, s);
}
}
pub(crate) fn on_end_combat(game: &mut Game, stats: CombatStats) {

View file

@ -121,6 +121,7 @@ impl GameOptions {
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum GameContext {
CombatPreview,
Play,
AI,
Replay,

View file

@ -23,6 +23,7 @@ use crate::victory_points::victory_points_parts;
use crate::wonder::Wonder;
use serde_json::{Value, json};
mod actions;
mod combat_estimate;
mod collection_potential;
mod decisions;
mod effects;
@ -36,6 +37,7 @@ pub fn query(game: &Game, seat: usize, input: Value) -> Result<Value, String> {
return Err("Choose a player".into());
}
match input["kind"].as_str() {
Some("combatEstimate") => combat_estimate::estimate(game, seat, &input),
Some("decision") => decisions::preview(game, seat, &input),
Some("researchPlan") => research_plan(game, seat, &input),
Some("movement") if input["city"].is_string() => actions::nomad_movement(

View file

@ -0,0 +1,201 @@
//! Run the real combat rules on disposable copies, with a separate random stream.
//! Unknown mandatory choices fail closed rather than producing misleading odds.
use crate::action::{Action, execute_without_undo};
use crate::combat_listeners::CombatResult;
use crate::content::persistent_events::{
EventResponse, PersistentEventRequest as Request, PersistentEventType,
};
use crate::game::{Game, GameContext};
use crate::log::current_turn_log;
use crate::movement::MovementAction;
use crate::resource_pile::ResourcePile;
use crate::unit::UnitType;
use crate::utils::Rng;
use serde_json::{Value, json};
pub(super) fn estimate(game: &Game, seat: usize, input: &Value) -> Result<Value, String> {
let mut visible = crate::game_api::strip_secret(game.clone(), Some(seat));
// Replay frames have no rules effect and can dominate late-game copy costs.
visible.board_history = Default::default();
let game = &visible;
let action: Action =
serde_json::from_value(input["action"].clone()).map_err(|e| e.to_string())?;
if seat != game.active_player() {
return Err("Not your decision".into());
}
match &action {
Action::Movement(MovementAction::Move(m)) => {
let legal = super::actions::movement(game, seat, m.units.clone())?;
if !legal["destinations"].as_array().is_some_and(|ds| {
ds.iter()
.any(|d| d["attack"] == true && d["action"] == input["action"])
}) {
return Err("Choose a legal attack".into());
}
}
Action::Response(_)
if game.events.iter().any(|e| {
matches!(
e.event_type,
PersistentEventType::CombatStart(_) | PersistentEventType::CombatRoundStart(_)
)
}) =>
{
()
}
_ => return Err("Choose an attack or combat option".into()),
}
let count = input["samples"].as_u64().unwrap_or(32).clamp(1, 64);
let offset = input["offset"].as_u64().unwrap_or(0).min(100_000);
let siege = input["siege"].as_u64().unwrap_or(0).min(3);
let steel = input["steel"].as_bool().unwrap_or(true);
let mut wins = 0;
let mut draws = 0;
let mut losses = 0;
let mut own_losses = 0;
let mut enemy_losses = 0;
let mut cost = ResourcePile::empty();
for sample in offset..offset + count {
let mut sim = game.clone();
sim.context = GameContext::CombatPreview;
// Never use the live seed, queued test dice, or future dice log.
sim.rng = Rng::from_seed(0x636c6173685f6f646473_u128.wrapping_mul(u128::from(sample) + 1));
for _ in 0..8 {
sim.rng.next_seed();
}
sim.dice_roll_outcomes.clear();
sim.dice_roll_log.clear();
// Hidden hand slots are sentinel IDs, not playable cards. Never inspect them.
for player in &mut sim.players {
player.action_cards.retain(|id| *id != 0);
}
for event in &mut sim.events {
if let PersistentEventType::CombatRoundStart(round) = &mut event.event_type {
if round.attacker_strength.tactics_card == Some(0) {
round.attacker_strength.tactics_card = None;
}
if round.defender_strength.tactics_card == Some(0) {
round.defender_strength.tactics_card = None;
}
}
}
let start = sim.log_index;
execute_without_undo(&mut sim, action.clone(), seat)?;
let mut result = None;
let mut paid = ResourcePile::empty();
let mut used_siege = 0;
for _ in 0..256 {
if let Some(stats) = current_turn_log(&sim)
.actions
.iter()
.skip(start)
.find_map(|a| a.combat_stats.as_ref())
{
result = Some(stats.clone());
break;
}
let event = sim.events.last().ok_or("No battle to estimate")?;
if matches!(event.event_type, PersistentEventType::CombatEnd(_)) {
return Err("Battle already ended".into());
}
let who = sim.active_player();
let handler = event
.player
.handler
.as_ref()
.ok_or("Unsupported combat choice")?;
let name = handler.origin.name(&sim);
let response = match &handler.request {
Request::Payment(fields) => {
let mut available = sim.player(who).resources.clone();
let mut payments = vec![];
for (i, field) in fields.iter().enumerate() {
let use_it = !field.optional
|| (name == "Steel Weapons" && (who != seat || steel))
|| (name == "Siegecraft" && who == seat && siege & (1 << i) != 0);
let payment = if use_it {
match field.cost.first_valid_payment(&available) {
Some(p) => p,
None if name == "Siegecraft" && who == seat => {
return Err("Cannot afford this Siegecraft combination".into());
}
None if field.optional => ResourcePile::empty(),
None => return Err("Cannot pay combat cost".into()),
}
} else {
ResourcePile::empty()
};
if name == "Siegecraft" && who == seat && !payment.is_empty() {
used_siege |= 1 << i;
}
available -= payment.clone();
if who == seat && (name == "Steel Weapons" || name == "Siegecraft") {
paid += payment.clone();
}
payments.push(payment);
}
EventResponse::Payment(payments)
}
Request::SelectHandCards(r) if *r.needed.start() == 0 => {
EventResponse::SelectHandCards(vec![])
}
Request::BoolRequest(_) => EventResponse::Bool(false),
Request::SelectUnits(r)
if name == "Choose Casualties"
|| name == "Choose Casualties (carried units)" =>
{
let mut units = r.request.choices.clone();
// Preserve leaders and expensive units. This is a policy, not optimal play.
units.sort_by_key(|id| match sim.player(r.player).get_unit(*id).unit_type {
UnitType::Settler => 0,
UnitType::Infantry | UnitType::Ship => 1,
UnitType::Cavalry => 2,
UnitType::Elephant => 3,
UnitType::Leader(_) => 4,
});
units.truncate(*r.request.needed.start() as usize);
EventResponse::SelectUnits(units)
}
_ => return Err(format!("Estimate unavailable for {name}")),
};
execute_without_undo(&mut sim, Action::Response(response), who)?;
}
let stats = result.ok_or("Combat simulation limit reached")?;
if used_siege != siege {
return Err("Cannot afford this Siegecraft combination".into());
}
let own_attacks = stats.attacker.player == seat;
match stats.result {
Some(CombatResult::Draw) => draws += 1,
Some(CombatResult::AttackerWins) if own_attacks => wins += 1,
Some(CombatResult::DefenderWins) if !own_attacks => wins += 1,
Some(_) => losses += 1,
None => return Err("Battle did not finish".into()),
}
// Stats omit some automatic passenger losses when the last ship sinks.
// Count actual removed unit IDs instead, starting at this decision.
let enemy = if own_attacks {
stats.defender.player
} else {
stats.attacker.player
};
let removed = |player: usize| -> u64 {
game.player(player)
.units
.iter()
.filter(|unit| {
!sim.player(player)
.units
.iter()
.any(|remaining| remaining.id == unit.id)
})
.count() as u64
};
own_losses += removed(seat);
enemy_losses += removed(enemy);
cost = paid;
}
Ok(
json!({"samples":count,"wins":wins,"draws":draws,"losses":losses,"ownLosses":own_losses,"enemyLosses":enemy_losses,"cost":cost}),
)
}

View file

@ -399,3 +399,5 @@ Viewer 0.1.141 adds arrows from sea spaces to every adjacent unexplored hex in t
Viewer 0.1.142 / engine 0.4.99 removes claimed Great People from the Event discard and excludes Great People in the Action discard from Event reshuffles. Existing saved games are not migrated.
Viewer 0.1.143 uses printed card names in waiting-status labels, matching event popups (for example Major Earthquake).
Viewer 0.1.144 / engine 0.4.100 adds combat estimates to attack confirmation and selected tactics, Siegecraft and Steel Weapons choices. An isolated worker runs 2,048 battles with the real engine, an independent random stream, public information only, and explicit no-retreat / no-additional-tactics and casualty assumptions. Attack previews compare affordable Siegecraft options and declining Steel Weapons. Unsupported decisions show no estimate. Results are cached, selection changes cancel old workers, and simulations stop before capture rewards.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.143",
"version": "0.1.144",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.143",
"version": "0.1.144",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.143",
"version": "0.1.144",
"private": true,
"type": "module",
"scripts": {

View file

@ -0,0 +1,109 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { createRequire } from 'node:module';
import { chromium } from 'playwright';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'estimate-ui', {})).players.slice(2);
function withNpcs(game) {
for (const npc of npcs)
if (!game.players.some((p) => p.civilization === npc.civilization))
game.players.push({ ...npc, id: game.players.length });
return game;
}
const game = JSON.parse(
await readFile(
new URL('../../server/tests/test_games/combat/direct_capture_city_metallurgy.json', import.meta.url),
'utf8',
),
);
withNpcs(game);
game.players[0].advances = game.players[0].advances.filter((a) => a !== 'Metallurgy');
const pending = engine.tryMove(
JSON.stringify(game),
JSON.stringify({ Movement: { Move: { units: [0, 1, 2, 3], destination: 'C1', payment: {} } } }),
0,
);
const state = engine.stripSecret(pending, 0);
const server = createServer(async (req, res) => {
if (req.url === '/')
return res.end(
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>',
);
if (!['/viewer.js', '/server_bg.wasm'].includes(req.url)) return res.writeHead(404).end();
res.setHeader('Content-Type', req.url.endsWith('.wasm') ? 'application/wasm' : 'text/javascript');
res.end(await readFile(new URL('../dist' + req.url, import.meta.url)));
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const width of [1400, 390]) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto('http://127.0.0.1:' + server.address().port);
await page.evaluate((state) => {
window.sent = [];
window.host = clash3d.launch('#app');
host.on('move', (a) => window.sent.push(a));
host.emit('player', { index: 0 });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false });
host.emit('state', state);
}, state);
const panel = page.getByRole('region', { name: 'Steel Weapons', exact: true });
await panel.waitFor();
await panel.locator('.estimate-summary').waitFor({ timeout: 60000 });
await panel.getByRole('button', { name: 'Assumptions & options', exact: false }).click();
await panel.getByText('2048 simulations', { exact: false }).waitFor({ timeout: 60000 });
assert.match(await panel.innerText(), /Win ≈\d+%/);
assert.equal(await page.evaluate(() => window.sent.length), 0, 'estimating must never submit a move');
assert.ok(await panel.evaluate((el) => el.scrollWidth <= el.clientWidth + 1));
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert.deepEqual(errors, []);
await page.screenshot({ path: `/tmp/combat-estimate-${width}.png` });
const attackState = engine.stripSecret(
JSON.stringify(
withNpcs(
JSON.parse(
await readFile(
new URL('../../server/tests/test_games/combat/combat_all_modifiers.json', import.meta.url),
'utf8',
),
),
),
),
0,
);
await page.reload();
await page.evaluate((state) => {
window.sent = [];
window.host = clash3d.launch('#app');
host.on('move', (a) => window.sent.push(a));
host.emit('player', { index: 0 });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false });
host.emit('state', state);
}, attackState);
await page.getByRole('button', { name: 'Move units and found cities' }).click();
const target = page.locator('.map-hit-target[data-position="C1"]');
await target.focus();
await target.press('Enter');
const attackPanel = page.getByRole('region', { name: 'Unit movement' });
await attackPanel.locator('.estimate-summary').waitFor({ timeout: 60000 });
await attackPanel.getByRole('button', { name: 'Assumptions & options', exact: false }).click();
await attackPanel.getByText('2048 simulations', { exact: false }).waitFor({ timeout: 60000 });
assert.match(await attackPanel.innerText(), /Cancel both/);
assert.equal(await page.evaluate(() => window.sent.length), 0);
assert.deepEqual(errors, []);
await page.screenshot({ path: `/tmp/combat-attack-estimate-${width}.png` });
console.log('Combat estimate UI passed:', width);
await page.close();
}
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -0,0 +1,189 @@
<script lang="ts">
import EstimateWorker from './combat-estimate.worker?worker&inline';
import wasm from '../.bridge/server_bg.wasm?url&no-inline';
import type { Controller } from './controller';
import type { Move } from './types';
import {
cachedEstimate,
cacheEstimate,
percentages,
type CombatEstimate,
type CombatScenario,
} from './combat-estimate';
import ResourceAmount from './ResourceAmount.svelte';
let {
controller,
action,
siege = false,
steel = false,
}: { controller: Controller; action: Move; siege?: boolean; steel?: boolean } = $props();
const session = $derived(controller.session);
let results = $state<(CombatEstimate | undefined)[]>([]);
let errors = $state<(string | undefined)[]>([]);
let done = $state(false);
let expanded = $state(false);
const scenarios = $derived<CombatScenario[]>([
{ label: siege ? 'No Siegecraft' : 'Battle estimate', siege: 0, steel: true },
...(steel ? [{ label: 'Without your Steel Weapons', siege: 0, steel: false }] : []),
...(siege
? [
{ label: 'Cancel extra die', siege: 1, steel: true },
{ label: 'Cancel ignored hit', siege: 2, steel: true },
{ label: 'Cancel both', siege: 3, steel: true },
]
: []),
]);
$effect(() => {
// Subscribe to game replacements as well as selection changes; never show stale odds.
const game = $session.game;
const currentAction = action;
const variants = scenarios;
results = [];
errors = [];
done = false;
if (!game || $session.playback || $session.pending) return;
const snapshot = controller.combatEstimateSnapshot();
if (!snapshot) return;
const key = JSON.stringify([snapshot.raw, snapshot.seat, currentAction, variants]);
const cached = cachedEstimate(key);
if (cached) {
results = cached.results;
errors = cached.errors;
done = true;
return;
}
let worker: Worker | undefined;
const timer = setTimeout(() => {
try { worker = new EstimateWorker(); }
catch { errors = ['Background simulation is unavailable in this browser.']; done = true; return; }
worker.onmessage = ({ data }) => {
results = data.results ?? [];
errors = data.errors ?? [data.error];
done = data.done;
if (data.done) {
cacheEstimate(key, { results: data.results ?? [], errors: data.errors ?? [data.error] });
worker?.terminate();
}
};
worker.onerror = () => {
results = [];
errors = ['Estimate unavailable'];
done = true;
worker?.terminate();
};
worker.postMessage({
...snapshot,
action: currentAction,
scenarios: variants,
wasm: new URL(wasm, location.href).href,
});
}, 200);
return () => {
clearTimeout(timer);
worker?.terminate();
};
});
</script>
<div class="combat-estimate" aria-label="Estimated combat outcome">
{#if results[0] && results[0].samples >= 256}
{@const odds = percentages(results[0])}
<div class="estimate-summary">
<strong>Win ≈{odds[0]}%</strong><span>Draw {odds[1]}%</span><span>Loss {odds[2]}%</span>
</div>
<div class="estimate-losses">No retreat or additional tactics</div>
<div class="estimate-losses">
Average losses: you {(results[0].ownLosses / results[0].samples).toFixed(1)} · enemy {(
results[0].enemyLosses / results[0].samples
).toFixed(1)}
</div>
{:else if done}<span class="estimate-losses" title={errors[0]}
>{errors[0] === 'No battle to estimate'
? 'Undefended capture · no battle'
: 'Estimate unavailable for this battle.'}</span
>
{:else}<span class="estimate-losses">Estimating battle…</span>{/if}
<button class="estimate-details" onclick={() => (expanded = !expanded)} aria-expanded={expanded}
>{expanded ? 'Hide' : 'Assumptions & options'}{!done && (results[0]?.samples ?? 0) >= 256
? ' · refining…'
: ''}</button
>
{#if expanded}
{#if errors[0]}<p>{errors[0]}</p>{/if}
<p>
Selected option included. No retreat or additional tactics; hidden tactics ignored. Steel Weapons when
affordable. Other optional abilities declined. Infantry lost before cavalry, elephants and leaders.
</p>
{#if scenarios.length > 1}
<div class="estimate-options">
{#each scenarios as scenario, i}
<div class="estimate-option">
<span>{scenario.label}</span>
{#if results[i] && results[i]!.samples >= 256}<strong>≈{percentages(results[i]!)[0]}% win</strong
>{#if Object.values(results[i]!.cost).some(Boolean)}<ResourceAmount
pile={results[i]!.cost}
/>{:else}<span>Free</span>{/if}
{:else if errors[i]}<small title={errors[i]}>Unavailable</small>{:else}<small>Calculating…</small
>{/if}
</div>
{/each}
</div>
<p>Costs shown are Steel Weapons and Siegecraft payments. Comparisons do not select or spend them.</p>
{/if}
<p>
{results[0]?.samples ?? 0} simulations{done ? '' : ' · refining'} · Estimates depend on choices; losses from
this choice include passengers.
</p>
{/if}
</div>
<style>
.combat-estimate {
border-top: 1px solid var(--line);
padding-top: 0.6rem;
margin-top: 0.6rem;
font-size: 12px;
}
.estimate-summary {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 0.45rem 1rem;
}
.estimate-summary strong {
color: var(--text);
font-size: 14px;
}
.estimate-losses,
p {
color: var(--muted);
font-size: 11px;
margin: 0.35rem 0;
}
.estimate-details {
background: none;
border: 0;
padding: 0.2rem 0;
color: var(--muted);
font-size: 11px;
text-decoration: underline;
}
.estimate-options {
display: grid;
gap: 0.4rem;
margin: 0.5rem 0;
}
.estimate-option {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.35rem 0.65rem;
}
.estimate-option > span:first-child {
flex: 1;
min-width: 140px;
}
.estimate-option small {
color: var(--muted);
}
</style>

View file

@ -1,4 +1,5 @@
<script lang="ts">
import CombatEstimate from './CombatEstimate.svelte';
import { printedCardName } from './card-names';
import { onDestroy } from 'svelte';
import { untrack } from 'svelte';
@ -356,7 +357,7 @@
options={directPayments.map((choice) => ({ payment: choice.payment, disabled: !choice.action }))}
value={payments[0]}
onChange={(payment) => choosePayment(0, payment)}
onPay={(payment) => {
onPay={decision.name === 'Steel Weapons' ? undefined : (payment) => {
const action = directPayments.find((choice) => samePayment(choice.payment, payment))?.action;
if (action) controller.submit(action);
}}
@ -367,6 +368,10 @@
label={field.name}
/>
{/if}
{#if decision.name === 'Steel Weapons' && preview.action}
<CombatEstimate {controller} action={preview.action} />
<button class="primary wide" disabled={$session.pending} onclick={() => preview.action && controller.submit(preview.action)}>Confirm<Check size={16} /></button>
{/if}
{:else}
{#each decision.fields as field, i}
<div class="decision-payment">
@ -427,6 +432,9 @@
Keep all cities; skip this step in future ages
</label>
{/if}
{#if (decision.tacticsSelection || decision.name === 'Siegecraft') && preview.action}
<CombatEstimate {controller} action={preview.action} />
{/if}
<div class="decision-footer" class:map-decision-footer={mapChoice}>
{#if decision.tacticsSelection}
{#if selected.length}<small class="tactics-discard">Discards the selected card</small>{/if}

View file

@ -1,4 +1,5 @@
<script lang="ts">
import CombatEstimate from './CombatEstimate.svelte';
import { onDestroy } from 'svelte';
import {
Footprints,
@ -47,6 +48,13 @@
const destination = $derived(
$session.moveDestination === null ? null : $session.moveDestinations[$session.moveDestination],
);
const ownAdvances = $derived($session.view?.players.find(p => p.index === $session.seat)?.advances ?? []);
const defender = $derived($session.game?.players.find(p => p.id !== $session.seat && (
p.units?.some(u => u.position === destination?.position) || p.cities?.some(c => c.position === destination?.position)
)));
const canDeclineSteel = $derived(destination?.terrain !== 'Water' && ownAdvances.some(a => a.id === 'SteelWeapons') && (
!ownAdvances.some(a => a.id === 'Metallurgy') || !!$session.view?.players.find(p => p.index === defender?.id)?.advances.some(a => a.id === 'SteelWeapons')
));
const settler = $derived.by(() => {
const here = $session.view?.settlers.filter((u) => u.position === origin) ?? [];
return (
@ -210,6 +218,9 @@
{/if}
{#if destination?.attack}
<div class="movement-leader-info" aria-label="Attack preview">
<CombatEstimate {controller} action={destination.action}
siege={!!$session.view?.players.find(p => p.index === $session.seat)?.advances.some(a => a.id === 'Siegecraft') && !!$session.game?.players.some(p => p.cities?.some(c => c.position === destination.position && c.city_pieces?.fortress != null))}
steel={canDeclineSteel} />
<h3><Swords size={16} />Defenders</h3>
<TileUnits players={$session.game?.players ?? []} position={destination.position} />
{#each $session.game?.players ?? [] as player}

View file

@ -0,0 +1,136 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { addEstimate, percentages } from './combat-estimate.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
function fixture(name: string) {
return readFileSync(new URL(`../../server/tests/test_games/combat/${name}.json`, import.meta.url), 'utf8');
}
function attack(raw: string, units: number[], destination: string) {
const choices = JSON.parse(
engine.webQuery(raw, 0, JSON.stringify({ kind: 'movement', units })),
).destinations;
return choices.find((d: any) => d.position === destination && d.attack).action;
}
function estimate(raw: string, action: unknown, extra: object = {}) {
return JSON.parse(
engine.webQuery(raw, 0, JSON.stringify({ kind: 'combatEstimate', action, samples: 64, ...extra })),
);
}
test('simulation is deterministic, independent of live dice and never changes the state', () => {
const raw = engine.stripSecret(fixture('direct_capture_city_metallurgy'), 0);
const action = attack(raw, [0, 1, 2, 3], 'C1');
const before = engine.tryMove(raw, JSON.stringify(action), 0);
const result = estimate(raw, action);
assert.equal(result.wins + result.draws + result.losses, 64);
assert.ok(result.wins > 50);
assert.deepEqual(estimate(raw, action), result);
assert.equal(engine.tryMove(raw, JSON.stringify(action), 0), before);
const changed = JSON.parse(raw);
changed.seed = '999';
changed.dice_roll_outcomes = [0, 0, 0, 0];
changed.dice_roll_log = [11, 11];
assert.deepEqual(estimate(JSON.stringify(changed), action), result);
});
test('Siegecraft alternatives run full combat on filtered hands and account for both costs', () => {
const raw = engine.stripSecret(fixture('combat_all_modifiers'), 0);
const action = attack(raw, [0, 1, 2, 3, 4, 5], 'C1');
const base = estimate(raw, action);
const both = estimate(raw, action, { siege: 3 });
assert.equal(base.samples, 64);
assert.equal(both.samples, 64);
assert.ok(Object.values(both.cost).reduce((a: number, b: any) => a + b, 0) >= 4);
});
test('naval estimates handle passengers and do not use them as fighting dice', () => {
const loaded = JSON.parse(engine.stripSecret(fixture('ship_combat'), 0));
loaded.players[1].units[0].carried_units = [
{ id: 2, unit_type: 'Infantry' },
{ id: 3, unit_type: 'Infantry' },
];
const raw = JSON.stringify(loaded);
const action = attack(raw, [7, 8], 'D2');
const result = estimate(raw, action);
assert.equal(result.wins + result.draws + result.losses, 64);
const bare = JSON.parse(raw);
for (const p of bare.players) {
p.units = (p.units ?? []).filter((u: any) => u.carrier_id == null);
for (const u of p.units) delete u.carried_units;
}
const without = estimate(JSON.stringify(bare), action);
assert.deepEqual([result.wins, result.draws, result.losses], [without.wins, without.draws, without.losses]);
assert.ok(result.ownLosses > without.ownLosses);
assert.ok(result.enemyLosses > without.enemyLosses);
});
test('batch totals and displayed percentages preserve all outcomes', () => {
const e = { samples: 3, wins: 1, draws: 1, losses: 1, ownLosses: 4, enemyLosses: 2, cost: {} };
assert.equal(
percentages(e).reduce((a, b) => a + b),
100,
);
assert.deepEqual(addEstimate(e, e), {
...e,
samples: 6,
wins: 2,
draws: 2,
losses: 2,
ownLosses: 8,
enemyLosses: 4,
});
});
test('one ship against one ship agrees with exact 40/20/40 odds', () => {
const game = JSON.parse(fixture('ship_combat'));
for (const p of game.players) {
p.advances = ['Farming', 'Tactics'];
p.special_advances = [];
p.units = (p.units ?? []).filter((u: any) => u.unit_type === 'Ship').slice(0, 1);
}
game.state = 'Playing';
game.events = [];
game.actions_left = 3;
for (const p of game.players) for (const u of p.units) u.movement_restrictions = [];
const raw = engine.stripSecret(JSON.stringify(game), 0);
const units = game.players[0].units.map((u: any) => u.id);
const action = attack(raw, units, 'D2');
let total;
for (let offset = 0; offset < 2048; offset += 64)
total = addEstimate(total, estimate(raw, action, { offset }));
assert.ok(Math.abs(total!.wins / 2048 - 0.4) < 0.04, JSON.stringify(total));
assert.ok(Math.abs(total!.draws / 2048 - 0.2) < 0.04, JSON.stringify(total));
assert.ok(Math.abs(total!.losses / 2048 - 0.4) < 0.04, JSON.stringify(total));
});
test('full and filtered states produce identical odds without reading hidden opponent cards', () => {
const raw = fixture('combat_all_modifiers');
const visible = engine.stripSecret(raw, 0);
const action = attack(visible, [0, 1, 2, 3, 4, 5], 'C1');
assert.deepEqual(estimate(raw, action), estimate(visible, action));
});
test('selected Steel Weapons and tactics responses are simulated before confirming', () => {
let raw = fixture('combat_all_modifiers');
raw = engine.tryMove(raw, JSON.stringify(attack(raw, [0, 1, 2, 3, 4, 5], 'C1')), 0);
const paid = { Response: { Payment: [{ ore: 1 }] } };
const skipped = { Response: { Payment: [{}] } };
const withSteel = estimate(engine.stripSecret(raw, 0), paid);
const withoutSteel = estimate(engine.stripSecret(raw, 0), skipped);
assert.notDeepEqual(withSteel, withoutSteel);
raw = engine.tryMove(raw, JSON.stringify(paid), 0);
raw = engine.tryMove(raw, JSON.stringify({ Response: { Payment: [{}, {}] } }), 0);
raw = engine.tryMove(raw, JSON.stringify(paid), 1);
const visible = engine.stripSecret(raw, 0);
const withTactic = estimate(visible, { Response: { SelectHandCards: [{ ActionCard: 1 }] } });
const withoutTactic = estimate(visible, { Response: { SelectHandCards: [] } });
assert.equal(withTactic.samples, 64);
assert.notDeepEqual(withTactic, withoutTactic);
});
test('unaffordable Siegecraft is unavailable, never presented as a free cancellation', () => {
const game = JSON.parse(fixture('combat_all_modifiers'));
game.players[0].resources = {};
const raw = engine.stripSecret(JSON.stringify(game), 0);
const action = attack(raw, [0, 1, 2, 3, 4, 5], 'C1');
assert.equal(estimate(raw, action).samples, 64);
assert.throws(() => estimate(raw, action, { siege: 3 }), /Cannot afford/);
});

View file

@ -0,0 +1,51 @@
import type { Pile } from './types.ts';
export interface CombatEstimate {
samples: number;
wins: number;
draws: number;
losses: number;
ownLosses: number;
enemyLosses: number;
cost: Pile;
}
export interface CombatScenario {
label: string;
siege: number;
steel: boolean;
}
export function addEstimate(a: CombatEstimate | undefined, b: CombatEstimate): CombatEstimate {
if (!a) return b;
return {
samples: a.samples + b.samples,
wins: a.wins + b.wins,
draws: a.draws + b.draws,
losses: a.losses + b.losses,
ownLosses: a.ownLosses + b.ownLosses,
enemyLosses: a.enemyLosses + b.enemyLosses,
cost: b.cost,
};
}
export function percentages(e: CombatEstimate): number[] {
const values = [e.wins, e.draws, e.losses].map((n) => (n * 100) / e.samples);
const rounded = values.map(Math.floor);
const order = values
.map((n, i) => ({ i, fraction: n - rounded[i] }))
.sort((a, b) => b.fraction - a.fraction);
const remaining = 100 - rounded.reduce((a, b) => a + b, 0);
for (let i = 0; i < remaining; i++) rounded[order[i].i]++;
return rounded;
}
export interface EstimateResult {
results: (CombatEstimate | undefined)[];
errors: (string | undefined)[];
}
const cache = new Map<string, EstimateResult>();
export function cachedEstimate(key: string) {
return cache.get(key);
}
export function cacheEstimate(key: string, result: EstimateResult) {
cache.delete(key);
cache.set(key, result);
while (cache.size > 4) cache.delete(cache.keys().next().value!);
}

View file

@ -0,0 +1,49 @@
import init, { webQuery } from '../.bridge/server.js';
import { addEstimate, type CombatEstimate, type CombatScenario } from './combat-estimate';
self.onmessage = async ({
data,
}: MessageEvent<{
wasm: string;
raw: string;
seat: number;
action: unknown;
scenarios: CombatScenario[];
}>) => {
try {
await init({ module_or_path: await fetch(data.wasm) });
const results: (CombatEstimate | undefined)[] = [];
const errors: (string | undefined)[] = [];
for (let offset = 0; offset < 2048; offset += 32) {
for (let i = 0; i < data.scenarios.length; i++) {
if (errors[i]) continue;
try {
const batch = JSON.parse(
webQuery(
data.raw,
data.seat,
JSON.stringify({
kind: 'combatEstimate',
action: data.action,
...data.scenarios[i],
samples: 32,
offset,
}),
),
) as CombatEstimate;
results[i] = addEstimate(results[i], batch);
} catch (error) {
results[i] = undefined;
errors[i] = String(error);
}
}
self.postMessage({
results,
errors,
done: offset === 2016 || errors.filter(Boolean).length === data.scenarios.length,
});
if (errors.filter(Boolean).length === data.scenarios.length) break;
}
} catch (error) {
self.postMessage({ error: String(error), done: true });
}
};

View file

@ -1623,6 +1623,11 @@ export class Controller {
s.selectedUnits.length ? s.selectedUnits : position ? this.defaultMovementGroup(position) : [],
);
}
combatEstimateSnapshot() {
const s = get(this.session);
if (!this.engine?.stripSecret || s.seat === undefined) return null;
return { raw: this.engine.stripSecret(this.raw, s.seat), seat: s.seat };
}
query<T>(input: unknown): T {
const s = get(this.session);
if (!this.engine || s.seat === undefined) throw new Error('Choose a player');