Allow direct swaps in Trade Routes reward picker

This commit is contained in:
coyotte508 2026-10-11 22:17:33 +02:00
commit 3a3e1b87a4
8 changed files with 103 additions and 12 deletions

View file

@ -170,3 +170,8 @@ A Trade Routes icon joins the map guides. It draws the selected civilization's c
# Viewer 0.1.63 / engine 0.4.61
Recruitment logs attribute Draft, Sanitation, Sparta and Mercenaries only when the actual payment needs those substitutions. Ambiguous payments retain a single consistent explanation. Old availability-only messages are hidden in the journal without modifying saves. Split primary action rows are combined within the same action and actor; recruitment discount explanations are included in the Recruit row. Separate events, battles, refunds and other players remain distinct.
# Viewer 0.1.64 / engine unchanged (0.4.61)
Trade Routes reward amounts now swap directly between engine-approved combinations. Raising mood, gold or another reward reduces food first, preserves other choices when possible, and always keeps a complete legal reward. Taxes and other reward allocations retain their existing limits. Desktop/mobile smoke coverage exercises India's food/gold/mood choices and verifies the submitted reward.

View file

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

View file

@ -0,0 +1,61 @@
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 npcs = JSON.parse(await engine.init(2, [], {}, 'abilities-ui', {})).players.slice(2);
async function fixture(name) {
const game = JSON.parse(
await readFile(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'),
);
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 browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const [width,height] of [[1400,900],[390,740]]) {
const initial=await fixture('advances/trade_routes_with_currency');
initial.players[1].civilization='India';
const state=JSON.parse(engine.tryMove(JSON.stringify(initial), JSON.stringify({Playing:'EndTurn'}),0));
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));
const food=page.getByRole('combobox',{name:/Food amount/});
const mood=page.getByRole('combobox',{name:/Mood.*amount/});
const gold=page.getByRole('combobox',{name:/Gold amount/});
await food.selectOption('2');
assert.equal(await mood.locator('option[value="2"]').isDisabled(),false);
await mood.selectOption('2');
assert.equal(await food.inputValue(),'0');
assert.equal(await mood.inputValue(),'2');
await gold.selectOption('1');
assert.equal(await mood.inputValue(),'1');
await food.selectOption('2');
assert.equal(await mood.inputValue(),'0');
assert.equal(await gold.inputValue(),'0');
await mood.selectOption('2');
assert.deepEqual(await page.evaluate(()=>sent),[]);
await page.screenshot({path:`/tmp/clash-trade-picker-${width}.png`});
await page.getByRole('button',{name:/^Gain 2 Mood/i}).click();
await page.waitForFunction(()=>sent.length===1);
const [action]=await page.evaluate(()=>sent);
const after=JSON.parse(engine.tryMove(JSON.stringify(state),typeof action==='string'?action:JSON.stringify(action),1));
assert.equal(after.players[1].resources.mood_tokens,state.players[1].resources.mood_tokens+2);
assert.equal(after.players[1].resources.food,state.players[1].resources.food);
assert.deepEqual(errors,[]);
await page.close();
}
console.log('Trade reward desktop/mobile smoke passed');
} finally {await browser.close();}

View file

@ -338,6 +338,7 @@
pending={$session.pending}
optional={field.optional}
reward={decision.reward}
rebalance={decision.reward && decision.origin?.Advance === 'TradeRoutes'}
label={field.name}
/>
{/if}
@ -355,6 +356,7 @@
pending={$session.pending}
optional={field.optional}
reward={decision.reward}
rebalance={decision.reward && decision.origin?.Advance === 'TradeRoutes'}
label={field.name}
/>
{:else}

View file

