Preserve Mercenaries recruitment alternatives through Warbeasts

This commit is contained in:
coyotte508 2026-11-11 10:23:01 +00:00
commit fb80f1f1b9
7 changed files with 325 additions and 5 deletions

View file

@ -193,13 +193,23 @@ fn warbeasts() -> SpecialAdvanceInfo {
let city=p.get(game).get_city(cost.city_position.unwrap());
cost.cost.conversions.push(PaymentConversion::resource_options(vec![ResourcePile::food(1)],ResourcePile::culture_tokens(1),PaymentConversionType::MayNotOverpay(units.elephants * UnitType::Elephant.cost().amount())));
if city.pieces.market.is_none(){
let base=cost.cost.default.clone();let elephant=UnitType::Elephant.cost();let mut alternatives=vec![base];
// Earlier listeners (notably Mercenaries) provide complete alternative
// costs. Apply the mandatory replacement to every branch, not only
// the regular price, and keep the transformed regular price first.
let elephant=UnitType::Elephant.cost();
let mut alternatives=std::iter::once(cost.cost.default.clone())
.chain(cost.cost.alternatives.clone()).collect::<Vec<_>>();
for _ in 0..units.elephants{
alternatives=alternatives.into_iter().flat_map(|base|elephant.types().into_iter().filter_map(move |kind|{
(base.get(&kind)>0).then(||{let mut c=base.clone();c.add_type(kind,-1);c.gold+=1;c})
})).collect();
}
alternatives.sort_by_key(|r|r.to_string());alternatives.dedup();cost.cost.default=alternatives.remove(0);cost.cost.alternatives=alternatives;
let mut seen=HashSet::new();
alternatives.retain(|base|seen.insert(base.clone()));
if let Some((default,others))=alternatives.split_first(){
cost.cost.default=default.clone();
cost.cost.alternatives=others.to_vec();
}
cost.cost.conversions.push(PaymentConversion::limited(ResourcePile::gold(1),ResourcePile::culture_tokens(1),units.elephants));
cost.info.add_log(p,"Warbeasts: pay at least 1 gold or culture per Elephant instead of a normal resource");
}

View file

@ -0,0 +1,164 @@
//! Warbeasts must transform every earlier Draft/Mercenaries price branch.
use server::{
cache::Cache,
game::{Game, GameContext},
game_data::GameData,
leader::Leader,
payment::PaymentOptions,
player::CostTrigger,
position::Position,
recruit::recruit_cost_without_replaced,
resource_pile::ResourcePile as R,
unit::Units,
};
fn cost(
elephants: u8,
ships: u8,
infantry: u8,
market: bool,
liberties: bool,
leader: bool,
) -> PaymentOptions {
let mut data: serde_json::Value = serde_json::from_str(include_str!(
"test_games/civilizations/greece/sparta_draft.json"
))
.unwrap();
let p = &mut data["players"][0];
p["civilization"] = "Carthage".into();
p["available_leaders"] = serde_json::json!(["Hanno"]);
p["advances"] = serde_json::json!(["Draft", "Husbandry", "Fishing", "Tactics"]);
if liberties {
p["advances"]
.as_array_mut()
.unwrap()
.push("CivilLiberties".into());
}
p["cities"][0]["city_pieces"] = serde_json::json!({"port":0,"temple":0,"fortress":0});
p["cities"][0]["port_position"] = "C3".into();
if market {
p["cities"][0]["city_pieces"]["market"] = 0.into();
}
let data: GameData = serde_json::from_value(data).unwrap();
let cache = Cache::new(&data.options);
let game = Game::from_data(data, cache, GameContext::Play);
recruit_cost_without_replaced(
&game,
game.player(0),
&Units::new(
0,
infantry,
ships,
0,
elephants,
leader.then_some(Leader::Hanno),
),
Position::from_offset("A1"),
CostTrigger::NoModifiers,
)
.unwrap()
.cost
}
fn legal(cost: &PaymentOptions, payment: R) {
assert!(
cost.is_valid_payment(&payment),
"not legal: {payment:?}, cost {cost:?}"
);
assert_eq!(cost.first_valid_payment(&payment), Some(payment));
}
#[test]
fn warbeasts_preserves_all_mercenaries_branches_with_and_without_market() {
for market in [false, true] {
for infantry in [false, true] {
let cost = cost(
1,
u8::from(!infantry),
u8::from(infantry),
market,
false,
false,
);
// One regular branch and exactly two Draft branches; no cross-product
// of payments, duplicate alternatives, or untransformed leftovers.
assert_eq!(cost.alternatives.len(), 2);
let branches = std::iter::once(&cost.default)
.chain(&cost.alternatives)
.collect::<std::collections::HashSet<_>>();
assert_eq!(branches.len(), 3);
if !market {
assert!(branches.iter().all(|price| price.gold >= 1));
}
legal(&cost, R::food(1) + R::gold(2));
legal(&cost, R::food(1) + R::gold(1) + R::mood_tokens(1));
legal(&cost, R::food(1) + R::culture_tokens(1) + R::gold(1));
let undiscounted = R::food(2)
+ if infantry {
R::food(1) + R::ore(1)
} else {
R::wood(2)
};
assert_eq!(cost.is_valid_payment(&undiscounted), market);
assert_eq!(
cost.is_valid_payment(&(R::food(2) + R::mood_tokens(1))),
market
);
}
}
}
#[test]
fn warbeasts_requires_each_elephant_and_mercenaries_drafts_only_one_unit() {
let two_ships = cost(1, 2, 0, false, false, false);
legal(&two_ships, R::food(1) + R::gold(2) + R::wood(2));
assert!(!two_ships.is_valid_payment(&(R::food(1) + R::gold(3))));
let two_elephants = cost(2, 1, 0, false, false, false);
legal(&two_elephants, R::food(2) + R::gold(3));
legal(
&two_elephants,
R::food(2) + R::culture_tokens(2) + R::mood_tokens(1),
);
assert!(!two_elephants.is_valid_payment(&(R::food(3) + R::gold(1) + R::mood_tokens(1))));
assert!(!two_elephants.is_valid_payment(&(R::food(4) + R::mood_tokens(1))));
}
#[test]
fn warbeasts_keeps_civil_liberties_mixed_tokens_and_reserved_leader_mood() {
for infantry in [false, true] {
let cost = cost(
1,
u8::from(!infantry),
u8::from(infantry),
false,
true,
true,
);
legal(
&cost,
R::food(1) + R::gold(2) + R::mood_tokens(2) + R::culture_tokens(1),
);
legal(
&cost,
R::food(1) + R::gold(3) + R::mood_tokens(1) + R::culture_tokens(1),
);
assert!(!cost.is_valid_payment(&(R::food(1) + R::gold(4) + R::culture_tokens(1))));
}
}
#[test]
fn ship_only_regular_default_and_elephant_only_remain_unchanged() {
let ship = cost(0, 1, 0, false, false, false);
assert_eq!(ship.default, R::wood(2));
legal(&ship, R::gold(1));
legal(&ship, R::mood_tokens(1));
assert_eq!(
ship.first_valid_payment(&(R::wood(2) + R::gold(2))),
Some(R::wood(2))
);
let elephant = cost(1, 0, 0, false, false, false);
assert_eq!(elephant.default, R::food(1) + R::gold(1));
assert!(elephant.alternatives.is_empty());
legal(&elephant, R::food(1) + R::culture_tokens(1));
assert!(!elephant.is_valid_payment(&R::food(2)));
}

View file

@ -1227,3 +1227,17 @@ 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.
# Viewer 0.1.214 / engine 0.4.146
Carthage's Warbeasts now applies its mandatory gold-or-culture replacement to
all existing recruitment prices, preserving Mercenaries' one-unit Draft
alternatives when Elephants and Ships or Infantry are recruited together without
a Market. Every branch still replaces at least one resource per Elephant; the
regular price remains the default branch. Civil Liberties' mixed gold/mood
payments and leaders' reserved mood costs remain separate. With a Market,
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.

View file

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

View file

@ -0,0 +1,87 @@
// Synthetic/offline real-engine and production-viewer combined recruitment check.
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');
let raw = await engine.init(2, [], { civilization: 'ChooseCivilization' }, 'carthage-combined-recruit', {});
for (const civilization of ['Carthage', 'Rome'])
raw = engine.tryMove(raw, JSON.stringify({ ChooseCivilization: civilization }), engine.currentPlayer(raw));
const initial = JSON.parse(raw), seat = engine.currentPlayer(raw), p = initial.players[seat];
p.advances.push('Husbandry', 'Draft', 'Fishing', 'Tactics');
p.cities = [{ position: 'D2', mood_state: 'Happy', city_pieces: { port: seat }, port_position: 'D3' }];
p.units = [];
for (const tile of initial.map.tiles) tile[1] = tile[0] === 'D2' ? 'Fertile' : 'Water';
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
for (const width of [1400, 390]) {
for (const payment of [
{ food: 1, gold: 2 },
{ food: 1, gold: 1, mood_tokens: 1 },
{ food: 1, gold: 1, culture_tokens: 1 },
]) {
const state = structuredClone(initial);
// Keep the regular payment available too, so the picker must be used.
state.players[seat].resources = { wood: 2, ...payment };
const stripped = engine.stripSecret(JSON.stringify(state), seat);
const offer = JSON.parse(engine.webQuery(stripped, seat, JSON.stringify({
kind: 'recruit', city: 'D2', units: { elephants: 1, ships: 1 }, replaced: [], payment,
})));
assert.deepEqual(offer.payment, payment);
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: 'Manage cities', exact: true }).click();
const city = page.getByRole('dialog');
await city.getByRole('button', { name: 'Recruit', exact: true }).click();
await city.getByRole('button', { name: 'Add Elephant', exact: true }).click();
await city.getByRole('button', { name: 'Add Ship', exact: true }).click();
const picker = city.getByRole('group', { name: 'Recruitment payment', exact: true });
await picker.waitFor();
if (await picker.locator('select').count()) {
await picker.getByLabel('Wood amount for Recruitment payment', { exact: true }).selectOption('0');
if (payment.culture_tokens)
await picker.getByLabel('Culture amount for Recruitment payment', { exact: true }).selectOption('1');
if (payment.mood_tokens)
await picker.getByLabel('Mood amount for Recruitment payment', { exact: true }).selectOption('1');
await picker.getByLabel('Food amount for Recruitment payment', { exact: true }).selectOption('1');
await picker.getByLabel('Gold amount for Recruitment payment', { exact: true }).selectOption(String(payment.gold));
} else {
const name = 'Pay ' + Object.entries(offer.payment).map(([key, value]) =>
`${value} ${key === 'mood_tokens' ? 'mood' : key === 'culture_tokens' ? 'culture' : key}`).join(' + ');
await picker.getByRole('button', { name, exact: true }).click();
}
await page.evaluate((state) => host.emit('state', state), stripped);
assert.deepEqual(await page.evaluate(() => sent), []);
await city.getByRole('button', { name: 'Recruit 2 units', exact: true }).click();
await page.waitForFunction(() => sent.length === 1);
const action = await page.evaluate(() => sent[0]);
assert.deepEqual(action.Playing.Recruit.payment, payment);
const after = JSON.parse(engine.tryMove(JSON.stringify(state), JSON.stringify(action), seat));
assert.equal(after.players[seat].units.filter((u) => u.unit_type === 'Elephant').length, 1);
assert.equal(after.players[seat].units.filter((u) => u.unit_type === 'Ship').length, 1);
for (const [key, amount] of Object.entries(payment))
assert.equal(after.players[seat].resources[key] ?? 0, state.players[seat].resources[key] - amount);
assert.deepEqual(errors, []);
console.log(`${width}px: combined Elephant + Ship ${JSON.stringify(payment)} selected, retained and executed`);
await page.close();
}
}
} finally { await browser.close(); }

