Conserve wildcard gold in default payments; release viewer 213 and engine 145

This commit is contained in:
coyotte508 2026-11-10 22:28:21 +00:00
commit 2923a068fc
10 changed files with 259 additions and 29 deletions

View file

@ -111,7 +111,25 @@ impl PaymentOptions {
#[must_use]
pub fn first_valid_payment(&self, available: &ResourcePile) -> Option<ResourcePile> {
self.find_payment(available, false)
let mut payment = self.find_payment(available, false)?;
// The conversion search proves legality, but its first route may mix in
// gold even when more of the ordinary resources are available (research
// can take one food, then one gold, before trying two food). Recommend
// conserving wildcard gold without changing that search's exact-payment
// semantics or enumerating every possible payment. Keep printed gold.
let mut lower = self.default.gold.min(payment.gold);
let mut upper = payment.gold;
let mut limited = available.clone();
while lower < upper {
limited.gold = lower + (upper - lower) / 2;
if let Some(candidate) = self.find_payment(&limited, false) {
upper = candidate.gold;
payment = candidate;
} else {
lower = limited.gold + 1;
}
}
Some(payment)
}
fn find_payment(&self, available: &ResourcePile, exact: bool) -> Option<ResourcePile> {
@ -284,7 +302,8 @@ impl PaymentOptions {
#[must_use]
pub fn can_afford(&self, available: &ResourcePile) -> bool {
self.is_free() || self.first_valid_payment(available).is_some()
// Availability only needs a witness, not the preferred allocation.
self.is_free() || self.find_payment(available, false).is_some()
}
#[must_use]
@ -669,6 +688,94 @@ pub(crate) fn base_resources() -> Vec<ResourcePile> {
#[cfg(test)]
mod tests {
#[test]
fn recommendations_conserve_gold_for_research_and_mixed_costs() {
let research = payment_options_sum(
2,
&[ResourceType::Ideas, ResourceType::Food, ResourceType::Gold],
check_event_origin(),
);
for (available, expected) in [
(
ResourcePile::food(2) + ResourcePile::gold(2),
ResourcePile::food(2),
),
(
ResourcePile::food(1) + ResourcePile::gold(2),
ResourcePile::food(1) + ResourcePile::gold(1),
),
(ResourcePile::gold(2), ResourcePile::gold(2)),
(
ResourcePile::ideas(2) + ResourcePile::food(2) + ResourcePile::gold(2),
ResourcePile::ideas(2),
),
] {
assert_eq!(research.first_valid_payment(&available), Some(expected));
}
assert!(
research.is_valid_payment(&ResourcePile::gold(2)),
"manual gold remains legal"
);
assert_eq!(research.first_valid_payment(&ResourcePile::food(1)), None);
let mixed = PaymentOptions::fixed_resources(
ResourcePile::food(2) + ResourcePile::wood(1) + ResourcePile::ore(1),
check_event_origin(),
);
let native = ResourcePile::food(2) + ResourcePile::ore(1);
assert_eq!(
mixed.first_valid_payment(&(native.clone() + ResourcePile::gold(4))),
Some(native + ResourcePile::gold(1))
);
}
#[test]
fn recommendations_preserve_printed_gold_and_separate_fees() {
let mut cost = PaymentOptions::fixed_resources(
ResourcePile::food(2) + ResourcePile::gold(1),
check_event_origin(),
);
let expected = cost.default.clone();
assert_eq!(
cost.first_valid_payment(&(ResourcePile::food(3) + ResourcePile::gold(3))),
Some(expected.clone())
);
assert_eq!(cost.first_valid_payment(&ResourcePile::food(4)), None);
cost.default += ResourcePile::mood_tokens(1);
cost.separate_fee = vec![ResourcePile::mood_tokens(1)];
assert_eq!(
cost.first_valid_payment(&(ResourcePile::food(2) + ResourcePile::gold(3))),
None
);
assert_eq!(
cost.first_valid_payment(
&(ResourcePile::food(2) + ResourcePile::gold(3) + ResourcePile::mood_tokens(1))
),
Some(expected + ResourcePile::mood_tokens(1))
);
}
#[test]
fn recommendations_keep_discounts_and_alternative_payments() {
let mut cost = PaymentOptions::fixed_resources(ResourcePile::food(3), check_event_origin());
cost.conversions.push(PaymentConversion::limited(
ResourcePile::food(1),
ResourcePile::empty(),
1,
));
assert_eq!(
cost.first_valid_payment(&(ResourcePile::food(3) + ResourcePile::gold(3))),
Some(ResourcePile::food(2))
);
assert!(cost.is_valid_payment(&ResourcePile::gold(2)));
cost.conversions.pop();
cost.alternatives.push(ResourcePile::wood(2));
assert_eq!(
cost.first_valid_payment(&(ResourcePile::wood(2) + ResourcePile::gold(3))),
Some(ResourcePile::wood(2))
);
}
#[test]
fn separate_fee_tries_all_choices_without_converting_the_fee() {
let mut cost = PaymentOptions::new(

View file

@ -253,7 +253,14 @@ fn alternative_costs_keep_their_own_payment_totals() {
ResourcePile::culture_tokens(3),
] {
assert!(cost.is_valid_payment(&payment), "{payment}");
assert_eq!(cost.first_valid_payment(&payment), Some(payment));
let expected = if payment == ResourcePile::gold(2) {
// The cheaper alternative is recommended, but spending two gold
// remains an exact legal manual choice.
ResourcePile::gold(1)
} else {
payment.clone()
};
assert_eq!(cost.first_valid_payment(&payment), Some(expected));
}
assert!(!cost.is_valid_payment(&ResourcePile::culture_tokens(2)));
assert!(!cost.is_valid_payment(&ResourcePile::gold(3)));

View file

@ -1213,3 +1213,17 @@ release does not change that separate limitation. Tests use synthetic setups onl
production saves are not committed. Publish the matching bridge and viewer while
preserving the existing gallery and all unrelated metadata, including game-length
labels/order and Standard as default.
# Viewer 0.1.213 / engine 0.4.145
Default payments conserve wildcard gold when ordinary resources can cover the
cost, including research using food or ideas. A bounded gold-allowance search
reuses the existing legality checks and keeps required printed gold, separate
fees, discounts and native-resource preferences. Affordability-only checks avoid
the preference search. Alternative-payment enumeration order and reward semantics
are unchanged; this changes the recommendation, not the list of legal choices.
Manual gold payments remain valid and survive ordinary host refreshes.
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.

View file

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

View file

@ -87,8 +87,8 @@ try {
await panel.waitFor();
assert.match(await panel.innerText(), new RegExp(`\\+${enemySteel ? 1 : 2} combat value each round`));
assert.equal((await panel.innerText()).includes('Enemy has Steel Weapons.'), enemySteel);
assert.doesNotMatch(await panel.innerText(), /Use steel weapons|Pay|Decline/);
const buttons = panel.locator('.cost-only button');
// Steel Weapons now previews a selected payment before explicit confirmation.
const buttons = panel.locator('.compact-payments button');
assert.equal(await buttons.count(), 3);
const bounds = await buttons.evaluateAll((els) =>
els.map((el) => ({
@ -99,12 +99,14 @@ try {
})),
);
assert(
bounds.every((b) => b.width <= 90 && b.height >= 36),
'Payment choices are compact touch targets',
bounds.every((b) => b.width >= 36 && b.height >= 36 && b.height <= 48),
'Payment choices remain compact-height touch targets',
);
assert(
bounds.every((b) => Math.abs(b.y - bounds[0].y) < 1),
'All three options fit in one row',
bounds.every((b, i) => bounds.slice(i + 1).every((other) =>
b.x + b.width <= other.x + 1 || other.x + other.width <= b.x + 1 ||
b.y + b.height <= other.y + 1 || other.y + other.height <= b.y + 1)),
'All payment choices fit without overlapping in the responsive grid',
);
assert(await panel.evaluate((el) => el.scrollWidth <= el.clientWidth + 1));
if (scenario === 'regular' || scenario === 'enemy-steel')
@ -112,10 +114,12 @@ try {
const payment = scenario === 'decline' ? {} : scenario === 'regular' ? { gold: 1 } : { ore: 1 };
await panel
.getByRole('button', {
name: scenario === 'decline' ? 'No' : scenario === 'regular' ? 'Pay 1 gold' : 'Pay 1 ore',
name: scenario === 'decline' ? 'Decline' : scenario === 'regular' ? 'Pay 1 gold' : 'Pay 1 ore',
exact: true,
})
.click();
assert.deepEqual(sent, [], 'Selecting a payment does not submit before confirmation');
await panel.getByRole('button', { name: 'Confirm', exact: true }).click();
await page.waitForFunction(() => window.moveApplied);
assert.deepEqual(sent, [{ Response: { Payment: [payment] } }]);
const payments = state.log
@ -128,7 +132,7 @@ try {
(item) =>
item.player === 0 &&
item.origin?.Advance === 'SteelWeapons' &&
item.Resources?.balance === 'Loss',
item.Resources?.balance === 'Pay',
)
.map((item) => item.Resources.resources);
assert.deepEqual(payments, [payment]);

View file

@ -0,0 +1,76 @@
// Offline real-engine + built-viewer regression. Run after build:bridge and build.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { chromium } from 'playwright';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const initial = JSON.parse(await engine.init(2, [], { civilization: 'Random' }, 'payment-defaults', {}));
const seat = engine.currentPlayer(JSON.stringify(initial));
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
for (const width of [1400, 390]) {
for (const [resources, expected] of [
[{ food: 2, gold: 2 }, { food: 2 }],
[{ food: 1, gold: 2 }, { food: 1, gold: 1 }],
[{ ideas: 1, food: 2, gold: 2 }, { ideas: 1, food: 1 }],
]) {
const state = structuredClone(initial);
state.players[seat].resources = resources;
const stripped = engine.stripSecret(JSON.stringify(state), seat);
const research = JSON.parse(engine.webView(stripped, seat)).advances.find((a) => a.id === 'Storage');
assert.deepEqual(research.payment, expected);
const page = await browser.newPage({ viewport: { width, height: 900 } });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.route('**/*', async (route) => {
const url = new URL(route.request().url());
if (url.hostname !== 'clash.test') return route.abort();
if (url.pathname === '/') 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(url.pathname)) return route.abort();
return route.fulfill({ contentType: url.pathname.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(new URL('../dist' + url.pathname, import.meta.url)) });
});
await page.goto('http://clash.test/');
await page.evaluate(({ state, seat }) => {
window.host = clash3d.launch('#app'); window.sent = [];
host.on('move', (action) => sent.push(JSON.parse(action)));
host.emit('player', { index: seat });
host.emit('preferences', { sound: false });
host.emit('state', state);
}, { state: stripped, seat });
await page.getByRole('button', { name: 'Research tree', exact: true }).click();
await page.locator('#research-Storage .research-pick').click();
const picker = page.getByRole('group', { name: 'Research payment', exact: true });
await picker.waitFor();
if (research.payments.length <= 4) {
const selected = picker.locator('[aria-pressed="true"]');
assert.equal(await selected.count(), 1);
for (const [resource, amount] of Object.entries(expected))
assert.equal(await selected.locator(`[title="${amount} ${resource[0].toUpperCase() + resource.slice(1)}"]`).count(), 1);
await picker.getByRole('button', { name: 'Pay 2 gold', exact: true }).click();
} else {
assert.equal(await picker.getByLabel('Food amount for Research payment').inputValue(), '1');
assert.equal(await picker.getByLabel('Ideas amount for Research payment').inputValue(), '1');
assert.equal(await picker.getByLabel('Gold amount for Research payment').inputValue(), '0');
await picker.getByLabel('Gold amount for Research payment').selectOption('2');
}
// A normal host refresh must not reset a valid manual allocation.
await page.evaluate((state) => host.emit('state', state), stripped);
if (research.payments.length <= 4)
assert.equal(await picker.getByRole('button', { name: 'Pay 2 gold', exact: true }).getAttribute('aria-pressed'), 'true');
else assert.equal(await picker.getByLabel('Gold amount for Research payment').inputValue(), '2');
assert.deepEqual(await page.evaluate(() => sent), []);
await page.locator('.research-payment > .primary').click();
await page.waitForFunction(() => sent.length === 1);
const action = await page.evaluate(() => sent[0]);
assert.deepEqual(action.Playing.Advance.payment, { gold: 2 });
const after = JSON.parse(engine.tryMove(JSON.stringify(state), JSON.stringify(action), seat));
assert.equal(after.players[seat].resources.gold ?? 0, 0);
assert.equal(after.players[seat].resources.food ?? 0, resources.food);
assert.deepEqual(errors, []);
console.log(`${width}px ${JSON.stringify(resources)}: native default and persistent manual gold verified`);
await page.close();
}
}
} finally { await browser.close(); }

View file

@ -103,8 +103,8 @@ try {
assert(state.players[0].cities.some((c) => c.city_pieces?.wonders?.includes('Colosseum')));
if (count === 10) {
await page.locator('.city-map-label').first().click();
await page.getByRole('button', { name: 'Colosseum', exact: true }).click();
const info = page.getByRole('region', { name: 'Colosseum effect', exact: true });
await page.getByRole('button', { name: 'Great Arena', exact: true }).click();
const info = page.getByRole('region', { name: 'Great Arena effect', exact: true });
await info.waitFor();
assert.match(await info.innerText(), /combat value/);
assert(await info.evaluate((el) => el.scrollWidth <= el.clientWidth + 1));
@ -123,16 +123,16 @@ try {
engine.stripSecret(JSON.stringify(state), 0),
);
await page.locator('.city-map-label').first().click();
for (const name of ['Great Lighthouse', 'Pyramids']) {
for (const name of ['Great Lighthouse', 'Great Pyramids']) {
await page.getByRole('button', { name, exact: true }).click();
const effect = page.getByRole('region', { name: `${name} effect`, exact: true });
const effect = page.getByRole('region', { name: `${name === 'Great Pyramids' ? 'Great Pyramid' : name} effect`, exact: true });
await effect.waitFor();
if (name === 'Pyramids')
if (name === 'Great Pyramids')
assert.match(await effect.innerText(), /5\.1 VP for building · 0 VP for owning/);
}
await page.screenshot({ path: `/tmp/clash-multiple-wonders-${width}.png` });
await page.getByRole('button', { name: 'Close tile actions', exact: true }).click();
await page.getByRole('button', { name: 'Toggle top-down view', exact: true }).click();
await page.getByRole('button', { name: 'Strategy map', exact: true }).click();
await page.screenshot({ path: `/tmp/clash-wonders-overhead-${width}.png` });
}
if (count === 34) {
@ -179,15 +179,10 @@ try {
const hex = page.locator('.map-hit-target[data-position="C1"]');
await hex.focus();
await hex.press('Enter');
const terrain = movement.getByRole('complementary', { name: 'Mountain rules', exact: true });
await terrain.waitFor();
assert.match(await terrain.innerText(), /cannot move again/);
assert.match(await terrain.innerText(), /No terrain bonus to combat value/);
assert(await movement.evaluate((el) => el.scrollWidth <= el.clientWidth + 1));
assert((await terrain.boundingBox()).height < 115, 'Terrain explanation remains compact');
await page.screenshot({ path: `/tmp/clash-terrain-move-${width}.png` });
await movement.getByRole('button', { name: 'Move here', exact: true }).click();
// Ordinary unambiguous moves now submit directly; only attacks and
// exploration retain a preview/confirmation step.
await page.waitForFunction(() => !document.querySelector('.settler-confirm'));
await page.screenshot({ path: `/tmp/clash-terrain-move-${width}.png` });
assert.equal(sent, 3);
assert(state.players[0].units[0].movement_restrictions.includes('Mountain'));
const closeMovement = page.getByRole('button', { name: 'Close movement controls', exact: true });

View file

@ -55,7 +55,7 @@ try {
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('h3').innerText(),'Defenders');
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();

View file

@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs';
import { createViewer } from '@boardgamers/protocol/viewer';
import { ChatController } from '@boardgamers/protocol/chat';
import { journal, positionXY } from './model.ts';
import { samePayment } from './payment-options.ts';
import type { View, Game } from './types.ts';
const require = createRequire(import.meta.url);
const engine = require('../.engine/server.js');
@ -624,6 +625,32 @@ test('research displays a stable flexible cost and offers executable food, idea,
assert.ok(view.advances.find((a) => a.id === 'Farming')!.payments.every((p) => p.action === null));
});
test('research defaults conserve gold without removing explicit gold choices', async () => {
const raw = JSON.parse(await initial());
const seat = engine.currentPlayer(JSON.stringify(raw));
for (const [resources, expected] of [
[{ food: 2, gold: 2 }, { food: 2 }],
[{ food: 1, gold: 2 }, { food: 1, gold: 1 }],
[{ ideas: 2, food: 2, gold: 2 }, { ideas: 2 }],
[{ ideas: 1, food: 2, gold: 2 }, { ideas: 1, food: 1 }],
[{ gold: 2 }, { gold: 2 }],
]) {
raw.players[seat].resources = resources;
const state = JSON.stringify(raw);
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);
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);
const gold = research.payments.find((p) => p.payment.gold === 2)!;
assert.ok(gold.action, 'manual gold remains available');
const after = JSON.parse(engine.tryMove(state, JSON.stringify(gold.action), seat));
assert.equal(after.players[seat].resources.gold ?? 0, 0);
assert.equal(after.players[seat].resources.food ?? 0, resources.food ?? 0);
}
});
test('research discounts produce a free payment while still consuming an action and event marker', async () => {
const raw = JSON.parse(await initial());
const seat = engine.currentPlayer(JSON.stringify(raw));