Restrict Siegecraft to attackers and offer Roads payment choices

This commit is contained in:
coyotte508 2026-10-12 23:28:53 +02:00
commit 94ec217d18
9 changed files with 163 additions and 5 deletions

View file

@ -51,6 +51,9 @@ fn siegecraft() -> AdvanceBuilder {
|e| &mut e.combat_start,
0,
|game, player, c| {
if player.index != c.attacker() {
return None;
}
let p = player.get(game);
let extra_die =
player
@ -84,6 +87,17 @@ fn siegecraft() -> AdvanceBuilder {
}
},
|game, s, c| {
// Older saves can contain an invalid defender Siegecraft prompt.
// Finish it without disabling their fortress or spending resources.
if s.player_index != c.attacker() {
for payment in &s.choice {
if !payment.is_empty() {
s.player().gain_resources(game, payment.clone());
}
}
s.log(game, "Siegecraft skipped: only the attacker may use it");
return;
}
let mut modifiers: Vec<CombatModifier> = Vec::new();
let payment = &s.choice;
if !payment[0].is_empty() {

View file

@ -238,7 +238,9 @@ pub fn movement(game: &Game, seat: usize, units: Vec<u32>) -> Result<Value, Stri
let mut destinations = vec![];
for carrier in carriers {
for route in possible_move_routes(p, game, &units, start, carrier).unwrap_or_default() {
if let Some(payment) = route.cost.first_valid_payment(&p.resources) {
let payments = super::decisions::payment_choices(&route.cost, &p.resources, false, false)
.unwrap_or_else(|| route.cost.first_valid_payment(&p.resources).into_iter().collect());
for payment in payments {
let breaks_diplomacy =
route
.cost

View file

@ -261,3 +261,11 @@ Verified both responses against a local copy of Willful-vertex-9913 without subm
# Viewer 0.1.81 / engine unchanged (0.4.69)
Opening Chat, including switching from Journal, scrolls its message feed to the newest message after the panel becomes visible. Scrolling back while Chat remains open is preserved; pending scrolls are cancelled on close or teardown. Verified with desktop/mobile browser checks using an overflowing message history, type checks and production build.
# Viewer 0.1.82 / engine 0.4.70
Siegecraft is offered only to the attacker. Legacy defender prompts finish without cancelling fortress abilities, refund any selected payment, and explain the skipped ability in the journal. Verified declining and paying against a local copy of Willful-vertex-9913; no live moves submitted.
Movement exposes all affordable payment combinations instead of selecting the first valid payment. Roads therefore offers food/ore and gold substitutions before committing the move. Attack destinations retain their preview after payment selection, and alternative payments remain available in the panel. Regression checks cover attacker/defender Siegecraft, legacy prompts, and choosing Roads payment before submitting an attack.
All 737 tests, locale validation, type checks and production build pass. Desktop/mobile browser checks confirm four payment choices and no submitted move before the attack preview.

View file

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

View file

@ -0,0 +1,59 @@
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 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));
await page.waitForTimeout(500);
await page.waitForTimeout(400);
async function tile(pos) {
const box=await page.locator(`.map-hit-target[data-position="${pos}"]`).boundingBox();
assert(box); await page.mouse.click(box.x+box.width/2,box.y+box.height/2); await page.waitForTimeout(250);
}
await tile('D8');
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),[]);
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();}

View file

@ -170,11 +170,13 @@
{/each}
</div>
{/if}
{#if $session.moveTarget && !destination && $session.moveDestinations.length}
{#if $session.moveTarget && $session.moveDestinations.filter((d) => d.position === $session.moveTarget).length > 1}
<div class="settler-destinations" role="group" aria-label="Choose how to move">
{#each $session.moveDestinations as d, i}{#if d.position === $session.moveTarget}
<button
disabled={!!$session.playback || $session.pending}
class:active={$session.moveDestination === i}
aria-pressed={$session.moveDestination === i}
onmouseenter={() => onHighlight(d.position)}
onmouseleave={() => onHighlight(null)}
onclick={() => controller.chooseMoveRoute(i)}

View file

@ -2660,3 +2660,31 @@ test('triggered event rules appear live and replay pauses on their historical fr
assert.equal(app.session().playback?.events?.length,0);
} finally {app.close();}
});
test('Roads offers food/gold choices before an attack and submits the selected payment', 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 = { food: 1, ore: 1, gold: 2 };
const target = g.players[1].cities.find((city: any) => city.position === 'F7');
g.players[1].cities = g.players[1].cities.filter((city: any) => city.position !== 'F7');
g.players[0].cities.push(target);
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(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));
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);
c.chooseMoveRoute(index);
assert.deepEqual(app.sent, [], 'choosing payment previews the battle without starting it');
const action = app.session().moveDestinations[index].action;
c.chooseMoveRoute(index);
assert.deepEqual(app.sent.map(a => JSON.parse(a)), [action]);
assert.doesNotThrow(() => engine.tryMove(JSON.stringify(g), app.sent[0], 1));
} finally { app.close(); }
});

View file

@ -0,0 +1,45 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'siegecraft', {})).players.slice(2);
function fixture(attacker = true, defender = true) {
const g = JSON.parse(readFileSync(new URL('../../server/tests/test_games/combat/direct_capture_city_fortress.json', import.meta.url), 'utf8'));
g.players.push(...structuredClone(npcs));
if (attacker) g.players[0].advances.push('Siegecraft');
if (defender) g.players[1].advances.push('Siegecraft');
return g;
}
const move = (g: any, action: any, seat = 0) => JSON.parse(engine.tryMove(JSON.stringify(g), JSON.stringify(action), seat));
const attack = (g: any) => move(g, { Movement: { Move: { units: [0, 1, 2, 3], destination: 'C1' } } });
const siege = (g: any) => g.events?.find((e: any) => e.handler?.origin?.Advance === 'Siegecraft');
test('Siegecraft is never offered to a defender, including after attacker declines', () => {
assert(!siege(attack(fixture(false))));
const g = attack(fixture());
assert.equal(siege(g).player, 0);
const after = move(g, { Response: { Payment: [{}, {}] } });
assert(!siege(after));
});
test('attacker can still pay to cancel both fortress abilities', () => {
const g = attack(fixture());
const after = move(g, { Response: { Payment: [{ wood: 2 }, { ore: 2 }] } });
assert(!siege(after));
assert.equal(after.players[0].resources.wood, g.players[0].resources.wood - 2);
assert.equal(after.players[0].resources.ore, g.players[0].resources.ore - 2);
assert.match(JSON.stringify(after), /Cancel Fortress Extra Die/);
assert.match(JSON.stringify(after), /Cancel Fortress Ignore Hit/);
});
for (const payment of [[{}, {}], [{ gold: 2 }, { gold: 2 }]]) {
test(`saved defender prompt safely resolves ${JSON.stringify(payment)}`, () => {
const g = attack(fixture());
const event = siege(g);
event.player = 1;
event.players_used = [0];
const after = move(g, { Response: { Payment: payment } }, 1);
assert(!siege(after));
assert.equal(after.players[1].resources.gold, g.players[1].resources.gold);
assert.doesNotMatch(JSON.stringify(after), /CancelFortressExtraDie|CancelFortressIgnoreHit|Cancel Fortress Extra Die|Cancel Fortress Ignore Hit/);
assert.match(JSON.stringify(after), /Siegecraft skipped: only the attacker may use it/);
});
}