Centralize gold-conserving payment choice ordering

This commit is contained in:
coyotte508 2026-11-11 22:33:02 +00:00
commit 536022cf41
11 changed files with 321 additions and 67 deletions

View file

@ -132,6 +132,23 @@ impl PaymentOptions {
Some(payment)
}
/// Order already-enumerated paid choices without changing their membership.
/// Conserve gold, then prefer the engine's native recommendation; keep other
/// ties stable. Empty choices (including optional declines) stay in place.
/// Callers presenting rewards must retain their original enumeration order.
pub fn order_paid_choices(&self, choices: &mut [ResourcePile], available: &ResourcePile) {
let recommended = self.first_valid_payment(available);
let mut paid = choices
.iter()
.filter(|p| !p.is_empty())
.cloned()
.collect::<Vec<_>>();
paid.sort_by_key(|payment| (payment.gold, Some(payment) != recommended.as_ref()));
for (choice, payment) in choices.iter_mut().filter(|p| !p.is_empty()).zip(paid) {
*choice = payment;
}
}
fn find_payment(&self, available: &ResourcePile, exact: bool) -> Option<ResourcePile> {
if let Some(default_fee) = self.separate_fee.first() {
let mut remainder = self.clone();
@ -688,6 +705,47 @@ pub(crate) fn base_resources() -> Vec<ResourcePile> {
#[cfg(test)]
mod tests {
#[test]
fn paid_choice_order_preserves_empty_slots_and_native_research_preference() {
let cost = payment_options_sum(
2,
&[ResourceType::Ideas, ResourceType::Food, ResourceType::Gold],
check_event_origin(),
);
let food = ResourcePile::food(2);
let ideas = ResourcePile::ideas(2);
let mixed = ResourcePile::food(1) + ResourcePile::ideas(1);
let gold = ResourcePile::gold(2);
let mut choices = vec![
ResourcePile::empty(),
gold.clone(),
food.clone(),
ResourcePile::empty(),
mixed.clone(),
ideas.clone(),
ResourcePile::empty(),
];
cost.order_paid_choices(&mut choices, &(food.clone() + ideas.clone() + gold.clone()));
assert_eq!(
choices,
vec![
ResourcePile::empty(),
ideas,
food,
ResourcePile::empty(),
mixed,
gold,
ResourcePile::empty()
]
);
let once = choices.clone();
cost.order_paid_choices(
&mut choices,
&(ResourcePile::food(2) + ResourcePile::ideas(2) + ResourcePile::gold(2)),
);
assert_eq!(choices, once);
}
#[test]
fn recommendations_conserve_gold_for_research_and_mixed_costs() {
let research = payment_options_sum(

View file

@ -383,7 +383,7 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
let payment_options = if advance_choice.is_some_and(|(_, mode)| mode != "paid") {
vec![ResourcePile::empty()]
} else {
advance_payments(&cost)
advance_payments(&cost, &p.resources)
};
let owned = p.has_advance(*advance);
let reason = if owned { Some("Already researched".to_string()) }
@ -540,7 +540,7 @@ fn advance_description(game: &Game, advance: Advance) -> Value {
// Research conversions replace resources one-for-one or waive their cost. Enumerate
// the small set of possible splits, validating every payment against the engine.
// Keeping unaffordable splits here lets the UI describe the cost independently of stock.
fn advance_payments(cost: &PaymentOptions) -> Vec<ResourcePile> {
fn advance_payments(cost: &PaymentOptions, available: &ResourcePile) -> Vec<ResourcePile> {
fn visit(
cost: &PaymentOptions,
types: &[ResourceType],
@ -571,6 +571,7 @@ fn advance_payments(cost: &PaymentOptions) -> Vec<ResourcePile> {
ResourcePile::empty(),
&mut result,
);
cost.order_paid_choices(&mut result, available);
result
}

View file

@ -292,6 +292,9 @@ pub(super) fn payment_choices(
) {
return None;
}
if !reward {
cost.order_paid_choices(&mut result, stock);
}
if optional && !result.iter().any(ResourcePile::is_empty) {
result.push(ResourcePile::empty());
}
@ -880,3 +883,87 @@ pub(super) fn influence_context(game: &Game, seat: usize) -> Option<Value> {
_ => None,
}
}
#[cfg(test)]
mod payment_order_tests {
use super::*;
use crate::events::check_event_origin;
use crate::payment::PaymentConversion;
#[test]
fn paid_roads_order_rewards_declines_and_fallback() {
let cost = PaymentOptions::fixed_resources(
ResourcePile::food(1) + ResourcePile::ore(1),
check_event_origin(),
);
let stock = ResourcePile::food(1) + ResourcePile::ore(1) + ResourcePile::gold(2);
let expected = vec![
ResourcePile::food(1) + ResourcePile::ore(1),
ResourcePile::ore(1) + ResourcePile::gold(1),
ResourcePile::food(1) + ResourcePile::gold(1),
ResourcePile::gold(2),
];
assert_eq!(
payment_choices(&cost, &stock, false, false),
Some(expected.clone())
);
let mut optional = expected.clone();
optional.push(ResourcePile::empty());
assert_eq!(payment_choices(&cost, &stock, false, true), Some(optional));
assert_eq!(
payment_choices(&cost, &stock, true, false),
Some(vec![
expected[3].clone(),
expected[1].clone(),
expected[2].clone(),
expected[0].clone()
])
);
assert_eq!(
payment_choices(&cost, &ResourcePile::gold(2), false, false),
Some(vec![ResourcePile::gold(2)])
);
let huge = PaymentOptions::fixed_resources(ResourcePile::food(200), check_event_origin());
assert!(
payment_choices(
&huge,
&(ResourcePile::food(200) + ResourcePile::gold(200)),
false,
false
)
.is_none()
);
}
#[test]
fn ordering_retains_all_exact_discounted_and_fee_payments() {
let mut cost = PaymentOptions::fixed_resources(
ResourcePile::food(2) + ResourcePile::gold(1),
check_event_origin(),
);
cost.conversions.push(PaymentConversion::limited(
ResourcePile::food(1),
ResourcePile::empty(),
1,
));
cost.default += ResourcePile::mood_tokens(1);
cost.separate_fee = vec![ResourcePile::mood_tokens(1)];
let stock = ResourcePile::food(2) + ResourcePile::gold(3) + ResourcePile::mood_tokens(1);
let choices = payment_choices(&cost, &stock, false, false).unwrap();
assert_eq!(choices.first(), cost.first_valid_payment(&stock).as_ref());
let mut exact = vec![];
for food in 0..=2 {
for gold in 0..=3 {
let pile = ResourcePile::food(food)
+ ResourcePile::gold(gold)
+ ResourcePile::mood_tokens(1);
if cost.is_valid_payment(&pile) {
exact.push(pile);
}
}
}
assert_eq!(choices.len(), exact.len());
assert!(exact.iter().all(|p| choices.contains(p)));
assert!(choices.iter().all(|p| p.gold >= 1 && p.mood_tokens == 1));
}
}

View file

@ -1241,3 +1241,30 @@ ship-only recruitment and gold-conserving payment recommendations are unchanged.
Publish the matching engine, bridge and viewer. Preserve the existing gallery and
all unrelated metadata, including game-length option labels/order and Standard as
default. This release performs no live game moves or historical repairs.
# Viewer 0.1.215 / engine 0.4.147
Centralized paid-choice ordering lists lower-gold payments first, then the native
recommendation among equal-gold choices, retaining stable ties. Research and the
shared web payment enumerator use the same policy. Roads offers food/ore,
ore/gold, food/gold, then two gold; explicitly selecting gold remains valid for
both routes and attacks. Carthage recruitment retains all legal alternatives.
Empty choices retain their positions, optional declines remain unchanged, and
rewards bypass ordering. Legality, default recommendations, route ordering and
oversized-enumeration fallback are unchanged; no extra exhaustive enumeration is
introduced.
Publish the matching engine, bridge and viewer. Preserve the existing real-game
gallery and all unrelated metadata, including game-length labels/order and
Standard as default. No live game moves or historical repairs are performed.
Release checks also caught an unused inline WASM fallback in the combat worker.
The existing external-WASM build transform now runs in worker builds too, keeping
the engine out of the inline worker script. Worker initialization still receives
the explicit external engine URL. The bundle smoke checks a single WASM request
and ready event on desktop/mobile.
Verified with Rust 1.94.1: 500 native workspace tests pass (one existing ignored),
1,062 frontend tests against the packed engine, gallery checks, all 17 locales,
extraction checks, Svelte (zero errors/warnings), and production build. Existing
Clippy warnings and expected rejected-move WASM diagnostics remain.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.214",
"version": "0.1.215",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.214",
"version": "0.1.215",
"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.214",
"version": "0.1.215",
"private": true,
"type": "module",
"scripts": {

View file

@ -18,48 +18,96 @@ const browser = await chromium.launch({
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const [width,height] of [[1400,900],[390,740]]) {
const state=await fixture('advances/roads_unit_test');
state.current_player_index=1;
state.players[1].units=state.players[1].units.filter(u=>u.id!==2);
state.players[1].resources={food:1,ore:1,gold:2};
const target=state.players[1].cities.find(c=>c.position==='F7');
state.players[1].cities=state.players[1].cities.filter(c=>c.position!=='F7');
state.players[0].cities.push(target);
const page=await browser.newPage({viewport:{width,height}}),errors=[];
page.on('pageerror',e=>errors.push(e.message));
await page.route('**/*',async route=>{
const path=new URL(route.request().url()).pathname;
if(path==='/') return route.fulfill({contentType:'text/html',body:'<!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(path)) return route.abort();
return route.fulfill({contentType:path.endsWith('.wasm')?'application/wasm':'text/javascript',body:await readFile(new URL('../dist'+path,import.meta.url))});
});
await page.goto('http://clash.test');
await page.evaluate(state=>{window.host=clash3d.launch('#app');window.sent=[];host.on('move',a=>sent.push(a));host.emit('player',{index:1});host.emit('theme',{dark:true});host.emit('preferences',{sound:false});host.emit('state',state)},engine.stripSecret(JSON.stringify(state),1));
async function tile(pos) {
// Use the map's accessible target, not coordinates that move while the
// camera finishes framing the board.
const target = page.locator(`.map-hit-target[data-position="${pos}"]`);
await target.focus();
await target.press('Enter');
}
await tile('D8');
await page.screenshot({path:`/tmp/move-before-target-${width}.png`});
await tile('F7');
const choices=page.getByRole('group',{name:'Choose how to move'});
await choices.waitFor();
assert.equal(await choices.getByRole('button').count(),4);
assert.deepEqual(await page.evaluate(()=>sent),[]);
await choices.getByRole('button').first().click();
await page.getByLabel('Attack preview',{exact:true}).waitFor();
assert.deepEqual(await page.evaluate(()=>sent),[]);
const bounds=await page.locator('[aria-label="Unit movement"]').boundingBox();
const attack=await page.locator('.settler-confirm button').boundingBox();
assert.ok(bounds && attack && attack.y >= bounds.y && attack.y + attack.height <= bounds.y + bounds.height, 'attack stays visible');
assert.equal(await page.getByLabel('Attack preview',{exact:true}).locator('.defenders-label').innerText(),'Defenders');
await page.screenshot({path:`/tmp/clash-roads-payment-${width}.png`});
assert.deepEqual(errors,[]);
await page.close();
}
console.log('Roads payment selection before attack desktop/mobile smoke passed');
} finally {await browser.close();}
for (const attackRoute of [false, true])
for (const [width, height] of [
[1400, 900],
[390, 740],
]) {
const state = await fixture('advances/roads_unit_test');
state.current_player_index = 1;
state.players[1].units = state.players[1].units.filter((u) => u.id !== 2);
state.players[1].resources = { food: 1, ore: 1, gold: 2 };
if (attackRoute) {
const target = state.players[1].cities.find((c) => c.position === 'F7');
state.players[1].cities = state.players[1].cities.filter((c) => c.position !== 'F7');
state.players[0].cities.push(target);
}
const page = await browser.newPage({ viewport: { width, height } }),
errors = [];
page.on('pageerror', (e) => errors.push(e.message));
await page.route('**/*', async (route) => {
const path = new URL(route.request().url()).pathname;
if (path === '/')
return route.fulfill({
contentType: 'text/html',
body: '<!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(path)) return route.abort();
return route.fulfill({
contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(new URL('../dist' + path, import.meta.url)),
});
});
await page.goto('http://clash.test');
await page.evaluate(
(state) => {
window.host = clash3d.launch('#app');
window.sent = [];
host.on('move', (a) => sent.push(a));
host.emit('player', { index: 1 });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false });
host.emit('state', state);
},
engine.stripSecret(JSON.stringify(state), 1),
);
async function tile(pos) {
// Use the map's accessible target, not coordinates that move while the
// camera finishes framing the board.
const target = page.locator(`.map-hit-target[data-position="${pos}"]`);
await target.focus();
await target.press('Enter');
}
await tile('D8');
await page.screenshot({ path: `/tmp/move-before-target-${width}.png` });
await tile('F7');
const choices = page.getByRole('group', { name: 'Choose how to move' });
await choices.waitFor();
assert.equal(await choices.getByRole('button').count(), 4);
assert.deepEqual(await page.evaluate(() => sent), []);
const buttons = choices.getByRole('button');
const piles = await buttons.evaluateAll((nodes) =>
nodes.map((node) =>
[...node.querySelectorAll('.resource-amount [title]')].map((n) => n.getAttribute('title')),
),
);
assert.deepEqual(piles, [['1 Food', '1 Ore'], ['1 Gold', '1 Ore'], ['1 Food', '1 Gold'], ['2 Gold']]);
await buttons.last().click();
if (attackRoute) {
await page.getByLabel('Attack preview', { exact: true }).waitFor();
assert.deepEqual(await page.evaluate(() => sent), []);
const bounds = await page.locator('[aria-label="Unit movement"]').boundingBox();
const attack = await page.locator('.settler-confirm button').boundingBox();
assert.ok(
bounds && attack && attack.y >= bounds.y && attack.y + attack.height <= bounds.y + bounds.height,
'attack stays visible',
);
assert.equal(
await page.getByLabel('Attack preview', { exact: true }).locator('.defenders-label').innerText(),
'Defenders',
);
await page.screenshot({ path: `/tmp/clash-roads-payment-${width}.png` });
assert.equal(await choices.getByRole('button').last().getAttribute('aria-pressed'), 'true');
await page.locator('.settler-confirm button').click();
}
await page.waitForFunction(() => sent.length === 1);
const action = JSON.parse((await page.evaluate(() => sent))[0]);
assert.deepEqual(action.Movement.Move.payment, { gold: 2 });
assert.doesNotThrow(() => engine.tryMove(JSON.stringify(state), JSON.stringify(action), 1));
assert.deepEqual(errors, []);
await page.close();
}
console.log('Roads ordered payments, manual gold route/attack desktop/mobile smoke passed');
} finally {
await browser.close();
}

View file

@ -2763,12 +2763,14 @@ test('Roads offers food/gold choices before an attack and submits the selected p
await c.load(engine.stripSecret(JSON.stringify(g), 1));
c.openUnits([0, 1]);
const offers = app.session().moveDestinations.filter(d => d.position === 'F7');
assert(offers.some(d => d.payment.food === 1 && d.payment.ore === 1));
assert(offers.some(d => d.payment.food === 1 && d.payment.gold === 1));
assert(offers.some(d => d.payment.gold === 2));
assert.deepEqual(offers.map(d => d.payment), [
{ food: 1, ore: 1 }, { ore: 1, gold: 1 }, { food: 1, gold: 1 }, { gold: 2 },
]);
for (const offer of offers)
assert.doesNotThrow(() => engine.tryMove(JSON.stringify(g), JSON.stringify(offer.action), 1));
c.chooseMoveDestination('F7');
assert.deepEqual(app.sent, []);
const index = app.session().moveDestinations.findIndex(d => d.position === 'F7' && d.payment.food === 1 && d.payment.ore === 1);
const index = app.session().moveDestinations.findIndex(d => d.position === 'F7' && d.payment.gold === 2);
c.chooseMoveRoute(index);
assert.deepEqual(app.sent, [], 'choosing payment previews the battle without starting it');
const action = app.session().moveDestinations[index].action;
@ -2778,6 +2780,23 @@ test('Roads offers food/gold choices before an attack and submits the selected p
} finally { app.close(); }
});
test('Roads retains the gold-only fallback when ordinary resources are missing', async () => {
const app = paymentController(), c = app.controller;
try {
const g = JSON.parse(fixture('advances/roads_unit_test'));
g.current_player_index = 1;
g.players[1].resources = { gold: 2 };
c.setPlayer(1);
await c.load(engine.stripSecret(JSON.stringify(g), 1));
c.openUnits([0, 1]);
const offers = app.session().moveDestinations.filter(d => d.position === 'F7');
assert.deepEqual(offers.map(d => d.payment), [{ gold: 2 }]);
c.chooseMoveDestination('F7');
assert.deepEqual(app.sent.map(a => JSON.parse(a)), [offers[0].action]);
assert.doesNotThrow(() => engine.tryMove(JSON.stringify(g), app.sent[0], 1));
} finally { app.close(); }
});
test('Collect preselects all tiles only when their count equals capacity', async () => {
const app = paymentController(), c = app.controller;
try {

View file

@ -640,6 +640,7 @@ test('research defaults conserve gold without removing explicit gold choices', a
const view: View = JSON.parse(engine.webView(engine.stripSecret(state, seat), seat));
const research = view.advances.find((a) => a.id === 'Storage')!;
assert.deepEqual(research.payment, expected);
assert.deepEqual(research.payments.find((p) => p.action)?.payment, expected, 'first affordable choice is the native recommendation');
const recommended = research.payments.find((p) => samePayment(p.payment, expected));
assert.ok(recommended?.action, 'the recommendation is an executable picker choice');
assert.deepEqual(research.action, recommended.action);

View file

@ -1187,6 +1187,13 @@ test('Warbeasts and Mercenaries offer and execute combined Elephant and Ship pay
if (market) p.cities[0].city_pieces.market = index;
const units = { elephants: 1, ships: 1 };
const offer = query(g, { kind: 'recruit', city: 'D2', units, replaced: [] });
assert.deepEqual(offer.payments.map((p: any) => p.gold ?? 0),
offer.payments.map((p: any) => p.gold ?? 0).sort((a: number, b: number) => a - b));
for (const payment of offer.payments) {
const selected = query(g, { kind: 'recruit', city: 'D2', units, replaced: [], payment });
assert.deepEqual(selected.payment, payment);
assert.doesNotThrow(() => move(g, selected.action));
}
for (const payment of [
{ food: 1, gold: 2 },
{ food: 1, gold: 1, mood_tokens: 1 },

View file

@ -2,7 +2,25 @@ import { defineConfig } from 'vite';
import { readFileSync } from 'node:fs';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { previewApi } from './scripts/preview-api';
// Worker builds have their own plugin pipeline; keep their unused default URL
// external too, rather than embedding a second engine in the inline worker.
function externalWasmFallback() {
return {
name: 'external-wasm-fallback',
enforce: 'pre' as const,
transform(code: string, id: string) {
if (!id.endsWith('/.bridge/server.js')) return;
// wasm-bindgen's default URL must stay external in library builds too.
// Otherwise Vite embeds a second copy alongside our explicit Wasm import.
return code.replace(
"new URL('server_bg.wasm', import.meta.url)",
"new URL('server_bg.wasm?no-inline', import.meta.url)",
);
},
};
}
export default defineConfig({
worker: { plugins: () => [externalWasmFallback()] },
base: './',
publicDir: false,
plugins: [
@ -30,19 +48,7 @@ export default defineConfig({
});
},
},
{
name: 'external-wasm-fallback',
enforce: 'pre',
transform(code, id) {
if (!id.endsWith('/.bridge/server.js')) return;
// wasm-bindgen's default URL must stay external in library builds too.
// Otherwise Vite embeds a second copy alongside our explicit Wasm import.
return code.replace(
"new URL('server_bg.wasm', import.meta.url)",
"new URL('server_bg.wasm?no-inline', import.meta.url)",
);
},
},
externalWasmFallback(),
// BGS loads the viewer script alone, so component styles must travel with it.
svelte({ emitCss: false }),
previewApi(),