diff --git a/client/src/log_ui.rs b/client/src/log_ui.rs index c7c91775..f8c7a858 100644 --- a/client/src/log_ui.rs +++ b/client/src/log_ui.rs @@ -273,6 +273,15 @@ fn draw_entry(drawer: &mut RichTextDrawer, entry: &ActionLogEntry, player: usize r.combat_value, r.hits, )); } + ActionLogEntry::CombatHitReport { + combat_value, + hit_cancels, + extra_hits, + casualties, + } => { + let hits = (combat_value / 5).saturating_sub(*hit_cancels) + extra_hits; + drawer.text(&format!("{hits} hits; {casualties} casualties")); + } ActionLogEntry::Text(m) => { drawer.text(m); } diff --git a/server/src/combat_listeners.rs b/server/src/combat_listeners.rs index b4bd4cb4..f3c2de79 100644 --- a/server/src/combat_listeners.rs +++ b/server/src/combat_listeners.rs @@ -603,6 +603,13 @@ pub(crate) fn choose_fighter_casualties() -> Ability { } else { "defending" }; + // All hit-changing tactics and abilities have resolved before this + // listener. Report even zero losses, before any casualty prompt. + if role.is_attacker() { + r.defender.report(game, r.combat.defender()); + } else { + r.attacker.report(game, r.combat.attacker()); + } let casualties = r.losses(role); if casualties == 0 { return None; diff --git a/server/src/combat_roll.rs b/server/src/combat_roll.rs index f3478503..50ae1c33 100644 --- a/server/src/combat_roll.rs +++ b/server/src/combat_roll.rs @@ -55,6 +55,20 @@ impl CombatHits { hits.min(self.opponent_fighters) } + /// Public reporting only; hit resolution remains in `hits`. + pub(crate) fn report(&self, game: &mut Game, player: usize) { + EventPlayer::new(player, combat_event_origin()).add_log_entry(game, self.hit_report()); + } + + fn hit_report(&self) -> ActionLogEntry { + ActionLogEntry::CombatHitReport { + combat_value: self.combat_value, + hit_cancels: self.opponent_hit_cancels, + extra_hits: self.extra_hits, + casualties: self.hits(), + } + } + pub(crate) fn all_opponents_killed(&self) -> bool { self.hits() == self.opponent_fighters } @@ -145,6 +159,7 @@ impl CombatRoundStats { combat_modifiers: self.strength.roll_log.clone(), }), ); + combat_hits.report(game, self.player); combat_hits } } @@ -307,3 +322,40 @@ fn roll_die(game: &mut Game, roll_log: &mut Vec) -> CombatDieRol }); roll } + +#[cfg(test)] +mod hit_reporting_tests { + use super::*; + + #[test] + fn hit_reports_preserve_uncapped_arithmetic_without_changing_casualties() { + for (value, cancels, extra, fighters, casualties) in [ + (29, 1, 0, 3, 3), + (29, 1, 0, 4, 4), + (29, 2, 0, 4, 3), + (29, 3, 0, 4, 2), + (29, 0, 0, 3, 3), + (0, 3, 0, 4, 0), + (4, 3, 2, 4, 2), + (29, 2, 1, 3, 3), + ] { + let mut hits = CombatHits::new(None, cancels, fighters, value); + hits.extra_hits = extra; + let before = hits.clone(); + assert_eq!( + hits.hit_report(), + ActionLogEntry::CombatHitReport { + combat_value: value, + hit_cancels: cancels, + extra_hits: extra, + casualties, + } + ); + assert_eq!(hits.hits(), casualties); + assert_eq!(hits, before); + let json = serde_json::to_string(&hits.hit_report()).unwrap(); + let decoded: ActionLogEntry = serde_json::from_str(&json).unwrap(); + assert_eq!(decoded, hits.hit_report()); + } + } +} diff --git a/server/src/log.rs b/server/src/log.rs index 74b5ecb6..308f0eb3 100644 --- a/server/src/log.rs +++ b/server/src/log.rs @@ -277,6 +277,13 @@ pub enum ActionLogEntry { }, CombatRound(ActionLogEntryCombatRound), CombatRoll(ActionLogEntryCombatRoll), + // Reporting only: retain the uncapped arithmetic separately from casualties. + CombatHitReport { + combat_value: u8, + hit_cancels: u8, + extra_hits: u8, + casualties: u8, + }, InfluenceCultureAttempt(InfluenceCultureAttemptInfo), } diff --git a/server/tests/civ_china_tests.rs b/server/tests/civ_china_tests.rs index 8b316632..e843a2e9 100644 --- a/server/tests/civ_china_tests.rs +++ b/server/tests/civ_china_tests.rs @@ -103,3 +103,67 @@ fn great_wall() { ], ); } + +#[test] +fn paid_fireworks_reports_final_hits_without_rewriting_the_roll() { + use server::game_api::execute; + use server::log::ActionLogEntry; + let game = execute( + JSON.load_game("fireworks"), + move_action(vec![0], Position::from_offset("C1")), + 0, + ); + let reports = |game: &server::game::Game| { + game.log + .iter() + .flat_map(|a| &a.rounds) + .flat_map(|r| &r.turns) + .flat_map(|t| &t.actions) + .flat_map(|a| &a.items) + .filter(|i| i.player == 1) + .filter_map(|i| match i.entry { + ActionLogEntry::CombatHitReport { + combat_value, + hit_cancels, + extra_hits, + casualties, + } => Some((combat_value, hit_cancels, extra_hits, casualties)), + _ => None, + }) + .collect::>() + }; + assert_eq!(reports(&game), vec![(6, 0, 0, 1)]); + let original_roll_action = game + .log + .last() + .unwrap() + .rounds + .last() + .unwrap() + .turns + .last() + .unwrap() + .actions + .last() + .unwrap() + .items + .clone(); + let game = execute(game, payment_response(ResourcePile::gold(2)), 0); + assert_eq!(reports(&game), vec![(6, 0, 0, 1), (6, 1, 0, 0)]); + for seat in [None, Some(0), Some(1)] { + let public = server::game_api::strip_secret(game.clone(), seat); + assert_eq!(reports(&public), reports(&game)); + } + let actions = &game + .log + .last() + .unwrap() + .rounds + .last() + .unwrap() + .turns + .last() + .unwrap() + .actions; + assert_eq!(actions[actions.len() - 2].items, original_roll_action); +} diff --git a/server/tests/common/mod.rs b/server/tests/common/mod.rs index 07cf8c81..dca2ac8e 100644 --- a/server/tests/common/mod.rs +++ b/server/tests/common/mod.rs @@ -136,7 +136,36 @@ fn assert_eq_game_json( } fn clean_json(expected: &str) -> String { - expected.replace([' ', '\t', '\n', '\r'], "") + // Historical golden games predate the presentation-only hit report. Keep + // those records intact and compare all gameplay/log data except this new + // redundant arithmetic, covered explicitly by hit-reporting regressions. + let mut value: serde_json::Value = serde_json::from_str(expected).unwrap(); + // Only public action-log items qualify, never arbitrary arrays or game state. + if let Some(ages) = value + .get_mut("log") + .and_then(serde_json::Value::as_array_mut) + { + for age in ages { + for round in age["rounds"].as_array_mut().unwrap() { + for turn in round["turns"].as_array_mut().unwrap() { + if let Some(actions) = turn + .get_mut("actions") + .and_then(serde_json::Value::as_array_mut) + { + for action in actions { + if let Some(items) = action + .get_mut("items") + .and_then(serde_json::Value::as_array_mut) + { + items.retain(|item| item.get("CombatHitReport").is_none()); + } + } + } + } + } + } + } + serde_json::to_string(&value).unwrap() } pub(crate) fn write_result(actual: &str, result_path: &GamePath) { diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md index 309477db..4709f25f 100644 --- a/web-client/docs/viewer-publishing.md +++ b/web-client/docs/viewer-publishing.md @@ -1113,3 +1113,35 @@ unaffordability and exhausted city supply. Combat, playback, recap-layout and Subterfuge browser smokes pass against the packed engine; the standalone battle-dice smoke also passes. Clippy retains existing warnings; expected invalid-move rejection tests log WASM panics. + +# Viewer 0.1.209 / engine 0.4.141 + +Combat journals and battle playback distinguish nominal hits from capped +casualties. For example, 29 combat value against three fighters with a Fortress +shows 5 → 4 hits and 3 casualties, not a misleading cancellation caused by the +unit cap. Elephant and WarShips cancellation quantities combine correctly; +successfully paid Fireworks and Qin Shi Huang's Tactician update the existing +battle cue without replaying its dice. Declined or unaffordable abilities do not +invent cancellations. Extra hits remain uncancellable. + +The engine appends public `CombatHitReport` arithmetic after each roll and after +late hit modifiers, before casualty choices. Original roll records and casualty +resolution are unchanged. Older saves remain readable; legacy displays infer +nominal hits only when explicit cancellation quantities reconcile with the +recorded capped result. Unknown modifiers remain conservative. Historical golden +tests exclude only these new public action-log items; dedicated native and packed +engine tests verify both reports, serialization, seat/spectator visibility, +paid/declined/unaffordable reductions and unchanged earlier roll records. + +Publish the matching viewer and engine together. Package the fresh Node bridge +as `@boardgamers/clash-server` 0.4.141, then run `npm run publish:bgs -- +--engine=/absolute/path/to/package.tgz` (first with `--dry-run`). Preserve all +unrelated metadata, especially game-length labels/order and the Standard default. +All 17 catalogs include the five new messages (5,283 source strings). No live game +moves, historical repairs or smaller-city experiments are included. + +Verified with Rust 1.94.1 build/format/Clippy and all 482 native workspace tests +(one existing ignored test), 1,052 frontend tests against the packed engine, +17 locale catalogs and four extraction tests, Svelte checks (zero errors/warnings) +and the production build. Clippy retains existing warnings; intentional rejected +moves in the regression suite emit expected WASM panic diagnostics. diff --git a/web-client/package-lock.json b/web-client/package-lock.json index 37bd3505..8920d5e0 100644 --- a/web-client/package-lock.json +++ b/web-client/package-lock.json @@ -1,12 +1,12 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.208", + "version": "0.1.209", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.208", + "version": "0.1.209", "dependencies": { "@boardgamers/protocol": "0.9.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index 809e0531..07fa659a 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.208", + "version": "0.1.209", "private": true, "type": "module", "scripts": { diff --git a/web-client/scripts/combat-hits-smoke.mjs b/web-client/scripts/combat-hits-smoke.mjs new file mode 100644 index 00000000..864d2271 --- /dev/null +++ b/web-client/scripts/combat-hits-smoke.mjs @@ -0,0 +1,104 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { chromium } from 'playwright'; + +// Both real views consume the same synthetic public journal projection. +const server = await createServer({ + configFile: false, + appType: 'custom', + root: new URL('..', import.meta.url).pathname, + plugins: [svelte()], + server: { host: '127.0.0.1', port: 0 }, +}); +server.middlewares.use(async (req, res, next) => { + if (req.url !== '/hits') return next(); + res.setHeader('Content-Type', 'text/html'); + res.end( + await server.transformIndexHtml( + req.url, + ` + +
+ `, + ), + ); +}); +await server.listen(); +const browser = await chromium.launch({ headless: true }); +try { + for (const width of [1400, 390, 320]) { + const page = await browser.newPage({ viewport: { width, height: 900 } }); + const errors = []; + page.on('pageerror', (e) => errors.push(e.message)); + await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/hits`); + await page.waitForFunction(() => typeof window.showHits === 'function'); + for (const [fighters, cancels, late, extra, value, before, nominal, casualties] of [ + [4, 2, false, 0, 29, 5, 3, 3], + [4, 2, true, 0, 29, 5, 2, 2], + [3, 1, false, 0, 29, 5, 4, 3], + [4, 1, false, 0, 29, 5, 4, 4], + [3, 0, false, 0, 29, null, 5, 3], + [3, 2, false, 0, 0, null, 0, 0], + [4, 2, false, 1, 29, 6, 4, 4], + ]) { + await page.evaluate((args) => window.showHits(...args), [fighters, cancels, late, extra, value]); + const cell = page.locator('#journal .combat-hits td').first(); + const popup = page.locator('.battle-hit-count strong').first(); + assert.equal(await cell.locator('b').innerText(), String(nominal)); + assert.match(await popup.innerText(), new RegExp(`${nominal} hits?$`)); + for (const view of [cell, popup]) { + assert.equal(await view.locator('s').count(), before === null ? 0 : 1); + if (before !== null) { + assert.equal(await view.locator('s').innerText(), String(before)); + assert.match( + await view.locator('s').evaluate((el) => getComputedStyle(el).textDecorationLine), + /line-through/, + ); + } + } + assert.equal(await page.locator('#journal .combat-casualties').count(), nominal !== casualties ? 1 : 0); + assert.equal(await page.locator('.battle-casualties').count(), nominal !== casualties ? 1 : 0); + if (nominal !== casualties) { + assert.equal( + await page.locator('#journal .combat-casualties td').first().innerText(), + String(casualties), + ); + assert.equal(await page.locator('.battle-casualties').innerText(), `Casualties: ${casualties}`); + } + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + } + assert.deepEqual(errors, []); + await page.close(); + console.log( + `${width}px: journal and popup show uncapped cancellations, paid changes, extras and separate casualties.`, + ); + } +} finally { + await browser.close(); + await server.close(); +} diff --git a/web-client/scripts/combat-smoke.mjs b/web-client/scripts/combat-smoke.mjs index 23742f67..080dbab6 100644 --- a/web-client/scripts/combat-smoke.mjs +++ b/web-client/scripts/combat-smoke.mjs @@ -73,7 +73,7 @@ try { .locator('tbody tr') .filter({ has: page.getByRole('rowheader', { name: 'Hits dealt', exact: true }) }) .innerText(), - 'Hits dealt\t2\t2', + 'Hits dealt\t5\t2', ); assert.ok(await table.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)); assert.equal(await table.locator('.combat-die').count(), 6); diff --git a/web-client/src/BattlePlayback.svelte b/web-client/src/BattlePlayback.svelte index d34b95d9..8e8d0288 100644 --- a/web-client/src/BattlePlayback.svelte +++ b/web-client/src/BattlePlayback.svelte @@ -42,7 +42,7 @@ {#if side.dice}
{#each side.dice as die, i} - {@const label = `${die.value} · ${die.symbol ? `${die.symbol} face · ${die.effect === 're-roll' ? 'Rerolled' : (die.blockedBy ? `Ability blocked by ${die.blockedBy}` : die.effect ?? 'No ability activated')}` : 'Face not recorded'}`} + {@const label = `${die.value} · ${die.symbol ? `${die.symbol} face · ${die.effect === 're-roll' ? 'Rerolled' : die.blockedBy ? `Ability blocked by ${die.blockedBy}` : (die.effect ?? 'No ability activated')}` : 'Face not recorded'}`} {die.value}{#if die.symbol}{/if}{#if die.blockedBy}{/if}{#if die.effect === 're-roll'}{/if} + />{/if}{#if die.blockedBy}{/if}{#if die.effect === 're-roll'}{/if} {:else}No dice{/each}
- {#if side.dice.some(d => d.blockedBy)}Abilities blocked by {side.diceBlockedBy}{/if} + {#if side.dice.some((d) => d.blockedBy)}Abilities blocked by {side.diceBlockedBy}{/if}
{side.value} value{#if side.cancelledHits}{side.cancelledHits.before}{/if} - {side.hits} - {side.hits === 1 ? 'hit' : 'hits'}
+ {#if side.nominalHits !== undefined && side.nominalHits !== side.hits}Casualties: {side.hits}{/if} {:else}Preparing battle{#if side.units?.length} · {side.units.reduce((sum, u) => sum + u.count, 0)} units{/if} - `${die.value} · ${die.symbol ? `${die.symbol} face · ${die.effect === 're-roll' ? 'Rerolled' : (die.blockedBy ? `Ability blocked by ${die.blockedBy}` : die.effect ?? 'No ability activated')}` : 'Face not recorded'}`; + `${die.value} · ${die.symbol ? `${die.symbol} face · ${die.effect === 're-roll' ? 'Rerolled' : die.blockedBy ? `Ability blocked by ${die.blockedBy}` : (die.effect ?? 'No ability activated')}` : 'Face not recorded'}`; @@ -76,10 +76,14 @@ {die.value}{#if die.symbol}{/if}{#if die.blockedBy}{/if}{#if die.effect === 're-roll'}{/if} + />{/if}{#if die.blockedBy}{/if}{#if die.effect === 're-roll'}{/if} {:else}{side.dice ? 'None' : '—'}{/each} - {#if side.dice?.some(d => d.blockedBy)}Dice-symbol abilities blocked by {side.diceBlockedBy}{/if} + {#if side.dice?.some((d) => d.blockedBy)}Dice-symbol abilities blocked by {side.diceBlockedBy}{/if} {#each side.dice?.filter((d) => d.effect && d.effect !== 're-roll') ?? [] as die} @@ -108,12 +112,17 @@ >{#each sides as side}{side.nominalHits ?? side.hits ?? '—'}{/each} + {#if sides.some((s) => s.nominalHits !== undefined && s.nominalHits !== s.hits)} + {#each sides as side}{/each} + {/if}
Hits dealt{#if side.cancelledHits} - {/if}{side.hits ?? '—'}
Casualties{side.hits ?? '—'}
Dice: number + face · Highlighted: ability used
diff --git a/web-client/src/battle-playback.ts b/web-client/src/battle-playback.ts index 4ad9c4c3..fd33fd92 100644 --- a/web-client/src/battle-playback.ts +++ b/web-client/src/battle-playback.ts @@ -53,9 +53,14 @@ export function battleCues( a.combat_stats || a.items?.some( (i) => - i.CombatRound || i.CombatRoll || i.origin?.Ability === 'Combat' || i.Text === 'wins the battle', + i.CombatRound || + i.CombatRoll || + i.CombatHitReport || + i.origin?.Ability === 'Combat' || + i.Text === 'Ignore the first hit' || + i.Text === 'wins the battle', ) || - a.log?.some((l) => /Combat|Tactics|wins|battle/.test(l)), + a.log?.some((l) => /Combat|Tactics|wins|battle|Ignore the first hit/.test(l)), ) ) return []; diff --git a/web-client/src/combat-hits.test.ts b/web-client/src/combat-hits.test.ts new file mode 100644 index 00000000..d45a7fc3 --- /dev/null +++ b/web-client/src/combat-hits.test.ts @@ -0,0 +1,203 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { journal } from './journal.ts'; +import { combatJournal } from './combat-journal.ts'; +import { battleCues } from './battle-playback.ts'; +import type { Game, LoggedAction } from './types.ts'; + +// Entirely synthetic public battle logs; no production game state. +function gameWith(actions: LoggedAction[]): Game { + const game: Game = JSON.parse( + readFileSync( + new URL( + '../../server/tests/test_games/combat/remove_casualties_attacker.outcome.json', + import.meta.url, + ), + 'utf8', + ), + ); + game.players[0].civilization = 'China'; + game.players[1].civilization = 'Celts'; + game.log![0].rounds[0].turns[0].actions = actions; + game.log_index = actions.length; + return game; +} +function battle(game: Game) { + return combatJournal(journal(game)).find((e) => e.combat)!.combat!; +} +function legacy(fighters: number, modifiers: string, hits: number, value = 29): LoggedAction { + return { + log: [ + 'Combat round 1', + 'Player1: Combat: Attacking with 2 infantry and Vercingetorix', + `Player2: Combat: Defending with ${fighters} infantry and 2 settlers`, + `Player1: Combat: Roll 6 for combined combat value of ${value} and gets ${hits} hits against defending units`, + ...(modifiers ? [`Player2: Combat: Combat modifiers: ${modifiers}`] : []), + ], + }; +} +for (const fighters of [3, 4]) + test(`29 value vs ${fighters} fighters: fortress cancels a hit before the unit cap`, () => { + const game = gameWith([legacy(fighters, 'fortress cancelled one hit', Math.min(4, fighters))]); + const side = battle(game).attacker; + assert.equal(side.cancelledHits?.before, 5); + assert.equal(side.nominalHits, 4); + assert.equal(side.hits, fighters); + assert.deepEqual(battleCues(game, 0)[0].combat.attacker, side); + }); + +test('China/Celts 29 value: Elephant + disembark WarShips cancel 5 to 3, paid Tactician makes 2', () => { + const roll: LoggedAction = { + log: [ + 'Combat round 1', + 'Player1: Combat: Attacking with 1 infantry and 1 cavalry and 1 elephant and Qin Shi Huang', + 'Player2: Combat: Defending with 2 infantry and Vercingetorix and 2 settlers', + 'Player1: Combat: Roll 4 (elephant, -1 hits, no combat value) for combined combat value of 0 and gets 0 hits against defending units', + 'Player1: Combat: Combat modifiers: WarShips ignore the first hit in the first round of combat', + 'Player2: Combat: Roll 6 for combined combat value of 29 and gets 3 hits against attacking units', + ], + }; + const pay: LoggedAction = { log: ['Player1: Tactician: Pay 2 culture tokens, Ignore the first hit'] }; + const game = gameWith([roll, pay]); + const before = battleCues(game, 0, 1)[0].combat.defender; + assert.equal(before.cancelledHits?.before, 5); + assert.equal(before.nominalHits, 3); + assert.equal(before.hits, 3); + const cue = battleCues(game, 1, 2)[0]; + assert.equal(cue.roll, false); + assert.equal(cue.combat.defender.cancelledHits?.before, 5); + assert.equal(cue.combat.defender.nominalHits, 2); + assert.equal(cue.combat.defender.hits, 2); + assert.deepEqual(cue.combat, battle(game)); + assert.equal(roll.log!.at(-1)?.includes('gets 3 hits'), true, 'history is not rewritten'); +}); + +test('overkill without cancellation and zero hits never acquire a false strike-through', () => { + for (const [value, hits, nominal] of [ + [29, 3, 5], + [0, 0, 0], + ]) { + const side = battle(gameWith([legacy(3, '', hits, value)])).attacker; + assert.equal(side.nominalHits, nominal); + assert.equal(side.hits, hits); + assert.equal(side.cancelledHits, undefined); + } +}); + +test('explicit multi-hit cancellation quantities, unknown legacy modifiers, and failed payments', () => { + const side = battle(gameWith([legacy(4, 'Shield cancels 2 hits', 3)])).attacker; + assert.equal(side.nominalHits, 3); + assert.equal(side.cancelledHits?.before, 5); + const unknown = battle(gameWith([legacy(4, 'Unknown cancels hits', 2)])).attacker; + assert.equal(unknown.nominalHits, undefined); + assert.equal(unknown.cancelledHits, undefined); + for (const note of [ + "Won't reduce the hits, no payment made.", + 'Not enough resources, no payment made.', + 'Pay 2 culture tokens', + ]) { + const side = battle(gameWith([legacy(4, '', 4), { log: [`Player2: Tactician: ${note}`] }])).attacker; + assert.equal(side.nominalHits, 5); + assert.equal(side.hits, 4); + } +}); + +test('structured hit reports retain uncancellable extras and later authoritative totals without double subtraction', () => { + const initial: LoggedAction = { + items: [ + { + player: 0, + CombatRound: { + round: 1, + attackers: { infantry: 3 }, + defenders: { infantry: 4 }, + defending_player: 1, + }, + }, + { + player: 0, + CombatRoll: { rolls: [{ value: 6, unit_type: 'Infantry', bonus: false }], combat_value: 29, hits: 4 }, + }, + { player: 0, CombatHitReport: { combat_value: 29, hit_cancels: 2, extra_hits: 1, casualties: 4 } }, + ], + }; + const payment: LoggedAction = { + items: [{ player: 1, origin: { SpecialAdvance: 'Fireworks' }, Text: 'Ignore the first hit' }], + }; + const final: LoggedAction = { + items: [ + { player: 0, CombatHitReport: { combat_value: 29, hit_cancels: 3, extra_hits: 1, casualties: 3 } }, + ], + }; + const game = gameWith([initial, payment, final]); + assert.equal(battleCues(game, 0, 1)[0].combat.attacker.cancelledHits?.before, 6); + assert.equal(battleCues(game, 0, 1)[0].combat.attacker.nominalHits, 4); + assert.equal(battleCues(game, 1, 2)[0].combat.attacker.nominalHits, 3); + const side = battle(game).attacker; + assert.equal(side.nominalHits, 3); + assert.equal(side.hits, 3); + assert.equal(side.cancelledHits?.before, 6); + // No cancellations can remove the extra hits, even with zero combat value. + final.items![0].CombatHitReport = { combat_value: 0, hit_cancels: 7, extra_hits: 2, casualties: 2 }; + const extra = battle(game).attacker; + assert.equal(extra.nominalHits, 2); + assert.equal(extra.cancelledHits, undefined); +}); + +test('Fortress, WarShips and Elephant combine explicitly; ambiguous prose never becomes arithmetic', () => { + const roll = legacy( + 4, + 'fortress cancelled one hit, WarShips ignore the first hit in the first round of combat', + 2, + ); + roll.log!.push( + 'Player2: Combat: Roll 4 (elephant, -1 hits, no combat value) for combined combat value of 0 and gets 0 hits against attacking units', + ); + const side = battle(gameWith([roll])).attacker; + assert.equal(side.cancelledHits?.before, 5); + assert.equal(side.nominalHits, 2); + assert.equal(side.hits, 2); + for (const reason of ['Unknown cancels hits', 'Shield cancels 1 hit and another shield cancels 1 hit']) { + const unknown = battle(gameWith([legacy(3, reason, 3)])).attacker; + assert.equal(unknown.nominalHits, undefined); + assert.equal(unknown.cancelledHits, undefined); + assert.equal(unknown.hits, 3); + } +}); + +test('real engine Fireworks reports survive saved JSON and public filtering for paid/declined/unaffordable responses', async () => { + const { createRequire } = await import('node:module'); + const engine = createRequire(import.meta.url)('../.engine/server.js'); + const npcs = JSON.parse(await engine.init(2, [], {}, 'hit-reports', {})).players.slice(2); + const items = (raw: string) => JSON.parse(raw).log.flatMap((a: any) => a.rounds.flatMap((r: any) => + r.turns.flatMap((t: any) => (t.actions ?? []).flatMap((a: any) => a.items ?? [])))); + const reports = (raw: string) => items(raw).filter((i: any) => i.player === 1 && i.CombatHitReport).map((i: any) => i.CombatHitReport); + for (const outcome of ['paid', 'declined', 'unaffordable']) { + const fixture = JSON.parse(readFileSync(new URL('../../server/tests/test_games/civilizations/china/fireworks.json', import.meta.url), 'utf8')); + for (const npc of npcs) if (!fixture.players.some((p: any) => p.civilization === npc.civilization)) fixture.players.push(structuredClone(npc)); + if (outcome === 'unaffordable') fixture.players[0].resources = {}; + let raw = JSON.stringify(fixture); + const query = JSON.parse(engine.webQuery(raw, 0, JSON.stringify({ kind: 'movement', units: [0] }))); + raw = engine.tryMove(raw, JSON.stringify(query.destinations.find((d: any) => d.position === 'C1' && d.attack).action), 0); + const rolls = items(raw).filter((i: any) => i.CombatRoll); + if (outcome !== 'unaffordable') { + assert.deepEqual(reports(raw), [{combat_value: 6, hit_cancels: 0, extra_hits: 0, casualties: 1}]); + raw = engine.tryMove(raw, JSON.stringify({Response: {Payment: [outcome === 'paid' ? {gold: 2} : {}]}}), 0); + } + assert.deepEqual(reports(raw).slice(0, 2), [ + {combat_value: 6, hit_cancels: 0, extra_hits: 0, casualties: 1}, + {combat_value: 6, hit_cancels: outcome === 'paid' ? 1 : 0, extra_hits: 0, casualties: outcome === 'paid' ? 0 : 1}, + ]); + assert.deepEqual(items(raw).filter((i: any) => i.CombatRoll).slice(0, rolls.length), rolls); + for (const seat of [undefined, 0, 1]) { + const visible = engine.stripSecret(raw, seat); + assert.deepEqual(reports(visible), reports(raw)); + const parsed = JSON.parse(visible); + assert.ok(parsed.players.every((p: any, index: number) => index === seat || (p.action_cards ?? []).every((c: number) => c === 0))); + const combat = battle(parsed); + assert.equal(combat.defender.nominalHits, outcome === 'paid' ? 0 : 1); + assert.equal(combat.defender.hits, outcome === 'paid' ? 0 : 1); + } + } +}); diff --git a/web-client/src/combat-journal.ts b/web-client/src/combat-journal.ts index 50f52ab2..f6ce4c53 100644 --- a/web-client/src/combat-journal.ts +++ b/web-client/src/combat-journal.ts @@ -12,7 +12,12 @@ export interface CombatSide { units?: { type: string | { Leader: string }; count: number; label: string }[]; dice?: CombatDie[]; value?: number; + /** Capped losses from the engine, not the nominal hit total. */ hits?: number; + nominalHits?: number; + hitReport?: { value: number; cancels: number; extra: number; casualties: number; lateCount: number }; + lateCancellations?: string[]; + unresolvedHits?: boolean; cancelledHits?: { before: number; reasons: string[] }; modifiers: string[]; tactics?: string; @@ -34,18 +39,54 @@ const cancelsHits = (text: string) => ); function explainCancelledHits(side: CombatSide, opponent: CombatSide) { - if (side.value === undefined || side.hits === undefined || !opponent.units) return; const reasons = [ ...(opponent.dice ?.filter((die) => die.effect === '-1 hits, no combat value') .map(() => 'Elephant blocks 1 hit') ?? []), ...opponent.modifiers.filter(cancelsHits), ]; + const late = opponent.lateCancellations ?? []; + if (side.hitReport) { + const h = side.hitReport; + side.value = h.value; + const before = Math.floor(h.value / 5) + h.extra; + const pending = late.length - h.lateCount; + side.nominalHits = Math.max(0, Math.floor(h.value / 5) - h.cancels - pending) + h.extra; + // The engine only offers these paid abilities when each reduces losses by + // one. A later authoritative report replaces this interim projection. + side.hits = Math.max(0, h.casualties - pending); + if (before > side.nominalHits) side.cancelledHits = { before, reasons: [...reasons, ...late] }; + return; + } + if ( + side.value === undefined || + side.hits === undefined || + !opponent.units || + side.unresolvedHits || + opponent.unresolvedHits + ) + return; + // Legacy logs: count explicit quantities, never the number of reason strings. + // If the equation cannot reproduce the recorded capped result, leave it alone: + // an unrecorded modifier / extra hit cannot safely be reconstructed. + const counts = reasons.map((reason) => { + const matches = [ + ...reason.matchAll( + /\b(?:cancels?|cancelled|canceled|ignores?|ignored|blocks?|blocked) (one|a|\d+|the first) hits?\b/gi, + ), + ]; + if (matches.length !== 1) return undefined; + const quantity = matches[0][1]; + return /^\d+$/.test(quantity) ? Number(quantity) : 1; + }); + if (counts.some((n) => n === undefined)) return; const fighters = opponent.units.reduce((n, unit) => n + (unit.type === 'Settler' ? 0 : unit.count), 0); - const before = Math.min(Math.floor(side.value / 5), fighters); - // The logged hit count already includes these cancellations. Explain the reduction; - // never subtract it again or mistake the enemy unit cap for a cancelled hit. - if (reasons.length && before > side.hits) side.cancelledHits = { before, reasons }; + const before = Math.floor(side.value / 5); + const nominal = Math.max(0, before - counts.reduce((n, count) => n + count!, 0)); + if (Math.min(nominal, fighters) !== side.hits) return; + side.nominalHits = Math.max(0, nominal - late.length); + side.hits = Math.min(side.nominalHits, fighters); + if (before > side.nominalHits) side.cancelledHits = { before, reasons: [...reasons, ...late] }; } function unitCounts(text: string): NonNullable { @@ -149,6 +190,21 @@ export function combatJournal(entries: JournalEntry[]): JournalEntry[] { continue; } } + // These exact success messages are emitted only after payment. Prompts, + // declined payments and unrelated ability prose must not cancel anything. + if ( + current?.combat && + ['Tactician', 'Fireworks'].includes(entry.title) && + entry.notes.some((note) => /^Ignore the first hit$/i.test(note)) + ) { + const side = [current.combat.attacker, current.combat.defender].find((s) => s.player === entry.player); + if (side) { + (side.lateCancellations ??= []).push(`${entry.title} ignores 1 hit`); + current.combat.outcomes.push(entry); + latest(); + continue; + } + } if (entry.title !== 'Combat' || entry.player === undefined) { output.push(entry); continue; @@ -198,6 +254,20 @@ export function combatJournal(entries: JournalEntry[]): JournalEntry[] { target.hits = Number(roll[3]); text = text.replace(roll[0], ''); } + const reports = [ + ...text.matchAll(/(?:^|, )Hit report: value (\d+); cancels (\d+); extra (\d+); casualties (\d+)/g), + ]; + for (const report of reports) { + const opponent = current!.combat![role === 'attacker' ? 'defender' : 'attacker']; + target.hitReport = { + value: Number(report[1]), + cancels: Number(report[2]), + extra: Number(report[3]), + casualties: Number(report[4]), + lateCount: opponent.lateCancellations?.length ?? 0, + }; + text = text.replace(report[0], ''); + } text = text.replace(/^,\s*|,\s*$/g, ''); if (text.startsWith('Combat modifiers: ')) { const clauses = text @@ -237,7 +307,10 @@ export function combatJournal(entries: JournalEntry[]): JournalEntry[] { target.tacticsEffect = clause.replace('rolls a', 'rolled a'); } if (/combat value|extra die/i.test(clause) || cancelsHits(clause)) target.modifiers.push(clause); - else remainder.push(clause); + else { + if (/\bhits?\b/i.test(clause)) target.unresolvedHits = true; + remainder.push(clause); + } } text = remainder.join(', '); } diff --git a/web-client/src/localization/da.json b/web-client/src/localization/da.json index f11db2b9..b978d666 100644 --- a/web-client/src/localization/da.json +++ b/web-client/src/localization/da.json @@ -5276,5 +5276,10 @@ "End on": "Slut ved", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Derefter må du udforske en region, der støder op til en region, hvor du har en by. Hvis du gør det, må du betale 2 mad for at grundlægge en by i den udforskede region uden at bruge en nybygger.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Derefter må du udforske en region, der støder op til en region, hvor du har en by. Hvis du gør det, må du betale 2 mad for at grundlægge en by i den udforskede region uden at bruge en nybygger." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Derefter må du udforske en region, der støder op til en region, hvor du har en by. Hvis du gør det, må du betale 2 mad for at grundlægge en by i den udforskede region uden at bruge en nybygger.", + "{p0} ignores 1 hit": "{p0} ignorerer 1 træffer", + "Casualties": "Tab", + "Casualties:": "Tab:", + "Casualties: {p0}": "Tab: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/de.json b/web-client/src/localization/de.json index 3b04cdd5..17bf4e71 100644 --- a/web-client/src/localization/de.json +++ b/web-client/src/localization/de.json @@ -5276,5 +5276,10 @@ "End on": "Ende bei", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Danach darfst du eine Region erkunden, die an eine Region angrenzt, in der du eine Stadt hast. Wenn du dies tust, darfst du 2 Nahrung bezahlen, um in der erkundeten Region eine Stadt zu gründen, ohne einen Siedler zu verwenden.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Danach darfst du eine Region erkunden, die an eine Region angrenzt, in der du eine Stadt hast. Wenn du dies tust, darfst du 2 Nahrung bezahlen, um in der erkundeten Region eine Stadt zu gründen, ohne einen Siedler zu verwenden." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Danach darfst du eine Region erkunden, die an eine Region angrenzt, in der du eine Stadt hast. Wenn du dies tust, darfst du 2 Nahrung bezahlen, um in der erkundeten Region eine Stadt zu gründen, ohne einen Siedler zu verwenden.", + "{p0} ignores 1 hit": "{p0} ignoriert 1 Treffer", + "Casualties": "Verluste", + "Casualties:": "Verluste:", + "Casualties: {p0}": "Verluste: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/el.json b/web-client/src/localization/el.json index 3e5d140f..9fef181a 100644 --- a/web-client/src/localization/el.json +++ b/web-client/src/localization/el.json @@ -5276,5 +5276,10 @@ "End on": "Λήξη με", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Έπειτα, μπορείς να εξερευνήσεις μια περιοχή γειτονική σε περιοχή όπου έχεις πόλη. Αν το κάνεις, μπορείς να πληρώσεις 2 τροφή για να ιδρύσεις πόλη στην εξερευνημένη περιοχή, χωρίς να χρησιμοποιήσεις Άποικο.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Έπειτα, μπορείς να εξερευνήσεις μια περιοχή γειτονική σε περιοχή όπου έχεις πόλη. Αν το κάνεις, μπορείς να πληρώσεις 2 τροφή για να ιδρύσεις πόλη στην εξερευνημένη περιοχή, χωρίς να χρησιμοποιήσεις Άποικο." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Έπειτα, μπορείς να εξερευνήσεις μια περιοχή γειτονική σε περιοχή όπου έχεις πόλη. Αν το κάνεις, μπορείς να πληρώσεις 2 τροφή για να ιδρύσεις πόλη στην εξερευνημένη περιοχή, χωρίς να χρησιμοποιήσεις Άποικο.", + "{p0} ignores 1 hit": "{p0} αγνοεί 1 χτύπημα", + "Casualties": "Απώλειες", + "Casualties:": "Απώλειες:", + "Casualties: {p0}": "Απώλειες: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/en.json b/web-client/src/localization/en.json index b5d2ed2a..5cfe7ca8 100644 --- a/web-client/src/localization/en.json +++ b/web-client/src/localization/en.json @@ -5276,5 +5276,10 @@ "End on": "End on", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.", + "{p0} ignores 1 hit": "{p0} ignores 1 hit", + "Casualties": "Casualties", + "Casualties:": "Casualties:", + "Casualties: {p0}": "Casualties: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/fa.json b/web-client/src/localization/fa.json index fff6d267..49977b2b 100644 --- a/web-client/src/localization/fa.json +++ b/web-client/src/localization/fa.json @@ -5276,5 +5276,10 @@ "End on": "پایان با", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "سپس می‌توانید منطقه‌ای مجاور منطقه‌ای که در آن شهر دارید را کاوش کنید. اگر چنین کنید، می‌توانید با پرداخت ۲ غذا، بدون استفاده از مهاجر، در منطقهٔ کاوش‌شده شهری بنا کنید.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} سپس می‌توانید منطقه‌ای مجاور منطقه‌ای که در آن شهر دارید را کاوش کنید. اگر چنین کنید، می‌توانید با پرداخت ۲ غذا، بدون استفاده از مهاجر، در منطقهٔ کاوش‌شده شهری بنا کنید." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} سپس می‌توانید منطقه‌ای مجاور منطقه‌ای که در آن شهر دارید را کاوش کنید. اگر چنین کنید، می‌توانید با پرداخت ۲ غذا، بدون استفاده از مهاجر، در منطقهٔ کاوش‌شده شهری بنا کنید.", + "{p0} ignores 1 hit": "{p0} یک ضربه را نادیده می‌گیرد", + "Casualties": "تلفات", + "Casualties:": "تلفات:", + "Casualties: {p0}": "تلفات: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/fr.json b/web-client/src/localization/fr.json index 879aa290..7a165c14 100644 --- a/web-client/src/localization/fr.json +++ b/web-client/src/localization/fr.json @@ -5276,5 +5276,10 @@ "End on": "Fin sur", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Ensuite, vous pouvez explorer une région adjacente à une région où vous avez une ville. Si vous le faites, vous pouvez payer 2 nourriture pour fonder une ville dans la région explorée, sans utiliser de colon.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Ensuite, vous pouvez explorer une région adjacente à une région où vous avez une ville. Si vous le faites, vous pouvez payer 2 nourriture pour fonder une ville dans la région explorée, sans utiliser de colon." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Ensuite, vous pouvez explorer une région adjacente à une région où vous avez une ville. Si vous le faites, vous pouvez payer 2 nourriture pour fonder une ville dans la région explorée, sans utiliser de colon.", + "{p0} ignores 1 hit": "{p0} ignore 1 touche", + "Casualties": "Pertes", + "Casualties:": "Pertes:", + "Casualties: {p0}": "Pertes: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/hi.json b/web-client/src/localization/hi.json index 6355df58..c6769146 100644 --- a/web-client/src/localization/hi.json +++ b/web-client/src/localization/hi.json @@ -5276,5 +5276,10 @@ "End on": "समाप्ति का परिणाम", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "इसके बाद, आप उस क्षेत्र के पड़ोसी क्षेत्र की खोज कर सकते हैं जहाँ आपका शहर है। यदि आप ऐसा करते हैं, तो आप बसने वाले का उपयोग किए बिना खोजे गए क्षेत्र में शहर बसाने के लिए 2 भोजन दे सकते हैं।", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} इसके बाद, आप उस क्षेत्र के पड़ोसी क्षेत्र की खोज कर सकते हैं जहाँ आपका शहर है। यदि आप ऐसा करते हैं, तो आप बसने वाले का उपयोग किए बिना खोजे गए क्षेत्र में शहर बसाने के लिए 2 भोजन दे सकते हैं।" + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} इसके बाद, आप उस क्षेत्र के पड़ोसी क्षेत्र की खोज कर सकते हैं जहाँ आपका शहर है। यदि आप ऐसा करते हैं, तो आप बसने वाले का उपयोग किए बिना खोजे गए क्षेत्र में शहर बसाने के लिए 2 भोजन दे सकते हैं।", + "{p0} ignores 1 hit": "{p0} 1 प्रहार को अनदेखा करता है", + "Casualties": "हताहत", + "Casualties:": "हताहत:", + "Casualties: {p0}": "हताहत: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/it.json b/web-client/src/localization/it.json index c891f128..6164e580 100644 --- a/web-client/src/localization/it.json +++ b/web-client/src/localization/it.json @@ -5276,5 +5276,10 @@ "End on": "Fine con", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Poi puoi esplorare una regione adiacente a una regione in cui hai una città. Se lo fai, puoi pagare 2 cibo per fondare una città nella regione esplorata, senza usare un Colono.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Poi puoi esplorare una regione adiacente a una regione in cui hai una città. Se lo fai, puoi pagare 2 cibo per fondare una città nella regione esplorata, senza usare un Colono." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Poi puoi esplorare una regione adiacente a una regione in cui hai una città. Se lo fai, puoi pagare 2 cibo per fondare una città nella regione esplorata, senza usare un Colono.", + "{p0} ignores 1 hit": "{p0} ignora 1 colpo", + "Casualties": "Perdite", + "Casualties:": "Perdite:", + "Casualties: {p0}": "Perdite: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/ko.json b/web-client/src/localization/ko.json index 142f232c..5bba6db4 100644 --- a/web-client/src/localization/ko.json +++ b/web-client/src/localization/ko.json @@ -5276,5 +5276,10 @@ "End on": "종료 결과", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "그런 다음, 자신의 도시가 있는 지역에 인접한 지역을 탐험할 수 있습니다. 그렇게 했다면 식량 2개를 지불하여 개척자를 사용하지 않고 탐험한 지역에 도시를 건설할 수 있습니다.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} 그런 다음, 자신의 도시가 있는 지역에 인접한 지역을 탐험할 수 있습니다. 그렇게 했다면 식량 2개를 지불하여 개척자를 사용하지 않고 탐험한 지역에 도시를 건설할 수 있습니다." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} 그런 다음, 자신의 도시가 있는 지역에 인접한 지역을 탐험할 수 있습니다. 그렇게 했다면 식량 2개를 지불하여 개척자를 사용하지 않고 탐험한 지역에 도시를 건설할 수 있습니다.", + "{p0} ignores 1 hit": "{p0}: 적중 1회 무시", + "Casualties": "사상자", + "Casualties:": "사상자:", + "Casualties: {p0}": "사상자: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/nl.json b/web-client/src/localization/nl.json index 64eba606..a7d69a29 100644 --- a/web-client/src/localization/nl.json +++ b/web-client/src/localization/nl.json @@ -5276,5 +5276,10 @@ "End on": "Einde bij", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Daarna mag je een regio verkennen die grenst aan een regio waar je een stad hebt. Als je dat doet, mag je 2 voedsel betalen om in de verkende regio een stad te stichten, zonder een kolonist te gebruiken.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Daarna mag je een regio verkennen die grenst aan een regio waar je een stad hebt. Als je dat doet, mag je 2 voedsel betalen om in de verkende regio een stad te stichten, zonder een kolonist te gebruiken." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Daarna mag je een regio verkennen die grenst aan een regio waar je een stad hebt. Als je dat doet, mag je 2 voedsel betalen om in de verkende regio een stad te stichten, zonder een kolonist te gebruiken.", + "{p0} ignores 1 hit": "{p0} negeert 1 treffer", + "Casualties": "Verliezen", + "Casualties:": "Verliezen:", + "Casualties: {p0}": "Verliezen: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/pl.json b/web-client/src/localization/pl.json index 4ca04d1d..f70d36e3 100644 --- a/web-client/src/localization/pl.json +++ b/web-client/src/localization/pl.json @@ -5276,5 +5276,10 @@ "End on": "Koniec przy", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Następnie możesz odkryć region sąsiadujący z regionem, w którym masz miasto. Jeśli to zrobisz, możesz zapłacić 2 żywności, aby założyć miasto w odkrytym regionie bez użycia osadnika.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Następnie możesz odkryć region sąsiadujący z regionem, w którym masz miasto. Jeśli to zrobisz, możesz zapłacić 2 żywności, aby założyć miasto w odkrytym regionie bez użycia osadnika." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Następnie możesz odkryć region sąsiadujący z regionem, w którym masz miasto. Jeśli to zrobisz, możesz zapłacić 2 żywności, aby założyć miasto w odkrytym regionie bez użycia osadnika.", + "{p0} ignores 1 hit": "{p0} ignoruje 1 trafienie", + "Casualties": "Straty", + "Casualties:": "Straty:", + "Casualties: {p0}": "Straty: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/pt-BR.json b/web-client/src/localization/pt-BR.json index 2586f5c3..336596c2 100644 --- a/web-client/src/localization/pt-BR.json +++ b/web-client/src/localization/pt-BR.json @@ -5276,5 +5276,10 @@ "End on": "Termina com", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Depois, você pode explorar uma região adjacente a uma região onde você tem uma cidade. Se fizer isso, pode pagar 2 comida para fundar uma cidade na região explorada, sem usar um Colono.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Depois, você pode explorar uma região adjacente a uma região onde você tem uma cidade. Se fizer isso, pode pagar 2 comida para fundar uma cidade na região explorada, sem usar um Colono." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Depois, você pode explorar uma região adjacente a uma região onde você tem uma cidade. Se fizer isso, pode pagar 2 comida para fundar uma cidade na região explorada, sem usar um Colono.", + "{p0} ignores 1 hit": "{p0} ignora 1 acerto", + "Casualties": "Baixas", + "Casualties:": "Baixas:", + "Casualties: {p0}": "Baixas: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/ro.json b/web-client/src/localization/ro.json index c0f92743..3dccfae2 100644 --- a/web-client/src/localization/ro.json +++ b/web-client/src/localization/ro.json @@ -5276,5 +5276,10 @@ "End on": "Sfârșit la", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Apoi poți explora o regiune adiacentă unei regiuni în care ai un oraș. Dacă o faci, poți plăti 2 hrană pentru a întemeia un oraș în regiunea explorată, fără a folosi un Colonist.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Apoi poți explora o regiune adiacentă unei regiuni în care ai un oraș. Dacă o faci, poți plăti 2 hrană pentru a întemeia un oraș în regiunea explorată, fără a folosi un Colonist." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Apoi poți explora o regiune adiacentă unei regiuni în care ai un oraș. Dacă o faci, poți plăti 2 hrană pentru a întemeia un oraș în regiunea explorată, fără a folosi un Colonist.", + "{p0} ignores 1 hit": "{p0} ignoră 1 lovitură", + "Casualties": "Pierderi", + "Casualties:": "Pierderi:", + "Casualties: {p0}": "Pierderi: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/ru.json b/web-client/src/localization/ru.json index 198b7d0f..a487b8da 100644 --- a/web-client/src/localization/ru.json +++ b/web-client/src/localization/ru.json @@ -5276,5 +5276,10 @@ "End on": "Конец при", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Затем вы можете исследовать регион, соседний с регионом, где у вас есть город. Если вы это сделаете, можете заплатить 2 еды, чтобы основать город в исследованном регионе, не используя поселенца.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Затем вы можете исследовать регион, соседний с регионом, где у вас есть город. Если вы это сделаете, можете заплатить 2 еды, чтобы основать город в исследованном регионе, не используя поселенца." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Затем вы можете исследовать регион, соседний с регионом, где у вас есть город. Если вы это сделаете, можете заплатить 2 еды, чтобы основать город в исследованном регионе, не используя поселенца.", + "{p0} ignores 1 hit": "{p0} игнорирует 1 попадание", + "Casualties": "Потери", + "Casualties:": "Потери:", + "Casualties: {p0}": "Потери: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/vi.json b/web-client/src/localization/vi.json index 04f8f197..745dfd3e 100644 --- a/web-client/src/localization/vi.json +++ b/web-client/src/localization/vi.json @@ -5276,5 +5276,10 @@ "End on": "Kết thúc khi ra", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "Sau đó, bạn có thể khám phá một vùng liền kề với vùng có thành phố của bạn. Nếu làm vậy, bạn có thể trả 2 lương thực để lập một thành phố trong vùng vừa khám phá mà không dùng Người định cư.", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Sau đó, bạn có thể khám phá một vùng liền kề với vùng có thành phố của bạn. Nếu làm vậy, bạn có thể trả 2 lương thực để lập một thành phố trong vùng vừa khám phá mà không dùng Người định cư." + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} Sau đó, bạn có thể khám phá một vùng liền kề với vùng có thành phố của bạn. Nếu làm vậy, bạn có thể trả 2 lương thực để lập một thành phố trong vùng vừa khám phá mà không dùng Người định cư.", + "{p0} ignores 1 hit": "{p0} bỏ qua 1 đòn đánh", + "Casualties": "Thương vong", + "Casualties:": "Thương vong:", + "Casualties: {p0}": "Thương vong: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/zh-CN.json b/web-client/src/localization/zh-CN.json index c9132789..a8376fb3 100644 --- a/web-client/src/localization/zh-CN.json +++ b/web-client/src/localization/zh-CN.json @@ -5276,5 +5276,10 @@ "End on": "结束点数", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "然后,你可以探索与你拥有城市的地区相邻的一个地区。如果这样做,你可以支付2食物,在探索的地区建立一座城市,无需使用移民。", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} 然后,你可以探索与你拥有城市的地区相邻的一个地区。如果这样做,你可以支付2食物,在探索的地区建立一座城市,无需使用移民。" + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} 然后,你可以探索与你拥有城市的地区相邻的一个地区。如果这样做,你可以支付2食物,在探索的地区建立一座城市,无需使用移民。", + "{p0} ignores 1 hit": "{p0} 忽略 1 次命中", + "Casualties": "伤亡", + "Casualties:": "伤亡:", + "Casualties: {p0}": "伤亡: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/localization/zh-TW.json b/web-client/src/localization/zh-TW.json index a62afdb6..393f3278 100644 --- a/web-client/src/localization/zh-TW.json +++ b/web-client/src/localization/zh-TW.json @@ -5276,5 +5276,10 @@ "End on": "結束點數", "{p0} · {p1} {p2}": "{p0} · {p1} {p2}", "Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "然後,你可以探索與你擁有城市的地區相鄰的一個地區。如果這樣做,你可以支付2食物,在探索的地區建立一座城市,無需使用移民。", - "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} 然後,你可以探索與你擁有城市的地區相鄰的一個地區。如果這樣做,你可以支付2食物,在探索的地區建立一座城市,無需使用移民。" + "{p0} Then, you may explore a region adjacent to a region where you have a city. If you do, you may pay 2 food to found a city in the explored region, without using a Settler.": "{p0} 然後,你可以探索與你擁有城市的地區相鄰的一個地區。如果這樣做,你可以支付2食物,在探索的地區建立一座城市,無需使用移民。", + "{p0} ignores 1 hit": "{p0} 忽略 1 次命中", + "Casualties": "傷亡", + "Casualties:": "傷亡:", + "Casualties: {p0}": "傷亡: {p0}", + "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}": "Hit report: value {p0}; cancels {p1}; extra {p2}; casualties {p3}" } diff --git a/web-client/src/structured-log.ts b/web-client/src/structured-log.ts index 1ce58a63..04ed19d0 100644 --- a/web-client/src/structured-log.ts +++ b/web-client/src/structured-log.ts @@ -169,6 +169,10 @@ function lines(game: Game, action: LoggedAction, context?: Context): string[] { if (roll.combat_modifiers?.length) add(item.player, 'Combat', `Combat modifiers: ${roll.combat_modifiers.join(', ')}`); } + if (item.CombatHitReport) { + const h = item.CombatHitReport; + add(item.player, 'Combat', `Hit report: value ${h.combat_value}; cancels ${h.hit_cancels}; extra ${h.extra_hits}; casualties ${h.casualties}`); + } if (item.InfluenceCultureAttempt) { const attempt = item.InfluenceCultureAttempt; write( diff --git a/web-client/src/tactician.test.ts b/web-client/src/tactician.test.ts index 54e9d1ac..b1d03f63 100644 --- a/web-client/src/tactician.test.ts +++ b/web-client/src/tactician.test.ts @@ -61,12 +61,24 @@ for (const declineFirst of [false, true]) } else if (r.BoolRequest) { response = { Bool: false }; } else assert.fail(JSON.stringify(h)); + const items = (state: any) => state.log.flatMap((a: any) => a.rounds.flatMap((r: any) => + r.turns.flatMap((t: any) => (t.actions ?? []).flatMap((a: any) => a.items ?? [])))); + const beforeItems = items(g); + const beforeReport = beforeItems.filter((i: any) => i.player === 1 && i.CombatHitReport).at(-1)?.CombatHitReport; // Round trips through saved JSON must preserve the once-per-battle marker. raw = engine.tryMove( JSON.stringify(g), JSON.stringify({ Response: response }), engine.currentPlayer(raw), ); + if (r.Payment) { + const afterItems = items(JSON.parse(raw)); + const final = afterItems.slice(beforeItems.length).find((i: any) => i.player === 1 && i.CombatHitReport)?.CombatHitReport; + assert.ok(beforeReport && final, 'Roll and post-payment hit reports must both exist'); + const reduction = response.Payment?.[0].culture_tokens ? 1 : 0; + assert.deepEqual(final, { ...beforeReport, hit_cancels: beforeReport.hit_cancels + reduction, casualties: beforeReport.casualties - reduction }); + assert.deepEqual(afterItems.slice(0, beforeItems.length), beforeItems, 'Payment must not rewrite earlier rolls or reports'); + } } assert.equal(paid, 1); assert.equal(offers, declineFirst ? 2 : 1); diff --git a/web-client/src/types.ts b/web-client/src/types.ts index 356400be..25d3db21 100644 --- a/web-client/src/types.ts +++ b/web-client/src/types.ts @@ -115,6 +115,12 @@ export interface LoggedAction { defenders: Record; defending_player: number; }; + CombatHitReport?: { + combat_value: number; + hit_cancels: number; + extra_hits: number; + casualties: number; + }; CombatRoll?: { rolls: { value: number;