Log used recruitment discounts and consolidate journal action rows

This commit is contained in:
coyotte508 2026-10-11 22:11:31 +02:00
commit ea97a2634f
19 changed files with 260 additions and 32 deletions

View file

@ -56,7 +56,7 @@ fn sanitation() -> AdvanceBuilder {
if units.settlers > 0 {
// insert at beginning so that it's preferred over gold
cost.info
.add_log(p, "Reduce the cost of 1 Settler to 1 mood token");
.add_log(p, "Used Sanitation for 1 Settler");
cost.cost.conversions.insert(
0,

View file

@ -161,7 +161,7 @@ fn draft() -> AdvanceBuilder {
let pile = ResourcePile::mood_tokens(draft_cost(p.get(game)));
cost.info
.add_log(p, "Reduce the cost of 1 Infantry to 1 mood token");
.add_log(p, "Used Draft for 1 Infantry");
cost.cost.conversions.insert(
0,
PaymentConversion::limited(UnitType::cost(&UnitType::Infantry), pile, 1),

View file

@ -213,7 +213,7 @@ fn mercenaries() -> SpecialAdvanceInfo {
if let Some(c)=cost.cost.conversions.iter_mut().find(|c|c.from.contains(&UnitType::Infantry.cost())){c.from.push(UnitType::Ship.cost());}
else {cost.cost.conversions.insert(0,PaymentConversion::limited(UnitType::Ship.cost(),draft.clone(),1));}
}
if units.ships>0||units.infantry>0 {cost.cost.conversions.push(PaymentConversion::limited(ResourcePile::mood_tokens(1),ResourcePile::gold(1),draft.amount()));cost.info.add_log(p,"Mercenaries: Draft 1 Infantry or Ship with mood or gold");}
if units.ships>0||units.infantry>0 {cost.cost.conversions.push(PaymentConversion::limited(ResourcePile::mood_tokens(1),ResourcePile::gold(1),draft.amount()));cost.info.add_log(p,"Used Mercenaries for recruitment");}
}).build()
}
fn pirate_allies() -> SpecialAdvanceInfo {

View file

@ -65,7 +65,7 @@ fn sparta() -> SpecialAdvanceInfo {
|cost, units, game, p| {
if units.infantry > 0 {
cost.info
.add_log(p, "Can pay the Draft cost as culture tokens");
.add_log(p, "Paid Draft with culture tokens");
cost.cost.conversions.insert(
0,
PaymentConversion::limited(

View file

@ -58,7 +58,7 @@ pub(crate) fn execute_recruit(
r: Recruit,
) -> Result<(), String> {
crate::content::civilizations::carthage::validate_recruit(game, game.player(player_index), &r)?;
let cost = recruit_cost_with_options(
let mut cost = recruit_cost_with_options(
game,
game.player(player_index),
&r.units,
@ -68,6 +68,48 @@ pub(crate) fn execute_recruit(
r.ballcourts,
r.draft_card,
)?;
// Cost listeners describe available substitutions. Keep only a consistent
// set needed to explain the payment actually chosen, not every owned ability.
let candidates = cost
.info
.log
.iter()
.map(|(origin, _)| origin.clone())
.unique()
.collect::<Vec<_>>();
let mut unused = Vec::new();
for origin in candidates {
if !matches!(
origin,
crate::events::EventOrigin::Advance(
crate::advance::Advance::Draft | crate::advance::Advance::Sanitation
) | crate::events::EventOrigin::SpecialAdvance(
SpecialAdvance::Sparta | SpecialAdvance::Mercenaries
)
) {
continue;
}
let mut excluded = unused.clone();
excluded.push(origin.clone());
if recruit_cost_options_excluding(
game,
game.player(player_index),
&r.units,
r.city_position,
game.execute_cost_trigger(),
r.ballcourts,
r.draft_card,
&excluded,
)
.is_ok_and(|without| without.cost.is_valid_payment(&r.payment))
{
unused.push(origin);
}
}
cost.info.log.retain(|(origin, _)| !unused.contains(origin));
cost.cost
.modifiers
.retain(|origin| !unused.contains(origin));
cost.pay(game, &r.payment);
let origin = cost.origin();
for unit in &r.replaced_units {
@ -287,6 +329,29 @@ fn recruit_cost_options(
execute: CostTrigger,
ballcourts: bool,
draft_card: bool,
) -> Result<CostInfo, String> {
recruit_cost_options_excluding(
game,
player,
units,
city_position,
execute,
ballcourts,
draft_card,
&[],
)
}
#[allow(clippy::too_many_arguments)]
fn recruit_cost_options_excluding(
game: &Game,
player: &Player,
units: &Units,
city_position: Position,
execute: CostTrigger,
ballcourts: bool,
draft_card: bool,
excluded: &[crate::events::EventOrigin],
) -> Result<CostInfo, String> {
let city = player.get_city(city_position);
if draft_card
@ -354,7 +419,16 @@ fn recruit_cost_options(
),
);
base_cost.city_position = Some(city_position);
let mut cost = player.trigger_cost_event(|e| &e.recruit_cost, base_cost, units, game, execute);
let mut cost = if excluded.is_empty() {
player.trigger_cost_event(|e| &e.recruit_cost, base_cost, units, game, execute)
} else {
let mut event = player.events.transient.recruit_cost.clone();
for origin in excluded {
event.remove_listener_mut_by_key(origin);
}
event.trigger(&mut base_cost, units, game, &mut ());
base_cost
};
if ballcourts {
cost.cost.default.mood_tokens += 1;
}

View file

@ -37,9 +37,7 @@ const JSON: JsonTest = JsonTest::new("advances");
#[test]
fn test_sanitation_and_draft() {
// we should figure out that sanitation or draft are used, but not both
// actually that code turns out to be too complicated and slow, so the log now says you
// used both
// The payment fits either substitution: the journal should attribute one, not both.
let units = Units::new(1, 1, 0, 0, 0, None);
let city_position = Position::from_offset("A1");
JSON.test(

View file

@ -284,7 +284,7 @@
},
{
"player": 0,
"Text": "Reduce the cost of 1 Infantry to 1 mood token",
"Text": "Used Draft for 1 Infantry",
"origin": {
"Advance": "Draft"
}

View file

@ -315,9 +315,6 @@
"Ability": "Recruit"
},
"modifiers": [
{
"Advance": "Draft"
},
{
"Advance": "Sanitation"
}
@ -325,14 +322,7 @@
},
{
"player": 0,
"Text": "Reduce the cost of 1 Infantry to 1 mood token",
"origin": {
"Advance": "Draft"
}
},
{
"player": 0,
"Text": "Reduce the cost of 1 Settler to 1 mood token",
"Text": "Used Sanitation for 1 Settler",
"origin": {
"Advance": "Sanitation"
}

View file

@ -299,14 +299,14 @@
},
{
"player": 0,
"Text": "Reduce the cost of 1 Infantry to 1 mood token",
"Text": "Used Draft for 1 Infantry",
"origin": {
"Advance": "Draft"
}
},
{
"player": 0,
"Text": "Can pay the Draft cost as culture tokens",
"Text": "Paid Draft with culture tokens",
"origin": {
"SpecialAdvance": "Sparta"
}

View file

@ -271,14 +271,14 @@
},
{
"player": 0,
"Text": "Reduce the cost of 1 Infantry to 1 mood token",
"Text": "Used Draft for 1 Infantry",
"origin": {
"Advance": "Draft"
}
},
{
"player": 0,
"Text": "Can pay the Draft cost as culture tokens",
"Text": "Paid Draft with culture tokens",
"origin": {
"SpecialAdvance": "Sparta"
}

View file

@ -266,7 +266,7 @@
},
{
"player": 0,
"Text": "Reduce the cost of 1 Infantry to 1 mood token",
"Text": "Used Draft for 1 Infantry",
"origin": {
"Advance": "Draft"
}
@ -333,7 +333,7 @@
},
{
"player": 0,
"Text": "Reduce the cost of 1 Infantry to 1 mood token",
"Text": "Used Draft for 1 Infantry",
"origin": {
"Advance": "Draft"
}

View file

@ -165,3 +165,8 @@ Steel Weapons activates and adds combat value only in land battles. Naval battle
Action sounds have a higher master level and longer click/action envelopes; hover cues remain subtle and the existing sound preference still mutes everything.
A Trade Routes icon joins the map guides. It draws the selected civilization's current eligible trade pairings using the engine's reward-route calculation, with a civilization selector, endpoint links and empty/unresearched explanations. It is read-only and mutually exclusive with sea, pirate and barbarian guides. Routes reflect the current board and are recalculated when the player's next turn starts.
# 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.

View file

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

View file

@ -0,0 +1,45 @@
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/sanitation_and_draft.outcome');
state.current_player_index=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:0});host.emit('theme',{dark:true});host.emit('preferences',{sound:false});host.emit('state',state)},engine.stripSecret(JSON.stringify(state),0));
await page.getByRole('button',{name:'Open journal',exact:true}).click();
const panel=page.getByRole('tabpanel',{name:'Journal',exact:true});
await panel.getByText('Recruit',{exact:true}).waitFor();
assert.equal(await panel.getByText('Recruit',{exact:true}).count(),1);
assert.match(await panel.innerText(),/Used Sanitation/);
assert.doesNotMatch(await panel.innerText(),/Used Draft|Reduce the cost/);
await page.screenshot({path:`/tmp/clash-journal-${width}.png`});
assert.deepEqual(await page.evaluate(()=>sent),[]);assert.deepEqual(errors,[]);
await page.close();
}
console.log('Journal desktop/mobile smoke passed');
} finally {await browser.close();}

View file

@ -383,3 +383,34 @@ test('Nomads city movement collapses duplicate origins but keeps rewards, units
] }]));
assert.equal(other.length, 3, 'different actors and routes are not duplicates');
});
test('split action rows collapse without merging different actions or actors', () => {
const action = { action: { Playing: { Recruit: {} } }, log: [
'Leif: Recruit: Gain 1 infantry at A1',
'Leif: Draft: Used Draft for 1 Infantry',
'Leif: Recruit: Pay 1 action, Pay 1 mood token',
'Leif: Medicine: Gain 1 food',
'Aurelia: Recruit: Gain 1 infantry at B2',
] };
const rows = journal(game([action, action]));
const own = rows.filter(row => row.title === 'Recruit' && row.player === 0);
assert.equal(own.length, 2);
assert(own.every(row => row.notes.includes('Used Draft for 1 Infantry')));
assert(own.every(row => row.tokens.some(t => t.icon === 'mood_tokens' && t.value === '−1')));
assert.equal(rows.filter(row => row.title === 'Medicine').length, 2);
assert.equal(rows.filter(row => row.title === 'Recruit' && row.player === 1).length, 2);
});
test('old prose-only recruitment discount offers are not reported as uses', () => {
const rows = journal(game([{ log: [
'Leif: Recruit: Gain 1 infantry at A1',
'Leif: Draft: Reduce the cost of 1 Infantry to 1 mood token',
'Leif: Sanitation: Reduce the cost of 1 Settler to 1 mood token',
'Leif: Sparta: Can pay the Draft cost as culture tokens',
'Leif: Recruit: Pay 1 food, Pay 1 ore',
] }]));
assert.equal(rows.length, 1);
assert.equal(rows[0].title, 'Recruit');
assert(rows[0].tokens.some(t => t.icon === 'food' && t.value === '−1'));
assert(!rows[0].text.includes('mood'));
});

View file

@ -401,6 +401,28 @@ export function journal(
entries.splice(entries.indexOf(duplicate), 1);
}
}
// Payment and results can interleave with bonuses. Consolidate only
// within this action and actor; preserve separate events and combat.
if (!action.combat_stats && !entries.some(entry => entry.event)) {
const primaryTitles = new Set(['Recruit', 'Construct', 'Research', 'Found city', 'Increase Happiness', 'Move']);
for (const primary of [...entries]) {
if (!primaryTitles.has(primary.title) || !entries.includes(primary)) continue;
for (const duplicate of [...entries]) {
if (duplicate === primary || duplicate.player !== primary.player || duplicate.title !== primary.title) continue;
primary.tokens.push(...duplicate.tokens);
primary.notes.push(...duplicate.notes);
entries.splice(entries.indexOf(duplicate), 1);
}
if (primary.title === 'Recruit') {
for (const discount of [...entries]) {
if (discount.player !== primary.player || !['Draft', 'Sanitation', 'Sparta', 'Mercenaries'].includes(discount.title) || discount.tokens.length) continue;
if (!discount.notes.every(note => /^(Used (Draft|Sanitation|Mercenaries)|Paid Draft with culture tokens)/.test(note))) continue;
primary.notes.push(...discount.notes);
entries.splice(entries.indexOf(discount), 1);
}
}
}
}
explainCollection(action, entries, historicalCities.get(id));
for (const entry of entries)
entry.text = [

View file

@ -0,0 +1,60 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { journal } from './journal.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'recruit-journal', {})).players.slice(2);
const fixture = () => {
const game = JSON.parse(readFileSync(new URL('../../server/tests/test_games/advances/sanitation_and_draft.json', import.meta.url), 'utf8'));
for (const npc of npcs) if (!game.players.some((p: any) => p.civilization === npc.civilization)) game.players.push({ ...npc, id: game.players.length });
game.players[0].resources = { food: 7, ore: 7, gold: 7, mood_tokens: 7, culture_tokens: 7 };
return game;
};
for (const [name, units, payment, expected] of [
['normal infantry', { infantry: 1 }, { food: 1, ore: 1 }, []],
['normal settler', { settlers: 1 }, { food: 2 }, []],
['Draft', { infantry: 1 }, { mood_tokens: 1 }, ['Draft']],
['Sanitation', { settlers: 1 }, { mood_tokens: 1 }, ['Sanitation']],
['both substitutions', { infantry: 1, settlers: 1 }, { mood_tokens: 2 }, ['Draft', 'Sanitation']],
['ambiguous substitution', { infantry: 1, settlers: 1 }, { mood_tokens: 1, gold: 2 }, ['Sanitation']],
] as const) test(`recruit journal records only paid substitutions: ${name}`, () => {
const game = fixture();
const action = { Playing: { Recruit: { units, city_position: 'A1', payment } } };
const after = JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify(action), 0));
const actions = after.log.flatMap((a: any) => a.rounds.flatMap((r: any) => r.turns.flatMap((t: any) => t.actions)));
const last = actions.at(-1);
const used = last.items.filter((i: any) => i.Text && ['Draft', 'Sanitation'].includes(i.origin?.Advance)).map((i: any) => i.origin.Advance).sort();
assert.deepEqual(used, [...expected].sort());
const entries = journal(after).filter(e => e.title === 'Recruit');
assert.equal(entries.length, 1, 'Recruitment and payment share one row');
assert(!journal(after).some(e => ['Draft', 'Sanitation'].includes(e.title)));
});
test('historical optional-discount announcements disappear without altering saved records or costs', () => {
const game = JSON.parse(readFileSync(new URL('../../server/tests/test_games/advances/sanitation_and_draft.outcome.json', import.meta.url), 'utf8'));
const items = game.log[0].rounds[0].turns[0].actions[0].items;
items.push({ player: 0, origin: { Advance: 'Draft' }, Text: 'Reduce the cost of 1 Infantry to 1 mood token' });
for (const item of items) if (item.Text === 'Used Sanitation for 1 Settler') item.Text = 'Reduce the cost of 1 Settler to 1 mood token';
const before = JSON.stringify(game);
const rows = journal(game);
assert(!rows.some(row => ['Draft', 'Sanitation'].includes(row.title)));
assert.equal(rows.filter(row => row.title === 'Recruit').length, 1);
assert(rows.some(row => row.tokens.some(t => t.icon === 'mood_tokens' && t.value === '−1')));
assert.equal(JSON.stringify(game), before);
});
for (const [civilization, payment, used] of [
['Greece', { food: 1, ore: 1 }, []],
['Greece', { mood_tokens: 1 }, ['Draft']],
['Greece', { culture_tokens: 1 }, ['Draft', 'Sparta']],
['Carthage', { food: 1, ore: 1 }, []],
['Carthage', { mood_tokens: 1 }, ['Draft']],
['Carthage', { gold: 1 }, ['Draft', 'Mercenaries']],
] as const) test(`recruitment attributes civilization conversions only when needed: ${civilization} ${JSON.stringify(payment)}`, () => {
const game = fixture(); game.players[0].civilization = civilization;
const after = JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify({ Playing: { Recruit: { units: { infantry: 1 }, city_position: 'A1', payment } } }), 0));
const actions = after.log.flatMap((a: any) => a.rounds.flatMap((r: any) => r.turns.flatMap((t: any) => t.actions)));
const actual = actions.at(-1).items.filter((i: any) => i.Text && /Used Draft|Paid Draft|Used Mercenaries/.test(i.Text)).map((i: any) => i.origin.Advance ?? i.origin.SpecialAdvance).sort();
assert.deepEqual(actual, [...used].sort());
});

