Prefer advantageous cultural influence sources and preserve explicit choices

This commit is contained in:
coyotte508 2026-11-03 23:43:21 +00:00
commit 989075f4eb
14 changed files with 956 additions and 22 deletions

View file

@ -592,15 +592,35 @@ fn influence_culture(game: &mut Game, influencer_index: usize, info: &InfluenceC
influence_success(game, influencer_index, info);
}
fn influence_success(game: &mut Game, influencer_index: usize, info: &InfluenceCultureAttemptInfo) {
/// Rewards that depend on the selected source, not on the target or the roll.
/// Shared by successful resolution and the read-only source preview; universal
/// success rewards such as Conversion remain in their resolve listeners.
pub(crate) fn source_success_rewards(
game: &Game,
player: usize,
starting_position: Position,
) -> Vec<(EventOrigin, ResourcePile)> {
if crate::content::civilizations::phoenicia::leader_at(
game.player(influencer_index),
game.player(player),
crate::leader::Leader::Darius,
info.starting_city_position,
starting_position,
) {
vec![(
EventOrigin::LeaderAbility("Cultural Unity".into()),
ResourcePile::mood_tokens(1),
)]
} else {
vec![]
}
}
fn influence_success(game: &mut Game, influencer_index: usize, info: &InfluenceCultureAttemptInfo) {
for (origin, resources) in
source_success_rewards(game, influencer_index, info.starting_city_position)
{
info.player(influencer_index)
.with_origin(EventOrigin::LeaderAbility("Cultural Unity".into()))
.gain_resources(game, ResourcePile::mood_tokens(1));
.with_origin(origin)
.gain_resources(game, resources);
}
let city_position = info.position;
game.trigger_transient_event_with_game_value(

View file

@ -421,6 +421,13 @@ pub fn special(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
}).collect()
}
fn influence_source_success_rewards(game: &Game, seat: usize, source: Position) -> Vec<Value> {
crate::cultural_influence::source_success_rewards(game, seat, source)
.into_iter()
.map(|(origin, resources)| json!({"name":origin.name(game),"resources":resources}))
.collect()
}
pub fn influence(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
use crate::cultural_influence::{
InfluenceCultureAttempt, available_influence_actions, available_influence_culture,
@ -440,6 +447,7 @@ pub fn influence(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
attempt.starting_position = Some(origin);
Some(json!({"position":origin,"settlers":game.try_get_any_city(origin).is_none(),
"reroll":crate::content::civilizations::india::buddhism_available(game,seat,&from),
"successRewards":influence_source_success_rewards(game,seat,from.starting_city_position),
"free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":from.range_boost_cost.default_payment(),
"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(attempt))}))
}).collect::<Vec<_>>();
@ -474,7 +482,9 @@ pub fn influence(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
let origins=influence_start_positions(game,game.player(seat)).into_iter().filter_map(|(pos,_)| {
let mut selected=attempt.clone();selected.starting_position=Some(pos);
let from=crate::cultural_influence::unit_influence_cost(game,seat,&selected,true).ok()?;
Some(json!({"position":pos,"settlers":false,"reroll":false,"free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":from.range_boost_cost.default_payment(),"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(selected))}))
Some(json!({"position":pos,"settlers":false,"reroll":false,
"successRewards":influence_source_success_rewards(game,seat,from.starting_city_position),
"free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":from.range_boost_cost.default_payment(),"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(selected))}))
}).collect::<Vec<_>>();
offers.push(json!({"name":format!("{} · {} #{}",owner.civilization.name,unit.unit_type.non_leader_name(),unit.id+1),"position":unit.position,"origin":info.starting_city_position,"variant":"Zoroastrianism","free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":info.roll_boost,"preventBoost":info.prevent_boost,"payment":info.range_boost_cost.default_payment(),"origins":origins,"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(attempt))}));
}

View file

@ -0,0 +1,308 @@
use serde_json::{Value, json};
use server::action::{Action, execute_action};
use server::cache::Cache;
use server::city_pieces::Building;
use server::content::persistent_events::EventResponse;
use server::events::EventOrigin;
use server::game::{Game, GameContext};
use server::game_data::GameData;
use server::leader::Leader;
use server::log::{ActionLogBalance, ActionLogEntry};
use server::map::Terrain;
use server::position::Position;
use server::resource_pile::ResourcePile;
use server::unit::UnitType;
use server::web_view;
fn source() -> Position {
Position::from_offset("C3")
}
fn other_source() -> Position {
source().neighbors()[0]
}
fn target() -> Position {
source().neighbors()[1]
}
fn fixture(unit_target: bool) -> Game {
let mut data: Value =
serde_json::from_str(include_str!("test_games/base/recruit.json")).unwrap();
let p = &mut data["players"][0];
p["civilization"] = json!("Persia");
p["advances"] = json!(["Farming", "Mining", "Writing", "Myths", "Priesthood"]);
p["available_leaders"] = json!(["Cyrus", "Xerxes"]);
p["cities"] = json!([
{"position":source(), "mood_state":"Happy", "city_pieces":{"academy":0}},
{"position":other_source(), "mood_state":"Happy", "city_pieces":{"academy":0}}
]);
p["units"] = json!([
{"id":0, "position":source(), "unit_type":{"Leader":"Darius"}}
]);
p["next_unit_id"] = json!(1);
p["resources"] = json!({"food":2,"wood":7,"ore":7,"ideas":7,"gold":7,
"mood_tokens":7,"culture_tokens":7});
p["resource_limit"] = p["resources"].clone();
p["objective_cards"] = json!([]);
let p = &mut data["players"][1];
p["objective_cards"] = json!([]);
p["cities"] = json!([{
"position":if unit_target { source().neighbors()[2] } else { target() },
"mood_state":"Happy", "city_pieces":{"temple":1}
}]);
p["units"] = if unit_target {
json!([{"id":0,"position":target(),"unit_type":"Infantry"}])
} else {
json!([])
};
p["next_unit_id"] = json!(1);
data["players"].as_array_mut().unwrap().extend([
json!({"id":2,"civilization":"Barbarians","next_unit_id":0}),
json!({"id":3,"civilization":"Pirates","next_unit_id":0}),
]);
data["actions_left"] = json!(3);
data["dice_roll_outcomes"] = json!([10]); // A successful roll of 6.
let data: GameData = serde_json::from_value(data).unwrap();
let cache = Cache::new(&data.options);
let mut game = Game::from_data(data, cache, GameContext::Play);
game.map.tiles.clear();
game.map.unexplored_blocks.clear();
for position in std::iter::once(source()).chain(source().neighbors()) {
game.map.tiles.insert(position, Terrain::Fertile);
}
game
}
fn offer(game: &Game, unit_target: bool) -> Value {
web_view::view(game, Some(0))["influence"]
.as_array()
.unwrap()
.iter()
.find(|offer| {
offer["position"] == json!(target())
&& if unit_target {
offer["variant"] == "Zoroastrianism"
} else {
offer["name"] == "Temple"
}
})
.expect("influence target must be offered")
.clone()
}
fn origin(offer: &Value, position: Position) -> &Value {
offer["origins"]
.as_array()
.unwrap()
.iter()
.find(|origin| origin["position"] == json!(position))
.expect("source must be offered")
}
fn cultural_unity_reward() -> Value {
json!([{"name":"Cultural Unity","resources":ResourcePile::mood_tokens(1)}])
}
fn play_origin(game: Game, origin: &Value) -> Game {
assert_eq!(origin["payment"], json!({}), "fixture needs no range boost");
let action: Action = serde_json::from_value(origin["action"].clone()).unwrap();
assert!(
!serde_json::to_string(&action)
.unwrap()
.contains("successRewards"),
"reward previews must not alter the serialized action schema"
);
execute_action(game, action, 0)
}
fn logged_source_rewards(game: &Game) -> Value {
let rewards: Vec<Value> = game
.log
.iter()
.flat_map(|age| &age.rounds)
.flat_map(|round| &round.turns)
.flat_map(|turn| &turn.actions)
.flat_map(|action| &action.items)
.filter(|item| item.origin == EventOrigin::LeaderAbility("Cultural Unity".into()))
.map(|item| {
assert_eq!(item.player, 0);
let ActionLogEntry::Resources {
resources,
balance: ActionLogBalance::Gain,
} = &item.entry
else {
panic!("Cultural Unity must retain its resource gain log entry")
};
json!({"name":item.origin.name(game),"resources":resources})
})
.collect();
json!(rewards)
}
fn assert_target_owner(game: &Game, unit_target: bool, success: bool) {
if unit_target {
let owner = usize::from(!success);
assert!(
game.player(owner)
.units
.iter()
.any(|unit| { unit.position == target() && unit.unit_type == UnitType::Infantry })
);
assert!(
!game
.player(1 - owner)
.units
.iter()
.any(|unit| { unit.position == target() && unit.unit_type == UnitType::Infantry })
);
} else {
assert_eq!(
game.get_any_city(target())
.pieces
.building_owner(Building::Temple),
Some(usize::from(!success))
);
}
assert_eq!(game.successful_cultural_influence, success);
}
#[test]
fn structure_and_unit_source_previews_match_successful_awards_and_logs() {
for unit_target in [false, true] {
for starting_position in [source(), other_source()] {
let game = fixture(unit_target);
let saved = serde_json::to_value(game.cloned_data()).unwrap();
let preview = offer(&game, unit_target);
assert_eq!(offer(&game, unit_target), preview);
assert_eq!(serde_json::to_value(game.cloned_data()).unwrap(), saved);
assert_eq!(
origin(&preview, source())["successRewards"],
cultural_unity_reward()
);
assert_eq!(
origin(&preview, other_source())["successRewards"],
json!([])
);
let selected = origin(&preview, starting_position);
let rewards = selected["successRewards"].clone();
let mood = game.player(0).resources.mood_tokens;
let game = play_origin(game, selected);
assert!(game.events.is_empty());
assert_target_owner(&game, unit_target, true);
assert_eq!(logged_source_rewards(&game), rewards);
assert_eq!(
game.player(0).resources.mood_tokens,
mood + u8::from(starting_position == source()),
"Cultural Unity applies only at Darius' exact source, even above resource_limit"
);
}
}
}
#[test]
fn moved_missing_and_replaced_leaders_do_not_reward_the_old_source() {
for unit_target in [false, true] {
for state in ["moved", "missing", "replaced"] {
let mut game = fixture(unit_target);
match state {
"moved" => game.player_mut(0).get_unit_mut(0).position = other_source(),
"missing" => game.player_mut(0).units.clear(),
"replaced" => {
game.player_mut(0).get_unit_mut(0).unit_type = UnitType::Leader(Leader::Xerxes);
}
_ => unreachable!(),
}
// These are setup changes; rebuild the leader listeners as on load.
let game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play);
let preview = offer(&game, unit_target);
assert_eq!(origin(&preview, source())["successRewards"], json!([]));
assert_eq!(
origin(&preview, other_source())["successRewards"],
if state == "moved" {
cultural_unity_reward()
} else {
json!([])
}
);
let mood = game.player(0).resources.mood_tokens;
let game = play_origin(game, origin(&preview, source()));
assert_target_owner(&game, unit_target, true);
assert_eq!(game.player(0).resources.mood_tokens, mood);
assert_eq!(logged_source_rewards(&game), json!([]));
}
}
}
#[test]
fn source_rewards_are_conditional_on_success_including_paid_roll_boosts() {
for unit_target in [false, true] {
for accept_boost in [false, true] {
let mut game = fixture(unit_target);
game.dice_roll_outcomes = vec![0]; // Roll 1, followed by an optional +4 boost.
let preview = offer(&game, unit_target);
assert_eq!(
origin(&preview, source())["successRewards"],
cultural_unity_reward()
);
let mood = game.player(0).resources.mood_tokens;
let game = play_origin(game, origin(&preview, source()));
assert!(game.current_event_handler().is_some());
assert_eq!(game.player(0).resources.mood_tokens, mood);
assert_eq!(logged_source_rewards(&game), json!([]));
let payment = if accept_boost {
ResourcePile::culture_tokens(4)
} else {
ResourcePile::empty()
};
let game = execute_action(
game,
Action::Response(EventResponse::Payment(vec![payment])),
0,
);
assert!(game.events.is_empty());
assert_target_owner(&game, unit_target, accept_boost);
assert_eq!(
game.player(0).resources.mood_tokens,
mood + u8::from(accept_boost)
);
assert_eq!(
logged_source_rewards(&game),
if accept_boost {
cultural_unity_reward()
} else {
json!([])
}
);
}
}
}
#[test]
fn universal_conversion_reward_is_not_listed_as_a_source_reward() {
for unit_target in [false, true] {
for starting_position in [source(), other_source()] {
let mut game = fixture(unit_target);
game.player_mut(0)
.advances
.insert(server::advance::Advance::Conversion);
let game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play);
let preview = offer(&game, unit_target);
let selected = origin(&preview, starting_position);
assert_eq!(selected["rollBonus"], 1);
assert_eq!(
selected["successRewards"],
if starting_position == source() {
cultural_unity_reward()
} else {
json!([])
}
);
let culture = game.player(0).resources.culture_tokens;
let game = play_origin(game, selected);
assert_target_owner(&game, unit_target, true);
assert_eq!(game.player(0).resources.culture_tokens, culture + 1);
assert_eq!(logged_source_rewards(&game), selected["successRewards"]);
}
}
}

View file

@ -864,3 +864,36 @@ Repeated awards to the same player remain legal while they have capacity; normal
waste remains possible only when all eligible opponents are full. The active
player and NPC Barbarians/Pirates do not count as recipients. Fixed rewards for
all players are unchanged.
## Viewer 0.1.197 / engine 0.4.132: benefit-aware cultural-influence sources
Reselecting the same influence destination—through the map or its building
button—keeps an explicitly selected source while it remains eligible. Clicking
an already selected target's hex no longer clears its building/source when the
hex has multiple buildings. Changing the destination or losing source eligibility
still resets the choice. Switching between Arts and ordinary influence for the
same destination also preserves a valid source.
At equal upfront resource and action cost, defaults compare the exact chance of
success without paying for a roll boost (including roll bonuses and an available
Buddhism reroll), then the option to boost, then source-dependent success rewards.
Darius's city therefore wins otherwise equivalent attempts for Cultural Unity's
extra mood token, including Arts and Zoroastrianism unit conversion. The source
buttons and payment summary show that bonus. Payment buttons grow to fit wrapped
labels and boost limits on narrow screens. Common rewards such as Conversion
and Code of Laws do not distinguish sources. Mood tokens have no storage cap.
The existing reclaim preference for another boostable city remains, even if it
has a range fee; outside that existing exception the default does not buy extra
range or spend an extra action for a potential benefit. Explicit choices always
win, including a city without Ashoka or Darius. Equal outcomes retain stable
ordering. Cheaper-source recommendations no longer suggest sacrificing success
chances, boosting, or a source reward merely to save range cost.
The engine supplies source-dependent success rewards through the same pure
helper used to grant them, with no RNG inspection or state mutation. This changes
preview metadata and selection, not influence rules, saved states or history.
Regression coverage includes real Arts and unit conversions, Darius's exact
position, moved/missing leaders, uncapped rewards, Ashoka plus Conversion and
used rerolls, manual selections, map/list reselection, and English/French desktop
and mobile browser flows. Publish the matching viewer and engine together.

View file

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

View file

@ -0,0 +1,281 @@
// Run after `npm run build` in web-client:
// node scripts/ashoka-influence-smoke.mjs
// Exercise Ashoka and Darius in the shipped viewer and local authoritative engine.
// Every HTTP request is intercepted; no live game, CDN, or development server is
// contacted. Screenshots are written only under /tmp.
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 base = JSON.parse(await readFile(
new URL('../../server/tests/test_games/base/cultural_influence_instant.json', import.meta.url),
'utf8',
));
const fresh = JSON.parse(await engine.init(2, [], {}, 'ashoka-influence-smoke', {}));
const stripped = (state) => engine.stripSecret(JSON.stringify(state), 0);
const view = (state) => JSON.parse(engine.webView(stripped(state), 0));
const move = (state, action) => JSON.parse(engine.tryMove(
JSON.stringify(state), JSON.stringify(action), 0,
));
const unity = [{ name: 'Cultural Unity', resources: { mood_tokens: 1 } }];
function fixture(leader) {
const game = structuredClone(base);
// Older saved fixtures omit NPCs required by the current engine.
game.players = [...game.players.slice(0, 2), ...structuredClone(fresh.players.slice(2))];
game.current_player_index = 0;
// Stored outcome 10 is a die roll of 6. Ashoka first rolls raw 2 + Conversion.
game.dice_roll_outcomes = leader === 'Ashoka' ? [10, 2] : [10];
const player = game.players[0];
player.civilization = leader === 'Ashoka' ? 'India' : 'Persia';
player.advances.push('Arts', ...(leader === 'Ashoka'
? ['Myths', 'StateReligion', 'Dogma', 'Conversion']
: ['Myths', 'Priesthood']));
player.cities = ['A1', 'C2'].map((position) => ({
position, mood_state: 'Happy', city_pieces: { temple: 0 },
}));
player.units = [{ id: 0, position: 'C2', unit_type: { Leader: leader } }];
player.next_unit_id = 1;
if (leader === 'Darius') player.resources.mood_tokens = 12; // The reward must not be capped at 7.
game.players[1].cities[0].city_pieces = { market: 1 };
const offers = view(game).influence.filter((offer) => offer.position === 'C1' && offer.name === 'Market');
const arts = offers.find((offer) => offer.variant === 'Arts');
assert(arts, `${leader}: the fixture must offer Arts against the Market at C1`);
for (const offer of offers) {
const ordinary = offer.origins.find((from) => from.position === 'A1');
const special = offer.origins.find((from) => from.position === 'C2');
assert(ordinary && special, `${leader}: both temple cities must be eligible sources`);
assert.deepEqual(ordinary.payment, special.payment, `${leader}: both sources have the same range cost`);
assert.deepEqual(ordinary.actionPayment, special.actionPayment, `${leader}: both sources have the same action fee`);
assert.equal(ordinary.free, special.free, `${leader}: the source benefit must not cost an extra action`);
assert.equal(ordinary.rollBonus, special.rollBonus, `${leader}: both sources have the same roll bonus`);
assert.equal(ordinary.preventBoost, special.preventBoost, `${leader}: both sources have the same boostability`);
assert.equal(ordinary.reroll, false, 'A1 has no Ashoka');
assert.equal(special.reroll, leader === 'Ashoka', `${leader}: only Ashoka offers the Buddhism reroll`);
assert.deepEqual(ordinary.successRewards, [], `${leader}: A1 offers no source success reward`);
assert.deepEqual(special.successRewards, leader === 'Darius' ? unity : [],
`${leader}: only Darius' exact city offers Cultural Unity`);
}
const selected = arts.origins.find((from) => from.position === 'C2');
assert.equal(selected.rollBonus, leader === 'Ashoka' ? 1 : 0, 'Only Conversion adds one to the die');
return { leader, game, selected };
}
const fixtures = ['Ashoka', 'Darius'].map(fixture);
const french = JSON.parse(await readFile(new URL('../dist/fr.json', import.meta.url), 'utf8'));
for (const key of [
'Cultural influence', 'Change source', 'Choose payment', 'Influence payment method',
'Arts', 'Reroll with Buddhism', 'Keep this roll', 'Cultural Unity', 'Mood',
]) {
assert.equal(typeof french[key], 'string', `The shipped French catalog must contain ${key}`);
assert(french[key], `The shipped French translation must not be empty: ${key}`);
}
for (const key of ['Reroll with Buddhism', 'Keep this roll', 'Cultural Unity']) {
assert.notEqual(french[key], key);
}
const origin = 'http://clash.test';
const assets = new Map(await Promise.all([
['viewer.js', 'text/javascript'],
['server_bg.wasm', 'application/wasm'],
['fr.json', 'application/json'],
].map(async ([name, contentType]) => [
`/${name}`,
{ contentType, body: await readFile(new URL(`../dist/${name}`, import.meta.url)) },
])));
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
const frame = (page) => page.evaluate(() => new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(resolve));
}));
const sentMoves = (page) => page.evaluate(() => window.sentMoves);
async function smoke({ leader, game, selected }, width, height, locale) {
const label = `${leader} ${width}px ${locale}`;
const text = (key) => locale === 'fr' ? french[key] : key;
const page = await browser.newPage({ viewport: { width, height }, serviceWorkers: 'block' });
page.setDefaultTimeout(15000);
const errors = [], unexpectedRequests = [];
page.on('pageerror', (error) => errors.push(error.message));
try {
await page.route('**/*', async (route) => {
const url = new URL(route.request().url());
// Match the localization smokes: optional display fonts are stubbed,
// not downloaded. All other requests must be one of our local assets.
if (url.origin === 'https://fonts.googleapis.com' && url.pathname === '/css2') {
return route.fulfill({ contentType: 'text/css', body: '' });
}
if (url.origin === origin && 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>',
});
}
const asset = url.origin === origin && assets.get(url.pathname);
if (asset) return route.fulfill(asset);
unexpectedRequests.push(url.href);
return route.abort();
});
await page.goto(`${origin}/`);
await page.evaluate(({ state, locale }) => {
window.host = clash3d.launch('#app');
window.sentMoves = [];
host.on('move', (action) => window.sentMoves.push(JSON.parse(action)));
host.emit('player', { index: 0 });
host.emit('preferences', { sound: false, locale });
host.emit('state', state);
}, { state: stripped(game), locale: locale === 'fr' ? 'fr-CA' : 'en' });
await page.waitForSelector(`[data-clash-locale="${locale}"]`);
await page.getByRole('button', { name: text('Cultural influence'), exact: true }).click();
const target = page.locator('.map-hit-target[data-position="C1"]');
await target.press('Enter');
const changeSource = page.locator('.influence-picker').getByRole('button', {
name: text('Change source'), exact: true,
});
const source = changeSource.locator('strong');
await source.waitFor({ state: 'visible' });
const assertReward = async (scope, expected, summary = false) => {
await frame(page);
const reward = scope.locator('.source-success-reward');
assert.equal(await reward.count(), expected ? 1 : 0, `${label}: only the Darius source shows a reward`);
if (expected) {
assert(await reward.isVisible(), `${label}: Cultural Unity must be visible`);
if (summary) {
assert((await reward.innerText()).includes(text('Cultural Unity')),
`${label}: the payment summary localizes Cultural Unity`);
} else {
assert.equal(await reward.getAttribute('title'), text('Cultural Unity'),
`${label}: the source reward tooltip localizes Cultural Unity`);
}
assert.match(await reward.innerText(), /\+\s*1\b/, `${label}: the reward is +1`);
assert.equal(await reward.getByLabel(`1 ${text('Mood')}`, { exact: true }).count(), 1,
`${label}: the reward is one mood token, not a cost or another resource`);
}
};
const assertSource = async (position, message) => {
await frame(page);
assert.equal(await source.innerText(), position, `${label}: ${message}`);
const chosen = page.locator('.influence-origins button.selected');
assert.equal((await chosen.innerText()).match(/A1|C2/)?.[0], position);
await assertReward(chosen, leader === 'Darius' && position === 'C2');
await assertReward(page.locator('.influence-origins button').filter({ hasText: 'A1' }), false);
await assertReward(page.locator('.influence-origins button').filter({ hasText: 'C2' }), leader === 'Darius');
};
await assertSource('C2', `the equal-cost default prefers ${leader === 'Ashoka' ? 'Buddhism' : 'Cultural Unity'}`);
// An ordinary manual choice is important: merely checking C2 could pass
// even if selecting C1 discards the source and recalculates it.
for (const position of ['A1', 'C2']) {
await page.locator('.influence-origins button').filter({ hasText: position }).click();
await assertSource(position, 'the source button respects the explicit choice');
await target.press('Enter');
await assertSource(position, 'reselecting the same target preserves the explicit source');
if (leader === 'Darius' && position === 'A1') {
await page.getByRole('button', { name: text('Choose payment'), exact: true }).click();
await page.locator('.roll-summary').waitFor({ state: 'visible' });
await assertReward(page.locator('.roll-summary'), false, true);
assert.equal(await source.innerText(), 'A1', `${label}: payment keeps the non-reward source`);
await changeSource.click();
await assertSource('A1', 'returning from payment keeps the explicit non-reward source');
}
}
assert.deepEqual(await sentMoves(page), [], `${label}: selection must not spend or roll`);
// Do not inject a pre-selected attempt: submit through the actual
// source/payment UI so the captured action proves C2 survived it.
await page.getByRole('button', { name: text('Choose payment'), exact: true }).click();
const methods = page.getByLabel(text('Influence payment method'), { exact: true });
await methods.waitFor({ state: 'visible' });
await assertReward(page.locator('.roll-summary'), leader === 'Darius', true);
const unclipped = await methods.locator('button').evaluateAll(buttons => buttons.every(button => {
const rect = button.getBoundingClientRect();
return [...button.children].every(child => {
const text = child.getBoundingClientRect();
return text.top >= rect.top && text.bottom <= rect.bottom && text.left >= rect.left && text.right <= rect.right;
});
}));
assert(unclipped, `${label}: payment labels and boost limits fit inside their buttons`);
await page.screenshot({ path: `/tmp/clash-influence-${leader}-${locale}-${width}-payment.png` });
assert.deepEqual(await sentMoves(page), [], `${label}: choosing payment is still local`);
await methods.getByRole('button', { name: /^Arts\b/ }).click();
await page.waitForFunction(() => window.sentMoves.length > 0);
const submitted = await sentMoves(page);
assert.equal(submitted.length, 1, `${label}: exactly one influence attempt is submitted`);
const attempt = submitted[0].Playing?.InfluenceCultureAttempt;
assert.equal(attempt?.starting_position, 'C2', `${label}: the real attempt starts at ${leader}`);
assert.equal(attempt.selected_structure.position, 'C1');
assert.deepEqual(attempt.selected_structure.structure, { Building: 'Market' });
assert.deepEqual(submitted[0], selected.action, `${label}: the real action uses Arts from C2`);
// Apply the captured attempt with the authoritative local engine. The
// action fee and range payment are separate server continuations, not
// additional rolls. Only Ashoka's resulting reroll state goes to the viewer.
let state = move(game, submitted[0]);
if (view(state).influenceContext?.stage === 'payment') {
state = move(state, { Response: { Payment: [selected.actionPayment] } });
}
if (view(state).influenceContext?.stage === 'range') {
state = move(state, { Response: { Payment: [selected.payment] } });
}
if (leader === 'Ashoka') {
assert.deepEqual(view(state).influenceContext, {
name: 'Market', source: 'C2', target: 'C1', stage: 'reroll',
roll: 3, rollBonus: 1, threshold: 5,
}, `${label}: raw die 2 plus Conversion must reach the Buddhism decision`);
await page.evaluate((state) => host.emit('state', state), stripped(state));
const reroll = page.getByRole('button', { name: text('Reroll with Buddhism'), exact: true });
const keep = page.getByRole('button', { name: text('Keep this roll'), exact: true });
await reroll.waitFor({ state: 'visible' });
await keep.waitFor({ state: 'visible' });
assert(await reroll.isEnabled(), `${label}: reroll must be actionable`);
assert(await keep.isEnabled(), `${label}: keeping the roll must be actionable`);
const flow = page.locator('.influence-flow');
assert.equal(await flow.locator('.influence-roll strong').innerText(), '3');
assert.match(await flow.locator('.influence-roll small').innerText(), /\+1/);
assert.equal(await flow.locator('.influence-route b').first().innerText(), 'C2');
assert.equal(await flow.locator('.influence-route b').last().innerText(), 'C1');
await page.screenshot({ path: `/tmp/clash-influence-Ashoka-${locale}-${width}-reroll.png` });
await reroll.click();
await page.waitForFunction(() => window.sentMoves.length > 1);
assert.deepEqual(await sentMoves(page), [submitted[0], { Response: { Bool: true } }],
`${label}: the Buddhism button submits the affirmative response`);
const resolved = move(state, { Response: { Bool: true } });
assert.equal(resolved.successful_cultural_influence, true);
assert.equal(resolved.players[0].event_info.Buddhism, 'used');
} else {
assert.equal(state.successful_cultural_influence, true, `${label}: the forced roll of 6 succeeds`);
assert.equal(state.players[1].cities.find((city) => city.position === 'C1').city_pieces.market, 0,
`${label}: the actual Market is influenced`);
const moodPaid = (selected.actionPayment?.mood_tokens ?? 0) + (selected.payment?.mood_tokens ?? 0);
assert.equal(game.players[0].resources.mood_tokens, 12);
assert.equal(state.players[0].resources.mood_tokens, 12 - moodPaid + 1,
`${label}: Cultural Unity awards exactly one mood token after fees and range payment`);
assert(state.players[0].resources.mood_tokens > game.players[0].resource_limit.mood_tokens,
`${label}: Cultural Unity is not capped at the ordinary resource limit`);
assert.deepEqual(await sentMoves(page), submitted, `${label}: the preview never submits a reward action`);
}
await frame(page);
assert.equal(await page.locator('[data-clash-locale-status]').count(), 0);
assert.deepEqual(errors, [], `${label}: no page errors`);
assert.deepEqual(unexpectedRequests, [], `${label}: no unexpected network requests`);
console.log(`${label}: equal-cost default, manual source retention, Arts attempt from C2, ${leader === 'Ashoka'
? 'roll 3 and Buddhism reroll' : 'localized reward preview and uncapped +1 mood on success'} passed`);
} finally {
await page.close();
}
}
try {
for (const [width, height] of [[1400, 900], [390, 844]]) {
for (const locale of ['en', 'fr']) {
for (const scenario of fixtures) await smoke(scenario, width, height, locale);
}
}
} finally {
await browser.close();
}

View file

@ -125,6 +125,7 @@
/>{:else}<small>In range</small>{/if}
{#if from.position === target.position}<span class="source-boost-warning" aria-label="Same hex: cannot boost the roll"><TriangleAlert size={15} /></span>{/if}
{#if from.reroll}<RotateCcw size={14} />{/if}
{#each from.successRewards ?? [] as reward}<span class="source-success-reward" title={reward.name}>+<ResourceAmount pile={reward.resources} compact /></span>{/each}
</button>{/each}
</div>{/if}
{#if !paymentStep}
@ -176,6 +177,7 @@
? 'Protected target · No range or roll boost'
: 'Boost after rolling · 1 culture per +1.'}</span>
{#if origin?.reroll}<span>Buddhism · One optional reroll</span>{/if}
{#each origin?.successRewards ?? [] as reward}<span class="source-success-reward">{reward.name} · +<ResourceAmount pile={reward.resources} compact /></span>{/each}
</div>
<div class="influence-methods" aria-label="Influence payment method">
{#each methods as method}
@ -196,6 +198,7 @@
<style>
.source-boost-warning { display: inline-flex; color: var(--gold, #b79351); }
.source-success-reward { display: inline-flex; align-items: center; gap: 0.2rem; }
.influence-picker { min-height: 0; overflow-y: auto; }
.influence-submit { flex-shrink: 0; padding-top: 0.4rem; border-top: 1px solid var(--line); }
.movement-heading { flex-shrink: 0; }
@ -206,7 +209,7 @@
.route-choice strong { font-size: 14px; }
.route-target { flex: 1; min-width: 0; }
.influence-methods { display: flex; gap: 0.5rem; margin: 0; }
.influence-methods button { flex: 1; flex-direction: column; align-items: stretch; gap: 0.3rem; }
.influence-methods button { flex: 1; height: auto; flex-direction: column; align-items: stretch; gap: 0.3rem; }
.influence-action-cost { display: inline-flex; align-items: center; gap: 0.2rem; color: inherit; font-size: inherit; line-height: 1; }
.method-title { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
.influence-methods small { font-size: 11px; color: inherit; }

View file

@ -13,6 +13,7 @@ import { requiredRecruitDiscards } from './recruit-discards.ts';
import { happinessPreview, happinessCities } from './happiness.ts';
import { frameDetails } from './playback.ts';
import { frameResources } from './resource-playback.ts';
import { activeInfluence, influenceKey } from './influence.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
// Bundle the actual controller so Node can run its browser TypeScript imports.
@ -1091,6 +1092,67 @@ test('cultural influence opens a map mode where clicking the target building cho
}
});
test('reselecting an influence target preserves the explicit legal source through map and list paths', async () => {
for (const multipleBuildings of [false, true]) {
const app = paymentController(), c = app.controller;
try {
const g = JSON.parse(fixture('base/cultural_influence_instant'));
g.current_player_index = 0;
const p = g.players[0];
p.civilization = 'India';
p.advances.push('Myths', 'StateReligion', 'Dogma', 'Conversion', 'Arts');
p.cities = ['A1', 'C2'].map(position => ({ position, mood_state: 'Happy', city_pieces: { temple: 0 } }));
p.units = [{ id: 0, position: 'C2', unit_type: { Leader: 'Ashoka' } }];
p.next_unit_id = 1;
g.players[1].cities[0].city_pieces = multipleBuildings ? { market: 1, academy: 1 } : { market: 1 };
c.setPlayer(0);
await c.load(engine.stripSecret(JSON.stringify(g), 0));
c.chooseInfluence();
c.selectTile('C1', { kind: 'tile' });
const targets = app.session().view!.influence!;
const market = targets.find(o => o.name === 'Market')!;
const arts = targets.find(o => o.name === 'Market' && o.variant === 'Arts')!;
if (multipleBuildings) {
assert.equal(app.session().influenceTarget, null, 'a new ambiguous hex still asks for a building');
c.selectInfluenceTarget(influenceKey(market));
}
assert.equal(activeInfluence(app.session())?.source, 'C2');
for (const source of ['A1', 'C2']) {
c.selectInfluenceOrigin(source);
c.selectInfluenceTarget(influenceKey(market));
assert.equal(app.session().influenceOrigin, source, 'list reselection must respect both reroll and non-reroll sources');
c.selectTile('C1', { kind: 'city', player: 1, structure: 'Building:Market' });
assert.equal(app.session().influenceOrigin, source, 'same building on the map preserves the source');
c.selectTile('C1', { kind: 'tile' });
assert.equal(app.session().influenceOrigin, source, 'same hex preserves its already selected building and source');
assert.equal(app.session().influenceTarget, influenceKey(market));
c.selectInfluenceTarget(influenceKey(arts));
assert.equal(app.session().influenceOrigin, source, 'changing only the action method preserves a legal source');
c.selectTile('C1', { kind: 'city', player: 1, structure: 'Building:Market' });
assert.equal(activeInfluence(app.session())?.source, source);
}
if (multipleBuildings) {
c.selectTile('C1', { kind: 'city', player: 1, structure: 'Building:Academy' });
assert.equal(app.session().influenceOrigin, null, 'a different building resets the source');
assert.match(app.session().influenceTarget!, /Academy/);
}
c.selectInfluenceTarget(influenceKey(market));
c.selectInfluenceOrigin('C2');
const v = app.session().view!;
c.patch({ view: { ...v, influence: v.influence!.map(o => ({ ...o, origins: o.origins!.filter(from => from.position !== 'C2') })) } });
c.selectInfluenceTarget(influenceKey(market));
assert.equal(app.session().influenceOrigin, null, 'do not retain a source that is no longer eligible');
assert.equal(activeInfluence(app.session())?.source, 'A1');
c.selectInfluenceOrigin('A1');
c.selectInfluenceTarget(null);
assert.equal(app.session().influenceOrigin, null, 'clearing the target still clears the source');
assert.deepEqual(app.sent, [], 'source selection never submits a move');
} finally {
app.close();
}
}
});
test('port resource choices replace one another even after selecting another tile or filling capacity', async () => {
const app = paymentController(),
c = app.controller;

View file

@ -3,7 +3,7 @@ import { liveActionMessages } from './live-actions';
import { eventNotices, liveEventNotices } from './event-notices';
import { publicActions } from './replay-actions';
import { boardingPlan, type BoardingGroup } from './boarding';
import { activeInfluence, influenceKey, influenceDestinations, influenceMapPick, influencePaymentMatches } from './influence';
import { activeInfluence, influenceKey, influenceDestinationKey, influenceDestinations, influenceMapPick, influencePaymentMatches } from './influence';
import { defaultCity, type CollectionPotential } from './default-city';
import { nextCollectionSelection } from './collection-yield';
import { get, writable } from 'svelte/store';
@ -1108,14 +1108,14 @@ export class Controller {
const influence = activeInfluence(s);
if (influence) {
const offer = influenceMapPick(influence.offers, position, influence.position === position ? pick : { kind: 'tile' });
if (influence.targets.includes(position))
this.patch({
influencePosition: position,
influenceTarget: offer ? influenceKey(offer) : null,
influenceOrigin: null,
error: '',
});
else if (influence.origins.includes(position)) this.patch({ influenceOrigin: position, error: '' });
if (influence.targets.includes(position)) {
if (offer) this.selectInfluenceTarget(influenceKey(offer));
else if (influence.target?.position !== position) {
// Open a new ambiguous hex, but do not discard an already selected
// building/source just because its own hex was clicked again.
this.patch({ influencePosition: position, influenceTarget: null, influenceOrigin: null, error: '' });
}
} else if (influence.origins.includes(position)) this.patch({ influenceOrigin: position, error: '' });
return;
}
const ability = activeCityAbility(s);
@ -1236,10 +1236,14 @@ export class Controller {
selectInfluenceTarget(key: string | null) {
const s = get(this.session);
const offer = s.view?.influence?.find((o) => influenceKey(o) === key);
const previous = s.view?.influence?.find((o) => influenceKey(o) === s.influenceTarget);
const keepSource = offer && previous &&
influenceDestinationKey(offer) === influenceDestinationKey(previous) &&
offer.origins?.some((o) => o.position === s.influenceOrigin);
this.patch({
influenceTarget: offer ? key : null,
influencePosition: offer?.position ?? s.influencePosition ?? null,
influenceOrigin: null,
influenceOrigin: keepSource ? s.influenceOrigin : null,
error: '',
});
}

View file

@ -0,0 +1,130 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { activeInfluence, bestInfluenceOrigin, cheaperInfluenceOrigin, influenceKey, influenceSuccessScore, type InfluenceOffer } from './influence.ts';
import type { Session, View } from './types.ts';
type Origin = NonNullable<InfluenceOffer['origins']>[number];
const source = (position: string, patch: Partial<Origin> = {}): Origin => ({
position, settlers: false, reroll: false, payment: {}, action: {}, free: false,
actionPayment: {}, rollBonus: 0, preventBoost: false, ...patch,
});
const offer = (...origins: Origin[]): InfluenceOffer => ({
name: 'Market', position: 'C1', origin: origins[0].position, origins,
variant: 'Influence Culture', payment: {}, action: {},
});
const unity = [{ name: 'Cultural Unity', resources: { mood_tokens: 1 } }];
test('equal-cost defaults compare exact free success chances, not just reroll flags', () => {
const ordinary = source('A1'), reroll = source('C2', { reroll: true });
assert.equal(influenceSuccessScore(ordinary), 12);
assert.equal(influenceSuccessScore(reroll), 20);
assert.equal(influenceSuccessScore(source('C2', { rollBonus: 1 })), 18);
assert.equal(influenceSuccessScore(source('C2', { rollBonus: 1, reroll: true })), 27);
assert.equal(bestInfluenceOrigin(offer(ordinary, source('C2', { rollBonus: 1 })))?.position, 'C2');
assert.equal(bestInfluenceOrigin(offer(source('A1', { rollBonus: 1 }), reroll))?.position, 'C2');
assert.equal(bestInfluenceOrigin(offer(reroll, source('A1', { rollBonus: 2 })))?.position, 'A1');
const guaranteed = source('A1', { rollBonus: 4 });
assert.equal(influenceSuccessScore(guaranteed), 36);
assert.equal(influenceSuccessScore(source('C2', { rollBonus: 8, reroll: true })), 36);
assert.equal(bestInfluenceOrigin(offer(guaranteed, source('C2', { rollBonus: 4, reroll: true })))?.position, 'A1', 'do not value an unusable reroll');
});
test('equal chances prefer boosting and source rewards without overriding costs or manual choices', () => {
const ordinary = source('A1'), darius = source('C2', { successRewards: unity });
assert.equal(bestInfluenceOrigin(offer(ordinary, darius))?.position, 'C2');
assert.equal(bestInfluenceOrigin(offer(darius, ordinary))?.position, 'C2');
assert.equal(bestInfluenceOrigin(offer(source('A1', { preventBoost: true }), source('C2')))?.position, 'C2');
assert.equal(bestInfluenceOrigin(offer(ordinary, { ...darius, payment: { culture_tokens: 1 } }))?.position, 'A1');
assert.equal(bestInfluenceOrigin(offer(ordinary, { ...darius, actionPayment: { mood_tokens: 1 } }))?.position, 'A1');
assert.equal(bestInfluenceOrigin(offer({ ...ordinary, free: true }, darius))?.position, 'A1');
assert.equal(bestInfluenceOrigin(offer(ordinary, { ...darius, rollBonus: 1, payment: { culture_tokens: 1 } }))?.position, 'A1');
assert.equal(bestInfluenceOrigin(offer(ordinary, source('C2')))?.position, 'A1', 'stable fallback');
const target = offer(ordinary, darius);
const s = { mode: 'overview', abilitiesOpen: true, influenceMode: true,
influenceTarget: influenceKey(target), influenceOrigin: 'A1',
view: { canPlay: true, influence: [target] } } as Session;
assert.equal(activeInfluence(s)?.source, 'A1');
assert.deepEqual(target.origins, [ordinary, darius], 'sorting does not mutate engine offers');
});
test('cheaper-source suggestions never silently trade away success chances, boosting or rewards', () => {
const cheaper = source('A1'), remote = source('C2', { payment: { culture_tokens: 1 } });
for (const benefit of [{ reroll: true }, { rollBonus: 1 }, { successRewards: unity }]) {
const selected = { ...remote, ...benefit };
assert.equal(cheaperInfluenceOrigin(offer(cheaper, selected), selected), null);
const equivalent = { ...cheaper, ...benefit };
assert.equal(cheaperInfluenceOrigin(offer(equivalent, selected), selected), equivalent);
}
assert.equal(cheaperInfluenceOrigin(offer({ ...cheaper, preventBoost: true }, remote), remote), null);
assert.equal(cheaperInfluenceOrigin(offer(cheaper, remote), remote), cheaper);
});
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'influence-defaults', {})).players.slice(2);
const view = (g: any): View => JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(g), 0), 0));
const move = (g: any, action: unknown) => JSON.parse(engine.tryMove(JSON.stringify(g), JSON.stringify(action), 0));
function dariusFixture() {
const g = JSON.parse(readFileSync(new URL('../../server/tests/test_games/base/cultural_influence_instant.json', import.meta.url), 'utf8'));
g.players = [...g.players.slice(0, 2), ...structuredClone(npcs)];
g.current_player_index = 0;
g.dice_roll_outcomes = [10];
const p = g.players[0];
p.civilization = 'Persia';
p.advances.push('Arts', 'Myths', 'Priesthood');
p.cities = ['A1', 'C2'].map(position => ({ position, mood_state: 'Happy', city_pieces: { temple: 0, academy: 0 } }));
p.units = [{ id: 0, position: 'C2', unit_type: { Leader: 'Darius' } }];
p.next_unit_id = 1;
p.resources.culture_tokens = 7;
p.resources.mood_tokens = 12; // Mood tokens are not capped at the ordinary resource limit.
g.players[1].cities[0].city_pieces = { market: 1 };
g.players[1].units = [{ id: 0, position: 'B3', unit_type: 'Infantry' }];
g.players[1].next_unit_id = 1;
return g;
}
function resolveAttempt(g: any, from: Origin) {
let next = move(g, from.action);
if (view(next).influenceContext?.stage === 'payment') next = move(next, { Response: { Payment: [from.actionPayment] } });
if (view(next).influenceContext?.stage === 'range') next = move(next, { Response: { Payment: [from.payment] } });
return next;
}
test('real Darius defaults include Arts and unit conversion, and match the actual source reward', () => {
const g = dariusFixture(), before = JSON.stringify(g);
const targets = view(g).influence!;
assert(targets.some(t => t.variant === 'Arts'));
assert(targets.some(t => t.variant === 'Zoroastrianism'));
for (const target of targets) {
const a = target.origins!.find(o => o.position === 'A1')!;
const d = target.origins!.find(o => o.position === 'C2')!;
assert(a && d);
assert.deepEqual(d.payment, a.payment);
assert.deepEqual(a.successRewards, []);
assert.deepEqual(d.successRewards, unity);
assert.equal(bestInfluenceOrigin(target)?.position, 'C2');
for (const from of [a, d]) {
const after = resolveAttempt(g, from);
assert.equal(after.successful_cultural_influence, true);
const actionMood = from.actionPayment?.mood_tokens ?? 0;
assert.equal(after.players[0].resources.mood_tokens, 12 - actionMood + (from === d ? 1 : 0));
}
}
assert.equal(JSON.stringify(g), before, 'previews and sorting do not mutate the state');
});
test('Darius reward metadata follows the actual leader position and never leaks into common success rewards', () => {
const g = dariusFixture();
g.players[0].units[0].position = 'A1';
for (const target of view(g).influence!) {
assert.deepEqual(target.origins!.find(o => o.position === 'C2')!.successRewards, []);
assert.equal(bestInfluenceOrigin(target)?.position, 'A1');
}
g.players[0].units = [];
g.players[0].advances.push('Conversion');
for (const target of view(g).influence!) {
assert(target.origins!.every(o => o.successRewards?.length === 0));
assert(target.origins!.every(o => o.rollBonus === 1));
assert.equal(bestInfluenceOrigin(target)?.position, 'A1');
}
});

View file

@ -169,6 +169,57 @@ test('destination selection defers Arts versus regular influence and defaults to
});
test('equal-cost influence defaults prefer Buddhism without overriding price, action cost or explicit sources', () => {
const g = influenceFixture(), p = g.players[0];
p.civilization = 'India';
p.advances.push('Myths', 'StateReligion', 'Dogma', 'Conversion', 'Arts');
p.cities[0].city_pieces = { temple: 0 };
p.cities.push({ position: 'C2', mood_state: 'Happy', city_pieces: { temple: 0 } });
p.units = [{ id: 0, position: 'C2', unit_type: { Leader: 'Ashoka' } }];
p.next_unit_id = 1;
g.players[1].cities[0].city_pieces = { market: 1 };
g.dice_roll_outcomes = [10, 2]; // raw 2 + Conversion, then raw 6
const v = view(g);
const targets = v.influence!.filter(o => o.position === 'C1' && o.name === 'Market');
assert.ok(targets.some(o => o.variant === 'Arts'));
for (const target of targets) {
const ordinary = target.origins!.find(o => o.position === 'A1')!;
const ashoka = target.origins!.find(o => o.position === 'C2')!;
assert.equal(ordinary.reroll, false);
assert.equal(ashoka.reroll, true);
assert.deepEqual(ordinary.payment, ashoka.payment);
assert.equal(bestInfluenceOrigin(target)?.position, 'C2');
assert.equal(bestInfluenceOrigin({ ...target, origins: [ashoka, ordinary] })?.position, 'C2');
assert.equal(bestInfluenceOrigin({ ...target, origins: [ordinary, { ...ashoka, payment: { culture_tokens: 1 } }] })?.position, 'A1', 'do not spend extra for the reroll automatically');
assert.equal(bestInfluenceOrigin({ ...target, origins: [{ ...ordinary, free: true }, { ...ashoka, free: false }] })?.position, 'A1', 'do not spend an extra action for the reroll automatically');
assert.equal(bestInfluenceOrigin({ ...target, origins: [ordinary, { ...ashoka, reroll: false }] })?.position, 'A1', 'preserve stable ordering without an available reroll');
const selection = { view: v, mode: 'overview', abilitiesOpen: true, influenceMode: true, influenceTarget: influenceKey(target) } as Session;
assert.equal(activeInfluence(selection)?.source, 'C2');
assert.equal(activeInfluence({ ...selection, influenceOrigin: 'A1' })?.source, 'A1', 'explicit non-reroll choices are respected');
for (const origin of [ordinary, ashoka]) {
let state = move(g, origin.action);
if (view(state).influenceContext?.stage === 'payment') state = move(state, { Response: { Payment: [origin.actionPayment] } });
if (view(state).influenceContext?.stage === 'range') state = move(state, { Response: { Payment: [origin.payment] } });
assert.equal(view(state).influenceContext?.source, origin.position);
assert.equal(view(state).influenceContext?.roll, 3);
assert.equal(view(state).influenceContext?.stage, origin.reroll ? 'reroll' : 'boost');
if (origin.reroll) {
assert.ok(view(state).choiceDecision?.choices.some(c => c.name === 'Reroll with Buddhism'));
const rerolled = move(state, { Response: { Bool: true } });
assert.ok(rerolled.successful_cultural_influence);
assert.equal(rerolled.players[0].event_info.Buddhism, 'used');
} else {
assert.equal(view(state).decision!.fields[0].cost.culture_tokens, 2);
}
}
}
p.event_info = { Buddhism: 'used' };
const used = view(g).influence!.find(o => o.position === 'C1' && o.name === 'Market')!;
assert.ok(used.origins!.every(o => !o.reroll));
assert.equal(bestInfluenceOrigin(used)?.position, 'A1');
});
test('reclaiming influence allows another city and boosting, but self-targeting cannot boost', () => {
const g = influenceFixture();
const reclaimedCity = g.players[1].cities.shift();

View file

@ -36,6 +36,24 @@ type Attempt = {
export const influenceKey = (offer: InfluenceOffer) => `${offer.position}/${offer.name}/${offer.variant}`;
export const influenceDestinationKey = (offer: InfluenceOffer) => `${offer.position}/${offer.name}`;
type InfluenceOrigin = NonNullable<InfluenceOffer['origins']>[number];
// Fair d6, success at 5+. Compare exact numerators over 36, including an optional
// reroll of a failed die. A reroll adds no benefit when success is already certain.
export function influenceSuccessScore(origin: InfluenceOrigin) {
const successes = Math.max(0, Math.min(6, 2 + (origin.rollBonus ?? 0)));
return origin.reroll ? 12 * successes - successes * successes : 6 * successes;
}
const canBoost = (offer: InfluenceOffer, origin: InfluenceOrigin) =>
origin.position !== offer.position && !origin.preventBoost;
const successReward = (origin: InfluenceOrigin) => (origin.successRewards ?? [])
.reduce<Pile>((total, reward) => influenceUpfrontCost(total, reward.resources), {});
const rewardSize = (origin: InfluenceOrigin) =>
Object.values(successReward(origin)).reduce((sum, n) => sum + (n ?? 0), 0);
const compareBenefits = (offer: InfluenceOffer, a: InfluenceOrigin, b: InfluenceOrigin) =>
influenceSuccessScore(b) - influenceSuccessScore(a) ||
Number(canBoost(offer, b)) - Number(canBoost(offer, a)) || rewardSize(b) - rewardSize(a);
export function bestInfluenceOrigin(offer: InfluenceOffer) {
const cost = (o: NonNullable<InfluenceOffer['origins']>[number]) =>
Object.values(influenceUpfrontCost(o.actionPayment, o.payment)).reduce((sum, n) => sum + (n ?? 0), 0);
@ -45,7 +63,9 @@ export function bestInfluenceOrigin(offer: InfluenceOffer) {
? origins.filter(o => o.position !== offer.position && !o.settlers && !o.preventBoost)
: [];
return [...(boostableCities.length ? boostableCities : origins)]
.sort((a, b) => cost(a) - cost(b) || Number(!!b.free) - Number(!!a.free))[0] ?? null;
// Improve otherwise equal-cost attempts without buying a benefit. The existing
// reclaim preference above is intentional; explicit choices bypass all defaults.
.sort((a, b) => cost(a) - cost(b) || Number(!!b.free) - Number(!!a.free) || compareBenefits(offer, a, b))[0] ?? null;
}
export function influenceDestinations(offers: InfluenceOffer[]) {
return offers.filter((o, i) => offers.findIndex(other => influenceDestinationKey(other) === influenceDestinationKey(o)) === i);
@ -112,6 +132,15 @@ export function activeInfluence(s: Session) {
};
}
/** Recommend savings only when they do not give up source benefits. */
function retainsInfluenceBenefits(offer: InfluenceOffer, candidate: InfluenceOrigin, selected: InfluenceOrigin) {
const kept = successReward(candidate);
return influenceSuccessScore(candidate) >= influenceSuccessScore(selected) &&
(!canBoost(offer, selected) || canBoost(offer, candidate)) &&
Object.entries(successReward(selected)).every(([resource, amount]) =>
(kept[resource as keyof Pile] ?? 0) >= (amount ?? 0));
}
/** Recommend only an eligible city for this same target and action variant. */
export function cheaperInfluenceOrigin(
offer: InfluenceOffer | null,
@ -124,11 +153,12 @@ export function cheaperInfluenceOrigin(
.filter(
(from) =>
!from.settlers &&
(!selected || retainsInfluenceBenefits(offer, from, selected)) &&
// Self-targeting loses the ability to boost, so it is not an equivalent saving.
!(from.position === offer.position && selected?.position !== offer.position && !selected?.preventBoost) &&
from.position !== (selected?.position ?? offer.origin) &&
(from.payment.culture_tokens ?? 0) < currentCost,
)
.sort((a, b) => (a.payment.culture_tokens ?? 0) - (b.payment.culture_tokens ?? 0))[0] ?? null
.sort((a, b) => (a.payment.culture_tokens ?? 0) - (b.payment.culture_tokens ?? 0) || compareBenefits(offer, a, b))[0] ?? null
);
}

View file

@ -328,6 +328,8 @@ export interface View {
actionPayment?: Pile;
rollBonus?: number;
preventBoost?: boolean;
/** Source-dependent rewards only; common success effects do not distinguish origins. */
successRewards?: { name: string; resources: Pile }[];
}[];
free?: boolean;
actionPayment?: Pile;