View file

@ -1180,6 +1180,51 @@ test('Warbeasts replaces a resource per Elephant and Mercenaries drafts ships',
});
assert.equal(ship.players[seat(sea)].units.filter((u: any) => u.unit_type === 'Ship').length, 2);
});
test('Warbeasts and Mercenaries offer and execute combined Elephant and Ship payments', async () => {
for (const market of [false, true]) {
const g = await carthageSea(), index = seat(g), p = g.players[index];
addAdvance(p, 'Draft', 'Husbandry');
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: [] });
for (const payment of [
{ food: 1, gold: 2 },
{ food: 1, gold: 1, mood_tokens: 1 },
{ food: 1, culture_tokens: 1, gold: 1 },
]) {
assert.ok(offer.payments.some((candidate: any) =>
Object.entries(payment).every(([key, value]) => candidate[key] === value) &&
Object.keys(candidate).length === Object.keys(payment).length));
const selected = query(g, { kind: 'recruit', city: 'D2', units, replaced: [], payment });
assert.deepEqual(selected.payment, payment);
const after = move(g, selected.action), ap = after.players[index];
assert.equal(ap.units.filter((u: any) => u.unit_type === 'Elephant').length, 1);
assert.equal(ap.units.filter((u: any) => u.unit_type === 'Ship').length, 2);
for (const [key, value] of Object.entries(p.resources))
assert.equal(ap.resources[key] ?? 0, Number(value) - ((payment as any)[key] ?? 0));
}
if (!market) {
for (const payment of [{ food: 2, wood: 2 }, { food: 2, mood_tokens: 1 }])
assert.throws(() => query(g, { kind: 'recruit', city: 'D2', units, replaced: [], payment }));
}
const ship = query(g, { kind: 'recruit', city: 'D2', units: { ships: 1 }, replaced: [] });
assert.deepEqual(ship.payment, { wood: 2 }, 'Do not broaden default-payment discount policy');
}
});
test('Warbeasts and Mercenaries retain Sanitation for a separately recruited Settler', async () => {
const g = await carthageSea(), index = seat(g), p = g.players[index];
addAdvance(p, 'Draft', 'Husbandry', 'Sanitation');
p.cities[0].city_pieces.temple = index;
const payment = { food: 1, gold: 1, mood_tokens: 2 };
const offer = query(g, { kind: 'recruit', city: 'D2',
units: { settlers: 1, ships: 1, elephants: 1 }, replaced: [], payment });
assert.deepEqual(offer.payment, payment);
assert.ok(offer.payments.some((candidate: any) => candidate.food === 1 &&
candidate.gold === 1 && candidate.mood_tokens === 2 && Object.keys(candidate).length === 3));
const after = move(g, offer.action);
assert.equal(after.players[index].units.length, p.units.length + 3);
assert.equal(after.players[index].resources.mood_tokens, p.resources.mood_tokens - 2);
});
test('Pirate Allies offers peaceful entry and attack, holds extra ships, and releases them when unescorted', async () => {
const g = await carthageSea(),
index = seat(g);