View file

@ -38,7 +38,10 @@ function source(item: Item, context?: Context): string {
// Keep the journal's presentation parsers at a single boundary. Engine records
// remain structured and immutable; legacy saved logs already contain prose.
function lines(game: Game, action: LoggedAction, context?: Context): string[] {
if (action.log) return action.log;
// Older saves logged optional cost conversions merely for owning the advance.
// Their payment records remain authoritative; do not present those offers as uses.
const offeredDiscount = (text: string) => /(?:^|: )(?:Reduce the cost of 1 (?:Infantry|Settler) to 1 mood token|Can pay the Draft cost as culture tokens|Mercenaries: Draft 1 Infantry or Ship with mood or gold)$/.test(text);
if (action.log) return action.log.filter(line => !offeredDiscount(line));
const result: string[] = [];
const stats = action.combat_stats as { attacker?: { player?: number } } | undefined;
let attacker = stats?.attacker?.player;
@ -54,7 +57,7 @@ function lines(game: Game, action: LoggedAction, context?: Context): string[] {
for (const item of action.items ?? []) {
const origin = source(item, context);
const write = (text: string) => add(item.player, origin, text);
if (item.Text !== undefined) {
if (item.Text !== undefined && !offeredDiscount(item.Text)) {
const event = item.Text.match(/^triggers the event (.+)$/);
if (event) result.push(`A new game event has been triggered: ${event[1]}`);
else if (item.Text === 'wins the battle')