@ -12,6 +12,7 @@
pending = false,
optional = false,
reward = false,
rebalance = false,
label = 'Payment',
}: {
options: { payment: Pile; disabled?: boolean }[];
@ -21,6 +22,7 @@
pending?: boolean;
optional?: boolean;
reward?: boolean;
rebalance?: boolean;
label?: string;
} = $props();
const icons = {
@ -38,9 +40,9 @@
const paid = $derived(available.filter((option) => !empty(option.payment)));
const selected = $derived(
available.find((option) => samePayment(option.payment, value)) ??
(reward && options.length > 4 ? undefined : available[0]),
(reward && !rebalance && options.length > 4 ? undefined : available[0]),
);
const allocation = $derived(reward ? value : selected?.payment);
const allocation = $derived(reward && !rebalance ? value : selected?.payment);
const totals = $derived([
...new Set(paid.map((option) => Object.values(option.payment).reduce((sum, n) => sum + (n ?? 0), 0))),
]);
@ -76,7 +78,7 @@
onChange(payment);
}
function setAmount(resource: Resource, amount: number) {
if (reward) {
if (reward && !rebalance) {
choose(
rewardWithAmount(
paid.map((option) => option.payment),
@ -94,11 +96,12 @@
selected.payment,
resource,
amount,
rebalance ? 'food' : 'gold',
),
);
}
$effect(() => {
if (reward && options.length > 4) {
if (reward && !rebalance && options.length > 4) {
const withFixed = { ...value, ...fixed };
if (!samePayment(withFixed, value)) {
onChange(withFixed);
@ -165,7 +168,7 @@
>
{#each field.amounts as amount}<option
value={amount}
disabled={reward &&
disabled={reward && !rebalance &&
!canCompletePayment(
paid.map((option) => option.payment),
{ ...allocation, [field.resource]: amount },
@ -176,7 +179,7 @@
{/each}
</div>
<small class="payment-builder-hint"
>{#if reward}{#if totals.length === 1}{allocated} / {totals[0]} selected · {totals[0] - allocated} remaining{:else}Choose
>{#if reward && !rebalance}{#if totals.length === 1}{allocated} / {totals[0]} selected · {totals[0] - allocated} remaining{:else}Choose
a complete resource combination.{/if}{:else}Changing one amount adjusts the others.{/if}</small
>
<div class="payment-builder-total">

View file

@ -44,3 +44,23 @@ test('payment changes preserve fixed costs and prefer gold substitutions', () =>
assert(samePayment({ food: 2 }, { food: 2, gold: 0 }));
assert(!samePayment({ food: 2 }, { food: 1, gold: 1 }));
});
test('Trade Routes swaps the requested reward directly, reducing food first', () => {
const choices: Pile[] = [];
for (let food = 0; food <= 3; food++)
for (let gold = 0; gold <= 3 - food; gold++) choices.push({ food, gold, mood_tokens: 3 - food - gold });
const next = paymentWithAmount(choices, { food: 2, gold: 1 }, 'mood_tokens', 2, 'food');
assert.deepEqual(next, { food: 0, gold: 1, mood_tokens: 2 });
assert.deepEqual(paymentWithAmount(choices, next, 'mood_tokens', 0, 'food'), { food: 2, gold: 1, mood_tokens: 0 });
for (const resource of ['food', 'gold', 'mood_tokens'] as const)
for (let amount = 0; amount <= 3; amount++) {
const changed = paymentWithAmount(choices, next, resource, amount, 'food');
assert.equal(changed[resource], amount);
assert.equal(Object.values(changed).reduce((a, b) => a + (b ?? 0), 0), 3);
assert(choices.includes(changed));
}
const limited = [{ food: 2 }, { food: 1, culture_tokens: 1 }, { food: 1, ideas: 2 }];
assert.deepEqual(paymentWithAmount(limited, limited[0], 'ideas', 2, 'food'), limited[2]);
assert.deepEqual(paymentWithAmount(limited, limited[0], 'culture_tokens', 2, 'food'), limited[0]);
});

View file

@ -16,14 +16,14 @@ export function rewardWithAmount(choices: Pile[], current: Pile, resource: Resou
}
// Keep the requested amount exact and choose a complete legal payment. Prefer
// adjusting gold substitutions over changing the other chosen resources.
export function paymentWithAmount(choices: Pile[], current: Pile, resource: Resource, amount: number): Pile {
// adjusting the preferred substitute before changing the other chosen resources.
export function paymentWithAmount(choices: Pile[], current: Pile, resource: Resource, amount: number, preferred: Resource = 'gold'): Pile {
let selected = current;
let distance = Infinity;
for (const choice of choices) {
if ((choice[resource] ?? 0) !== amount) continue;
const change = resources.reduce(
(sum, r) => sum + Math.abs((choice[r] ?? 0) - (current[r] ?? 0)) * (r === 'gold' ? 1 : 2),
(sum, r) => sum + Math.abs((choice[r] ?? 0) - (current[r] ?? 0)) * (r === preferred ? 1 : 2),
0,
);
if (change < distance) {