Finalize both armies' combat modifiers before casualties; prepare 0.4.166

This commit is contained in:
coyotte508 2026-11-22 16:45:28 +00:00
commit b20ed37e87
27 changed files with 6748 additions and 16 deletions

View file

@ -28,6 +28,8 @@ jobs:
working-directory: web-client
- run: npm run test:boarding && node scripts/embark-smoke.mjs && node scripts/ship-landing-smoke.mjs
working-directory: web-client
- run: node scripts/horse-master-smoke.mjs
working-directory: web-client
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: clash-viewer

View file

@ -0,0 +1,163 @@
# Combat round finalization — viewer 0.1.235 / engine 0.4.166
Baseline: `60484d3d`, viewer 0.1.234 / engine 0.4.165. Prepared for release;
publication follows source push and green CI. No production game writes or save repair.
## Rule verification
The Huns source entry in `civilization-sources.json` links the secondary guide
<https://boardgamegeek.com/thread/2684906> and primary photograph
<https://boardgamegeek.com/image/9490522>. The **actual original photograph was
opened and visually read** (retrieved via `api.geekdo.com/api/images/9490522`,
then its `images.original.url`; the ordinary BGG HTML returned a challenge).
Attila L22 says:
> Horse Master — 1st combat round: 1 Cavalry unit in his Army may instead use the
> Elephant Clash ability when triggering a Cavalry Clash icon.
The official Monumental rulebook linked in that same source file was downloaded
and pages 22–23 read using PDF text extraction. Page 22 specifies Cavalry +2 CV
and Elephant: “The value on the die does not add to your CV, but you cancel an
opponent’s hit.” Page 23 determines casualties from **final** CV, with hit-cancel
abilities applied in the casualty step, and ends combat when either army is gone.
This supports replacing the activated Cavalry face plus its bonus, not merely
subtracting two CV. No claim is made to having newly read the secondary guide.
## Cause and implementation
Persistent events finish *all* listeners for attacker before beginning defender.
A priority 99 defender Horse Master listener therefore ran after priority 1
attacker casualty removal. Raising its priority cannot solve the problem.
New battles use these persisted phases:
1. Existing round-end tactics for both players.
2. `RoundEndModifiers`: both players finish hit-changing abilities/payments.
3. `RoundEndFinalize`: hit-dependent rewards, final reports, casualty choices and
removal, and surviving-leader effects.
4. Existing post-casualty retreat phase.
The original registered round-end event is retained. Copies select its two
priority bands, preserving listener origins and response priorities. The explicit
contract is **priority > 10 for modifiers; <= 10 for consumers of finalized hits**.
Future round-end listeners must respect that contract. This avoids duplicating
ability implementations or changing legacy saved response cursors. Both copies
are reconstructed on resume, including after a JSON reload. Ordinary attacker-
then-defender preparation and all movement rules remain unchanged.
### Complete round-end listener audit
| Listener | Priority | Dependency / phase |
| --- | ---: | --- |
| Attila Horse Master | 99 | Changes own CV and opposing hit cancels; modifiers |
| Phoenician Protector | 92 | Optional paid cancellation, once/battle marker and later refund; modifiers |
| Qin Tactician | 92 | Optional paid cancellation, once/battle marker; modifiers |
| Fireworks | 91 | Optional first-round paid cancellation; modifiers |
| Colosseum | 90 | Optional paid CV increase; modifiers |
| Ahuitzotl Expansionist | 35 | Leader-dependent automatic cancellation; modifiers, before leader losses |
| Solar Eclipse | 10 | Uses final result to award VP and terminate battle; finalize |
| Final hit reports | 9 | Both players’ adjusted totals before either casualty prompt; finalize |
| Pirate ship reward | 3 | Uses hits for gold reward; finalize |
| Choose Casualties | 1 | Removal/selection (legacy reporting order retained); finalize |
| Legacy retreat compatibility | 0 | No new prompts; accepts already-saved responses on old path |
| Dido Sacrifice | -50 | Requires surviving leader/city and no final result; finalize after defender casualties |
`combat_round_end_tactics` is separate: Encircled modifies hits and Surprise
awards its card using the existing tactics resolution semantics. Both remain in
the existing tactics phase, ahead of ability modifiers; this change does not
reinterpret conditional tactics timing. Tactics-reveal sacrifice/withdrawal is
also unchanged. All ordinary hit modifications finish before casualty listeners.
Horse Master's existing conversion calculation is retained, including the
Persian bonus cap marginal calculation. The converted CV lives in `CombatHits`;
final reports contain 8 rather than 12. Original rolls remain 12, unchanged in
history. Existing viewer hit-report handling already displays the adjusted total
and emits no fresh dice animation; no presentation code change was necessary.
## Legacy saves and replay
`Combat.finalized_round_end` selects the mode for the entire battle. Missing means
legacy, including a pending Horse Master prompt whose attacker losses have
already happened. **Those losses are not undone, reconstructed, or repaired.**
An open old battle remains old for all subsequent rounds. This intentionally
preserves old execution, including the known defect, rather than silently
changing or invalidating its recorded response sequence. A separate explicit
repair would need user authorization and is not supplied here.
`finalized_combat_from` follows the independent asynchronous-preparation history
boundary pattern. New games use zero. Old live saves record the current history
index at their first new battle. Replay lacking the marker stays legacy through
recorded history. Playable replay cursors and fresh branches clamp the boundary
to the next action; redo preserves it. Undo patches exclude the boundary. This
marker does not change the preparation-mode marker. Historical golden fixtures
explicitly retain legacy mode; synthetic regressions exercise the new mode.
## Regression coverage
Native and real locally built WASM tests construct a public synthetic battle from
an existing small test board, not a private production snapshot:
- India: Flanking, 5 Infantry / 2 Elephant / 5 Infantry, all symbols blocked by
High Ground: 12 CV.
- Huns: Attila + Cavalry, activated 2 Cavalry / unactivated 6 Infantry, paid Steel
Weapons: 12 CV.
- Before defender Horse Master: both sides still have two units. Accepting gives
Huns 8 CV, India one canceled hit, and one loss each. Both surviving armies
reach round two, with no second Horse Master offer.
- Declining preserves the original totals and ends in a draw.
- Attacker Horse Master followed by defender Qin payment: both armies remain
untouched until both decisions resolve, including across JSON reloads.
- No Attila / no activated Cavalry, extra dice with exhausted Cavalry activation,
disabled symbols, and capped/uncapped CV contributions.
- Both final hit reports, original dice/history preservation, adjusted viewer CV,
and no fake reroll animation.
- An explicitly legacy pending defender prompt retains its already-removed
attackers across reload; no attempted repair.
- Historical replay/branch and undo/redo tests assert both independent mode markers.
The new defender survivor assertion was also run against the preserved legacy
path: it fails with **0 attackers instead of 2 before the prompt**. The same
assertion passes on the new phase path.
### Local validation
- `cargo test -p server --quiet`: 569 passed, 1 ignored, no failures.
- `cargo check --workspace --quiet`: passed (server and native client).
- `bash web-client/scripts/build-bridge.sh`: rebuilt the local WASM engine.
- `node --experimental-strip-types --test src/*.test.ts` in `web-client`:
1,188 passed, no failures, against that rebuilt engine.
- `npm run check` in `web-client`: zero errors and warnings.
- `git diff --check`: passed.
Full-suite testing also covered reveal-time battle termination. That path now
enters the matching new modifier phase instead of the legacy `Default` phase;
otherwise the phase lookup would reject it. No Tactical Retreat destinations,
movement rules, or withdrawal behavior were changed.
## Release regression additions
`horse-master-smoke.mjs` runs the production viewer/controller and built WASM
at 1400px and 390px. The normal choice UI accepts Horse Master and selects a
Cavalry casualty: final values 12/8, one hit each, original dice unchanged, no
roll-animation class, one surviving unit on each side and the retreat prompt.
CI runs this smoke after building the viewer.
`legacy_horse_master_165.json` is frozen output from the published 0.4.165
package, generated only by the explicit maintenance script. It preserves the
old pending Horse Master outcome, including already removed attackers. Its
separate legally generated from-init history verifies full and partial replay
outcomes and the next-action boundary. The synthetic battle is **not** claimed
to be a from-init replay history: that exact combined scenario remains outside
this fixture. Native boundary tests cover new battles after replay and undo/redo.
Release keeps achievement catalog revision 8 (46 entries), nonfaction art revision
4 and all 60 live asset URLs/bytes unchanged. The faction manifest lockfile hash
changes only because the viewer package version changes; no art input changes.
Frozen fixture provenance: published engine archive SHA-256
`47601b7c4bff38e08cc03aadcaa47ecd35a860e0272ebdd70743d1e105c97a45`.
The new browser smoke and all npm ancillary suites pass. Pinned Rust 1.94.1
workspace check, formatting and ordinary workspace/all-target Clippy pass.
An additional stricter `-D warnings` Clippy experiment fails on existing
repository lint warnings; the repository CI uses ordinary Clippy with
`RUSTFLAGS=''`. No lint settings were changed for this release.

View file

@ -0,0 +1,51 @@
// Explicit maintenance command only. Use the immutable published engine 0.4.165.
// CLASH_WASM=/absolute/path/to/0.4.165/package/server.js node scripts/generate-legacy-horse-master.mjs
import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import {
battle,
respond,
engine,
} from "../web-client/scripts/horse-master-fixture.mjs";
assert.equal(
JSON.parse(
readFileSync(join(dirname(process.env.CLASH_WASM), "package.json")),
).version,
"0.4.165",
);
const pending = JSON.parse(battle());
const accepted = JSON.parse(respond(JSON.stringify(pending), { Bool: true }));
// A separate from-init legal history exercises reconstruction, without pretending
// that the synthetic Horse Master board can be reconstructed from its seed.
let history = await engine.init(2, [], {}, "legacy-finalization-165", {});
const cursors = [];
for (let i = 0; i < 2; i++) {
history = engine.tryMove(
history,
JSON.stringify({ Playing: "EndTurn" }),
engine.currentPlayer(history),
);
cursors.push({
to: engine.logLength(history),
state: JSON.parse(engine.replay(history, {})),
});
}
// Synthetic board, real old-engine actions: not a from-init replay history.
writeFileSync(
new URL(
"../server/tests/fixtures/legacy_horse_master_165.json",
import.meta.url,
),
JSON.stringify(
{
engine: "0.4.165",
pending,
accepted,
history: JSON.parse(history),
cursors,
},
null,
2,
) + "\n",
);

View file

@ -51,6 +51,8 @@ pub enum CombatRetreatState {
pub struct Combat {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub asynchronous_preparation: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub finalized_round_end: bool,
pub attackers: Vec<u32>,
pub retreat: CombatRetreatState,
#[serde(default)]
@ -64,6 +66,7 @@ impl Combat {
pub fn new(attackers: Vec<u32>, can_retreat: bool, stats: CombatStats) -> Self {
Self {
asynchronous_preparation: false,
finalized_round_end: false,
attackers,
modifiers: vec![],
retreat: if can_retreat {
@ -227,6 +230,8 @@ pub fn initiate_combat(
let index = crate::game_api::log_length(game);
let from = *game.asynchronous_combat_from.get_or_insert(index);
combat.asynchronous_preparation = index >= from;
let from = *game.finalized_combat_from.get_or_insert(index);
combat.finalized_round_end = index >= from;
log_round(game, &combat);
start_combat(game, combat);
}
@ -351,7 +356,13 @@ pub(crate) fn combat_loop(game: &mut Game, mut s: CombatRoundStart) {
c,
);
round_end.final_result = Some(result);
round_end.phase = CombatEventPhase::Default;
// A reveal-time battle result skips round-end tactics, but must still
// enter the correct ability/finalization pipeline for this battle.
round_end.phase = if round_end.combat.finalized_round_end {
CombatEventPhase::RoundEndModifiers
} else {
CombatEventPhase::Default
};
round_end
} else {
let mut a = CombatRoundStats::roll(c.attacker(), &c, game, s.attacker_strength);

View file

@ -74,6 +74,8 @@ pub enum CombatEventPhase {
RevealTacticsCard,
TacticsCard,
Retreat,
RoundEndModifiers,
RoundEndFinalize,
Done,
}
@ -307,7 +309,10 @@ pub(crate) fn combat_round_start(
CombatEventPhase::Default => |e| &mut e.combat_round_start,
CombatEventPhase::RevealTacticsCard => |e| &mut e.combat_round_start_reveal_tactics,
CombatEventPhase::TacticsCard => |e| &mut e.combat_round_start_tactics,
CombatEventPhase::Retreat | CombatEventPhase::Done => panic!("Invalid round type"),
CombatEventPhase::Retreat
| CombatEventPhase::RoundEndModifiers
| CombatEventPhase::RoundEndFinalize
| CombatEventPhase::Done => panic!("Invalid round type"),
},
|s| &mut s.phase,
|s| &s.combat,
@ -400,14 +405,36 @@ const ROUND_END_TYPES: &[CombatEventPhase; 3] = &[
CombatEventPhase::Retreat,
];
// Round-end priorities above 10 are hit modifiers; priorities <= 10 consume
// finalized hits (Solar Eclipse, pirate rewards, casualties, legacy retreat, Dido).
// Keep the original event intact for old battles and their saved response cursors.
const FINALIZED_ROUND_END_TYPES: &[CombatEventPhase] = &[
CombatEventPhase::TacticsCard,
CombatEventPhase::RoundEndModifiers,
CombatEventPhase::RoundEndFinalize,
CombatEventPhase::Retreat,
];
pub(crate) fn combat_round_end(game: &mut Game, r: CombatRoundEnd) -> Option<Combat> {
let phases = if r.combat.finalized_round_end {
for player in r.combat.players() {
let events = &mut game.player_mut(player).events.persistent;
events.combat_round_end_modifiers = events.combat_round_end.priority_band(|p| p > 10);
events.combat_round_end_finalize = events.combat_round_end.priority_band(|p| p <= 10);
}
FINALIZED_ROUND_END_TYPES
} else {
ROUND_END_TYPES
};
let e = event_with_tactics(
game,
r,
PersistentEventType::CombatRoundEnd,
ROUND_END_TYPES,
phases,
|phase| match phase {
CombatEventPhase::Default => |e| &mut e.combat_round_end,
CombatEventPhase::RoundEndModifiers => |e| &mut e.combat_round_end_modifiers,
CombatEventPhase::RoundEndFinalize => |e| &mut e.combat_round_end_finalize,
CombatEventPhase::TacticsCard => |e| &mut e.combat_round_end_tactics,
CombatEventPhase::Retreat => |e| &mut e.combat_retreat,
_ => panic!("Invalid round type"),
@ -564,7 +591,9 @@ pub(crate) fn event_with_tactics<T: Clone + PartialEq>(
event_type = (match t {
CombatEventPhase::Default
| CombatEventPhase::AllowTacticsCard
| CombatEventPhase::Retreat => game.trigger_persistent_event(
| CombatEventPhase::Retreat
| CombatEventPhase::RoundEndModifiers
| CombatEventPhase::RoundEndFinalize => game.trigger_persistent_event(
&get_combat(&event_type).players(),
event,
event_type,
@ -690,6 +719,18 @@ fn add_tactics_listener(
pub(crate) fn choose_fighter_casualties() -> Ability {
Ability::builder("Choose Casualties", "Choose which carried units to remove.")
.add_simple_persistent_event_listener(
|event| &mut event.combat_round_end,
9,
|game, player, r| {
if r.combat.finalized_round_end && r.role(player.index).is_attacker() {
// Publish both finalized totals before either casualty prompt,
// even if the attacker must choose among different unit types.
r.attacker.report(game, r.combat.attacker());
r.defender.report(game, r.combat.defender());
}
},
)
.add_units_request(
|event| &mut event.combat_round_end,
1,
@ -703,12 +744,14 @@ 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());
// Preserve legacy reporting order for old saved battles. New
// battles published both totals before either casualty prompt.
if !r.combat.finalized_round_end {
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 {

View file

@ -327,6 +327,72 @@ fn roll_die(game: &mut Game, roll_log: &mut Vec<UnitCombatRoll>) -> CombatDieRol
mod hit_reporting_tests {
use super::*;
#[test]
fn horse_master_tracks_one_activated_cavalry_face_and_actual_capped_bonus() {
use crate::{cache::Cache, game::GameContext, game_data::GameData};
let data: GameData =
serde_json::from_str(include_str!("../tests/test_games/combat/retreat.json")).unwrap();
let cache = Cache::new(&data.options);
let mut game = Game::from_data(data, cache, GameContext::Play);
crate::log::add_log_action(
&mut game,
crate::action::Action::Response(
crate::content::persistent_events::EventResponse::Bool(false),
),
);
// One cavalry: a second cavalry icon is a plain face, not another activation.
for (dice, deny, cap, extra, expected_value, converted) in [
(vec![6, 2], false, false, 0, 8, Some(4)),
(vec![4, 6], false, false, 0, 9, Some(6)),
(vec![4, 8], false, false, 0, 10, Some(7)),
(vec![6, 2], true, false, 0, 6, None),
(vec![10, 9], false, false, 0, 11, None),
(vec![6, 2], false, true, 2, 8, Some(2)),
(vec![6, 2], false, true, 0, 8, Some(4)),
(vec![6, 2], false, false, 2, 10, Some(4)),
] {
game.dice_roll_outcomes = dice;
// Only unit 1 is fighting (the fixture's cavalry), plus an extra die.
let result = roll(
&mut game,
0,
&vec![1],
1,
extra,
deny,
cap,
false,
&mut vec![],
);
assert_eq!(result.combat_value, expected_value);
assert_eq!(result.horse_master_value, converted);
}
game.player_mut(0)
.units
.iter_mut()
.find(|u| u.id == 0)
.unwrap()
.unit_type = Cavalry;
game.dice_roll_outcomes = vec![6, 2];
let result = roll(
&mut game,
0,
&vec![0, 1],
0,
0,
false,
false,
false,
&mut vec![],
);
assert_eq!(result.combat_value, 10);
assert_eq!(
result.horse_master_value,
Some(4),
"only one of two activated cavalry converts"
);
}
#[test]
fn hit_reports_preserve_uncapped_arithmetic_without_changing_casualties() {
for (value, cancels, extra, fighters, casualties) in [

View file

@ -210,6 +210,17 @@ where
self.listeners.reverse();
}
/// Copy a priority band without changing listener identity or saved response priorities.
pub(crate) fn priority_band(&self, include: impl Fn(i32) -> bool) -> Self
where
U: Clone,
V: Clone,
{
let mut event = self.clone();
event.listeners.retain(|l| include(l.priority));
event
}
pub(crate) fn remove_listener_mut_by_key(&mut self, key: &EventOrigin) {
let _ = self.listeners.remove(
self.listeners

View file

@ -156,6 +156,7 @@ pub struct Game {
pub context: GameContext, // transient
pub options: GameOptions,
pub asynchronous_combat_from: Option<usize>,
pub finalized_combat_from: Option<usize>,
pub home_layout: crate::map::HomeLayout,
pub version: u16, // JSON schema version
pub state: GameState,

View file

@ -39,6 +39,8 @@ pub struct GameData {
version: u16,
#[serde(default, skip_serializing_if = "Option::is_none")]
asynchronous_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
finalized_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "crate::map::HomeLayout::is_legacy")]
home_layout: crate::map::HomeLayout,
#[serde(default)]
@ -155,6 +157,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
options: data.options,
version: data.version,
asynchronous_combat_from: data.asynchronous_combat_from,
finalized_combat_from: data.finalized_combat_from,
home_layout: data.home_layout,
state: data.state,
players: Vec::new(),
@ -217,6 +220,7 @@ pub fn data(game: Game) -> GameData {
options: game.options,
version: game.version,
asynchronous_combat_from: game.asynchronous_combat_from,
finalized_combat_from: game.finalized_combat_from,
home_layout: game.home_layout,
state: game.state,
events: game.events,
@ -265,6 +269,7 @@ pub fn cloned_data(game: &Game) -> GameData {
options: game.options.clone(),
version: game.version,
asynchronous_combat_from: game.asynchronous_combat_from,
finalized_combat_from: game.finalized_combat_from,
home_layout: game.home_layout,
state: game.state.clone(),
events: game.events.clone(),

View file

@ -206,6 +206,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
seed: setup.seed.clone(),
context: GameContext::Play,
asynchronous_combat_from: Some(0),
finalized_combat_from: Some(0),
version: JSON_SCHEMA_VERSION,
options: GameOptions {
legacy_undo: None,

View file

@ -457,6 +457,7 @@ pub(crate) fn add_log_action(game: &mut Game, item: Action) {
// must retain the recorded format boundary for deterministic history.
let next = crate::game_api::log_length(game).saturating_add(1);
game.asynchronous_combat_from = game.asynchronous_combat_from.map(|from| from.min(next));
game.finalized_combat_from = game.finalized_combat_from.map(|from| from.min(next));
}
let l = &mut current_turn_log_mut(game).actions;
remove_redo_actions(l, i);

View file

@ -133,6 +133,8 @@ pub(crate) struct PersistentEvents {
pub combat_round_start_reveal_tactics: PersistentEvent<CombatRoundStart>,
pub combat_round_start_tactics: PersistentEvent<CombatRoundStart>,
pub combat_round_end: PersistentEvent<CombatRoundEnd>,
pub combat_round_end_modifiers: PersistentEvent<CombatRoundEnd>,
pub combat_round_end_finalize: PersistentEvent<CombatRoundEnd>,
pub combat_round_end_tactics: PersistentEvent<CombatRoundEnd>,
pub combat_retreat: PersistentEvent<CombatRoundEnd>,
pub combat_end: PersistentEvent<CombatStats>,
@ -176,6 +178,8 @@ impl PersistentEvents {
combat_round_start_allow_tactics: Event::new("combat_round_start_allow_tactics"),
combat_round_start_tactics: Event::new("combat_round_start_tactics"),
combat_round_end: Event::new("combat_round_end"),
combat_round_end_modifiers: Event::new("combat_round_end_modifiers"),
combat_round_end_finalize: Event::new("combat_round_end_finalize"),
combat_round_end_tactics: Event::new("combat_round_end_tactics"),
combat_retreat: Event::new("combat_retreat"),
combat_end: Event::new("combat_end"),

View file

@ -14,6 +14,8 @@ pub struct ReplayGameData {
seed: String,
#[serde(default)]
asynchronous_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
finalized_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "crate::map::HomeLayout::is_legacy")]
home_layout: crate::map::HomeLayout,
log: Vec<ActionLogAge>,
@ -117,6 +119,10 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
data.asynchronous_combat_from
.unwrap_or(actions.len().saturating_add(1)),
);
game.finalized_combat_from = Some(
data.finalized_combat_from
.unwrap_or(actions.len().saturating_add(1)),
);
if data.options.civilization == CivSetupOption::DraftThree {
// Draft locks are private and absent from the action log; setup turns
// record their final choices. Re-deal before locking to preserve the RNG.
@ -168,6 +174,9 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
game.asynchronous_combat_from = game
.asynchronous_combat_from
.map(|from| from.min(to.saturating_add(1)));
game.finalized_combat_from = game
.finalized_combat_from
.map(|from| from.min(to.saturating_add(1)));
for player in data.players {
game.players[player.id].settings = player.settings;
}

View file

@ -5,7 +5,7 @@ use crate::movement::execute_movement_action;
use json_patch::{PatchOperation, patch};
use serde_json::Value;
const IGNORE_PATHS: [&str; 8] = [
const IGNORE_PATHS: [&str; 9] = [
"/calendar_knowledge",
"/log/",
"/log_index",
@ -17,6 +17,7 @@ const IGNORE_PATHS: [&str; 8] = [
// Once a new branch replaces old actions, undo must not restore their switch
// point and accidentally make redo execute a newly recorded battle as legacy.
"/asynchronous_combat_from",
"/finalized_combat_from",
];
pub(crate) fn clean_patch(mut patch: Vec<PatchOperation>) -> Vec<PatchOperation> {

View file

@ -0,0 +1,231 @@
//! Synthetic fixed-die regressions: no production save data.
use serde_json::{Value, json};
use server::{
board_history,
cache::Cache,
game::{Game, GameContext},
game_data::GameData,
};
fn load(v: Value) -> Game {
let d: GameData = serde_json::from_value(v).unwrap();
let cache = Cache::new(&d.options);
Game::from_data(d, cache, GameContext::Play)
}
fn data(g: &Game) -> Value {
serde_json::to_value(g.cloned_data()).unwrap()
}
fn play(g: Game, p: usize, a: Value) -> Game {
board_history::execute(g, serde_json::from_value(a).unwrap(), p).unwrap()
}
fn response(g: Game, r: Value) -> Game {
let p = g.active_player();
play(load(data(&g)), p, json!({"Response":r}))
}
fn end(g: &Game) -> Value {
data(g)["events"].as_array().unwrap().last().unwrap()["event_type"]["CombatRoundEnd"].clone()
}
fn request(g: &Game) -> Value {
serde_json::to_value(&g.current_event_handler().unwrap().request).unwrap()
}
fn last_report(g: &Game, player: usize) -> Value {
fn visit(v: &Value, player: usize, result: &mut Value) {
match v {
Value::Array(values) => {
for v in values {
visit(v, player, result);
}
}
Value::Object(fields) => {
if v["player"] == player && fields.contains_key("CombatHitReport") {
*result = v["CombatHitReport"].clone();
}
for v in fields.values() {
visit(v, player, result);
}
}
_ => (),
}
}
let mut result = Value::Null;
visit(&data(g)["log"], player, &mut result);
result
}
fn setup(legacy: bool) -> Game {
let mut v: Value =
serde_json::from_str(include_str!("test_games/combat/retreat.json")).unwrap();
v["players"][0]["civilization"] = json!("India");
v["players"][1]["civilization"] = json!("Huns");
for p in 0..2 {
v["players"][p]["advances"] = json!(["Farming", "Mining", "Tactics"]);
v["players"][p]["units"] = json!([
{"id":0,"position":if p==0 {"C2"} else {"C1"},"unit_type":if p==0 {json!("Infantry")} else {json!({"Leader":"Attila"})}},
{"id":1,"position":if p==0 {"C2"} else {"C1"},"unit_type":if p==0 {"Infantry"} else {"Cavalry"}}
]);
v["players"][p]["next_unit_id"] = json!(2);
}
v["players"][1]["advances"]
.as_array_mut()
.unwrap()
.push(json!("SteelWeapons"));
v["players"][0]["action_cards"] = json!([31]); // Flanking
v["players"][1]["action_cards"] = json!([9]); // High Ground
v["dice_roll_outcomes"] = json!([10, 2, 9, 3, 9]); // 5 Inf, 2 Elephant, 5 Inf; 2 Cavalry, 6 Inf
if legacy {
v["finalized_combat_from"] = json!(10000);
}
load(v)
}
fn horse_master(legacy: bool) -> Game {
let g = play(
setup(legacy),
0,
json!({"Movement":{"Move":{"units":[0,1],"destination":"C1","payment":{}}}}),
);
let g = response(g, json!({"SelectHandCards":[{"ActionCard":31}]}));
let g = response(g, json!({"Payment":[{"ore":1}]}));
let g = response(g, json!({"SelectHandCards":[{"ActionCard":9}]}));
assert!(
request(&g)["BoolRequest"]
.as_str()
.unwrap()
.starts_with("Horse Master")
);
assert_eq!(end(&g)["attacker"]["combat_value"], 12);
assert_eq!(end(&g)["defender"]["combat_value"], 12);
g
}
#[test]
fn defender_conversion_precedes_both_casualties_and_survivors_continue() {
let g = horse_master(false);
assert_eq!(
g.player(0).units.len(),
2,
"neither attacker may die before defender's conversion"
);
assert_eq!(g.player(1).units.len(), 2);
assert_eq!(end(&g)["phase"], "RoundEndModifiers");
let g = response(g, json!({"Bool":true}));
assert_eq!(end(&g)["defender"]["combat_value"], 8);
assert_eq!(end(&g)["attacker"]["opponent_hit_cancels"], 1);
assert_eq!(g.player(0).units.len(), 1);
assert_eq!(request(&g)["SelectUnits"]["needed"]["start"], 1);
let g = response(g, json!({"SelectUnits":[1]}));
assert_eq!(g.player(1).units.len(), 1);
assert_eq!(end(&g)["phase"], "Retreat");
let mut v = data(&g);
v["dice_roll_outcomes"] = json!([3, 3, 3, 3]);
let g = response(load(v), json!({"Bool":false}));
assert_eq!(end(&g)["combat"]["stats"]["round"], 2);
assert_eq!(end(&g)["phase"], "Retreat");
assert_eq!(g.player(0).units.len(), 1);
assert_eq!(g.player(1).units.len(), 1);
}
#[test]
fn decline_keeps_original_values_and_draw() {
let g = response(horse_master(false), json!({"Bool":false}));
assert!(g.player(0).units.is_empty());
assert!(g.player(1).units.is_empty());
}
#[test]
fn legacy_pending_conversion_is_not_repaired_or_reinterpreted() {
let g = horse_master(true);
// Baseline bug reproduced using the preserved old execution mode. Changing
// this pending battle to the new phase cannot resurrect already killed units.
assert!(g.player(0).units.is_empty());
assert_eq!(end(&g)["phase"], json!(null)); // Default is omitted
let g = load(data(&g));
assert!(g.player(0).units.is_empty());
let accepted = response(load(data(&g)), json!({"Bool":true}));
assert!(
accepted.player(0).units.is_empty(),
"legacy acceptance must not silently resurrect attackers"
);
let g = response(g, json!({"Bool":false}));
assert!(g.player(0).units.is_empty());
assert!(g.player(1).units.is_empty());
}
#[test]
fn attacker_conversion_and_defender_paid_cancel_both_resolve_before_any_losses() {
let mut v = data(&setup(false));
v["players"][0]["civilization"] = json!("Huns");
v["players"][1]["civilization"] = json!("China");
v["players"][0]["units"][0]["unit_type"] = json!({"Leader":"Attila"});
v["players"][0]["units"][1]["unit_type"] = json!("Cavalry");
v["players"][1]["units"][0]["unit_type"] = json!({"Leader":"Qin"});
v["players"][1]["units"][1]["unit_type"] = json!("Infantry");
v["players"][0]["advances"] = json!(["Tactics", "SteelWeapons"]);
v["players"][1]["advances"] = json!(["Tactics"]);
for p in 0..2 {
v["players"][p]["action_cards"] = json!([]);
}
v["dice_roll_outcomes"] = json!([10, 9, 10, 2]);
let g = play(
load(v),
0,
json!({"Movement":{"Move":{"units":[0,1],"destination":"C1","payment":{}}}}),
);
let g = response(g, json!({"Payment":[{"ore":1}]}));
assert!(
request(&g)["BoolRequest"]
.as_str()
.unwrap()
.starts_with("Horse Master")
);
assert_eq!(end(&g)["attacker"]["combat_value"], 12);
assert_eq!(end(&g)["defender"]["combat_value"], 12);
let g = response(g, json!({"Bool":true}));
assert_eq!(g.active_player(), 1);
assert!(request(&g).get("Payment").is_some());
assert_eq!(g.player(0).units.len(), 2);
assert_eq!(g.player(1).units.len(), 2);
let g = response(g, json!({"Payment":[{"culture_tokens":2}]}));
assert_eq!(end(&g)["attacker"]["combat_value"], 8);
assert_eq!(end(&g)["attacker"]["opponent_hit_cancels"], 1);
assert_eq!(
last_report(&g, 0),
json!({"combat_value":8,"hit_cancels":1,"extra_hits":0,"casualties":0})
);
assert_eq!(
last_report(&g, 1),
json!({"combat_value":12,"hit_cancels":1,"extra_hits":0,"casualties":1})
);
assert_eq!(request(&g)["SelectUnits"]["needed"]["start"], 1);
let g = response(g, json!({"SelectUnits":[1]}));
assert_eq!(g.player(0).units.len(), 1);
assert_eq!(g.player(1).units.len(), 2);
assert_eq!(end(&g)["phase"], "Retreat");
}
#[test]
fn later_round_activated_cavalry_does_not_offer_conversion() {
let mut g = setup(false);
g.dice_roll_outcomes = vec![10, 2, 3, 3, 3];
let g = play(
g,
0,
json!({"Movement":{"Move":{"units":[0,1],"destination":"C1","payment":{}}}}),
);
let g = response(g, json!({"SelectHandCards":[{"ActionCard":31}]}));
let g = response(g, json!({"Payment":[{"ore":1}]}));
let g = response(g, json!({"SelectHandCards":[{"ActionCard":9}]}));
assert!(
request(&g)["BoolRequest"]
.as_str()
.unwrap()
.starts_with("Horse Master")
);
let g = response(g, json!({"Bool":true}));
assert_eq!(end(&g)["phase"], "Retreat");
assert_eq!(g.player(0).units.len(), 1);
assert_eq!(g.player(1).units.len(), 2); // Attila AND cavalry still present.
let mut v = data(&g);
v["dice_roll_outcomes"] = json!([10, 2, 3]);
let g = response(load(v), json!({"Bool":false}));
// Round two's activated cavalry kills the last attacker without another offer.
assert!(g.player(0).units.is_empty());
assert_eq!(g.player(1).units.len(), 2);
assert!(g.events.is_empty());
}

View file

@ -222,11 +222,14 @@ fn replay_format_boundary_is_explicit_and_absent_in_historical_records() {
let replayed =
server::replay::replay(serde_json::from_value(v.clone()).unwrap(), None).unwrap();
assert_eq!(replayed.asynchronous_combat_from, Some(0));
assert_eq!(replayed.finalized_combat_from, Some(0));
v.as_object_mut().unwrap().remove("finalized_combat_from");
v.as_object_mut()
.unwrap()
.remove("asynchronous_combat_from");
let legacy = server::replay::replay(serde_json::from_value(v).unwrap(), None).unwrap();
assert!(legacy.asynchronous_combat_from.unwrap() > server::game_api::log_length(&legacy));
assert!(legacy.finalized_combat_from.unwrap() > server::game_api::log_length(&legacy));
}
#[test]
@ -290,8 +293,11 @@ fn historical_combat_replay_branches_enable_new_battles() {
let round = &data(&open)["events"][0]["event_type"]["CombatRoundStart"];
assert_eq!(round["combat"]["asynchronous_preparation"], Value::Null);
assert_eq!(open.asynchronous_combat_from, Some(218));
assert_eq!(open.finalized_combat_from, Some(218));
assert_eq!(round["combat"]["finalized_round_end"], Value::Null);
let before = historical_replay(216);
assert_eq!(before.asynchronous_combat_from, Some(217));
assert_eq!(before.finalized_combat_from, Some(217));
let next = play(
before,
0,
@ -299,6 +305,7 @@ fn historical_combat_replay_branches_enable_new_battles() {
);
let round = &data(&next)["events"][0]["event_type"]["CombatRoundStart"];
assert_eq!(round["combat"]["asynchronous_preparation"], json!(true));
assert_eq!(round["combat"]["finalized_round_end"], json!(true));
// The newly recorded switch survives replay of the branched history.
let again = server::replay::replay(serde_json::from_value(data(&next)).unwrap(), None).unwrap();
assert_eq!(data(&again)["events"], data(&next)["events"]);
@ -332,6 +339,10 @@ fn historical_combat_replay_branches_enable_new_battles() {
data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"],
json!(true)
);
assert_eq!(
data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["finalized_round_end"],
json!(true)
);
// A branch earlier than the original history's switch cannot inherit it.
let earlier = historical_replay(167);
@ -344,33 +355,44 @@ fn historical_combat_replay_branches_enable_new_battles() {
data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"],
json!(true)
);
assert_eq!(
data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["finalized_round_end"],
json!(true)
);
}
#[test]
fn undo_redo_preserves_history_boundary_but_replacing_future_clamps_it() {
let mut g = server::game_api::init(2, "combat-undo-boundary".into(), Default::default());
g.asynchronous_combat_from = Some(100);
g.finalized_combat_from = Some(100);
let player = g.active_player();
let action = json!({"Playing":{"Advance":{"advance":"Storage","payment":{"food":2}}}});
let paid = play(g, player, action.clone());
let undone = play(paid, player, json!("Undo"));
assert_eq!(undone.asynchronous_combat_from, Some(100));
assert_eq!(undone.finalized_combat_from, Some(100));
let redone = play(undone, player, json!("Redo"));
assert_eq!(redone.asynchronous_combat_from, Some(100));
assert_eq!(redone.finalized_combat_from, Some(100));
let undone = play(redone, player, json!("Undo"));
let next = server::game_api::log_length(&undone) + 1;
let branched = play(undone, player, action);
assert_eq!(branched.asynchronous_combat_from, Some(next));
assert_eq!(branched.finalized_combat_from, Some(next));
let undone = play(branched, player, json!("Undo"));
assert_eq!(undone.asynchronous_combat_from, Some(next));
assert_eq!(undone.finalized_combat_from, Some(next));
let redone = play(undone, player, json!("Redo"));
assert_eq!(redone.asynchronous_combat_from, Some(next));
assert_eq!(redone.finalized_combat_from, Some(next));
}
#[test]
fn undo_redo_of_a_branched_battle_keeps_new_preparation() {
let mut v = fixture("tactics_cards/peltasts");
v["asynchronous_combat_from"] = json!(100);
v["finalized_combat_from"] = json!(100);
for p in [0, 1] {
v["players"][p]["advances"]
.as_array_mut()
@ -391,6 +413,10 @@ fn undo_redo_of_a_branched_battle_keeps_new_preparation() {
expected["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"],
json!(true)
);
assert_eq!(
expected["events"][0]["event_type"]["CombatRoundStart"]["combat"]["finalized_round_end"],
json!(true)
);
let undone = play(branch, 0, json!("Undo"));
let redone = play(undone, 0, json!("Redo"));
assert_eq!(data(&redone)["events"], expected["events"]);
@ -398,4 +424,8 @@ fn undo_redo_of_a_branched_battle_keeps_new_preparation() {
data(&redone)["asynchronous_combat_from"],
expected["asynchronous_combat_from"]
);
assert_eq!(
data(&redone)["finalized_combat_from"],
expected["finalized_combat_from"]
);
}

View file

@ -146,6 +146,12 @@ fn clean_json(expected: &str) -> String {
.unwrap()
.remove("asynchronous_combat_from");
}
if value["finalized_combat_from"] == serde_json::json!(usize::MAX) {
value
.as_object_mut()
.unwrap()
.remove("finalized_combat_from");
}
// Only public action-log items qualify, never arbitrary arrays or game state.
if let Some(ages) = value
.get_mut("log")
@ -472,6 +478,9 @@ pub fn load_game(path: &GamePath) -> Game {
let mut game = Game::from_data(game_data, cache, GameContext::Play);
// These golden histories record the legacy battle response order. Exercise
// that compatibility path; new sequencing has dedicated preparation tests.
if game.finalized_combat_from.is_none() {
game.finalized_combat_from = Some(usize::MAX);
}
if game.asynchronous_combat_from.is_none() {
game.asynchronous_combat_from = Some(usize::MAX);
}

File diff suppressed because it is too large Load diff

View file

@ -4,6 +4,7 @@
},
"version": 2,
"asynchronous_combat_from": 0,
"finalized_combat_from": 0,
"home_layout": "ClockwiseV1",
"state": "ChooseCivilization",
"players": [

View file

@ -1763,3 +1763,16 @@ bytes, run boarding on those actual artifacts, and preserve catalog revision 8 /
preferences/Standard options. Only the frozen artwork manifest's lockfile integrity
pin changes for the viewer version bump; no artwork or catalog is republished.
No production moves, migrations, history edits or rewinds are involved.
# Viewer 0.1.235 / engine 0.4.166 — finalized combat rounds
Both sides now finish Horse Master and other hit-changing round-end abilities
before final hit reports, casualty choices and casualty-dependent rewards.
Attila's activated Cavalry conversion retains the original dice and displays
adjusted CV without a fake reroll. Existing open battles and historical outcomes
keep legacy timing; no losses are repaired or saves backfilled. Replay branches
adopt finalized timing only for new battles. See `docs/combat-round-finalization.md`
for the listener audit and regression coverage. Publish matching viewer and engine
only after the source push and green CI. Achievement catalog 8 / 46 entries,
nonfaction art revision 4 and the 60 registered assets are unchanged.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.234",
"version": "0.1.235",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.234",
"version": "0.1.235",
"dependencies": {
"@boardgamers/protocol": "0.11.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.234",
"version": "0.1.235",
"private": true,
"type": "module",
"scripts": {

View file

@ -13,7 +13,7 @@
"web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0",
"web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b",
"server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332",
"web-client/package-lock.json": "e13672f16b16cb39d284f0ba017084769a75fbb4e2ddcc3bc37aefc0e98811d8",
"web-client/package-lock.json": "3a429d2fbd77daee7ce454ffc9d57f969cb21177a7c48404f6dd252ceb7e732e",
"web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be",
"web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a",
"web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db"

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-server",
"version": "0.4.165",
"version": "0.4.166",
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
"license": "MIT",
"type": "commonjs",

View file

@ -0,0 +1,37 @@
// Public synthetic board; all combat actions use the real engine.
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
export const engine = createRequire(import.meta.url)(process.env.CLASH_WASM ?? '../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'horse-master', {})).players.slice(2);
export const items = (g) =>
g.log.flatMap((a) =>
a.rounds.flatMap((r) => r.turns.flatMap((t) => (t.actions ?? []).flatMap((a) => a.items ?? []))),
);
export function respond(raw, response) {
return engine.tryMove(raw, JSON.stringify({ Response: response }), engine.currentPlayer(raw));
}
export function battle(leader = 'Attila', cavalry = true) {
const g = JSON.parse(
readFileSync(new URL('../../server/tests/test_games/combat/retreat.json', import.meta.url), 'utf8'),
);
g.players.push(...structuredClone(npcs));
for (let p = 0; p < 2; p++) {
g.players[p].civilization = p === 0 ? 'India' : 'Huns';
g.players[p].advances = ['Farming', 'Mining', 'Tactics', ...(p === 1 ? ['SteelWeapons'] : [])];
g.players[p].units = [
{ id: 0, position: p === 0 ? 'C2' : 'C1', unit_type: p === 0 ? 'Infantry' : { Leader: leader } },
{ id: 1, position: p === 0 ? 'C2' : 'C1', unit_type: p === 0 || !cavalry ? 'Infantry' : 'Cavalry' },
];
g.players[p].next_unit_id = 2;
g.players[p].action_cards = [p === 0 ? 31 : 9];
}
g.dice_roll_outcomes = [10, 2, 9, 3, 9];
let raw = engine.tryMove(
JSON.stringify(g),
JSON.stringify({ Movement: { Move: { units: [0, 1], destination: 'C1', payment: {} } } }),
0,
);
raw = respond(raw, { SelectHandCards: [{ ActionCard: 31 }] });
raw = respond(raw, { Payment: [{ ore: 1 }] });
return respond(raw, { SelectHandCards: [{ ActionCard: 9 }] });
}

View file

@ -0,0 +1,98 @@
// Production viewer/controller and actual WASM battle; only BGS transport is local.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { chromium } from 'playwright';
import { battle, engine, items } from './horse-master-fixture.mjs';
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const width of [1400, 390]) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
let raw = battle();
const originalRolls = items(JSON.parse(raw)).filter((i) => i.CombatRoll);
assert.deepEqual(
originalRolls.map((i) => i.CombatRoll.combat_value),
[12, 12],
);
const emit = () => page.evaluate((state) => host.emit('state', state), engine.stripSecret(raw, 1));
const sent = [];
await page.exposeFunction('applyMove', async (action) => {
sent.push(JSON.parse(action));
raw = engine.tryMove(raw, action, 1);
await emit();
});
await page.route('**/*', async (route) => {
const path = new URL(route.request().url()).pathname;
if (path === '/')
return route.fulfill({
contentType: 'text/html',
body: '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>',
});
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) return route.abort();
return route.fulfill({
contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(new URL('../dist' + path, import.meta.url)),
});
});
await page.goto('http://clash.test/');
await page.waitForFunction(() => typeof window.clash3d !== 'undefined');
await page.evaluate(() => {
window.host = clash3d.launch('#app');
host.on('move', (action) => window.applyMove(action));
host.emit('player', { index: 1 });
host.emit('preferences', { sound: false, reducedMotion: false });
});
await emit();
await page
.getByText(/Horse Master/)
.first()
.waitFor();
await page.getByRole('button', { name: 'Cancel 1 hit', exact: true }).click();
await page.waitForTimeout(500);
assert.deepEqual(sent[0], { Response: { Bool: true } });
const state = JSON.parse(raw);
assert.deepEqual(
items(state).filter((i) => i.CombatRoll),
originalRolls,
'no new dice roll',
);
assert.deepEqual(
items(state)
.filter((i) => i.CombatHitReport)
.slice(-2)
.map((i) => i.CombatHitReport),
[
{ combat_value: 12, hit_cancels: 1, extra_hits: 0, casualties: 1 },
{ combat_value: 8, hit_cancels: 0, extra_hits: 0, casualties: 1 },
],
);
const sides = page.locator('.battle-side');
assert.deepEqual(await page.locator('.battle-hit-count > span').allTextContents(), [
'12 value',
'8 value',
]);
assert.match(await sides.nth(0).locator('.battle-hit-count strong').innerText(), /1 hit$/);
assert.equal(await sides.nth(1).locator('.battle-hit-count strong').innerText(), '1 hit');
assert.deepEqual(await sides.nth(0).locator('.battle-die b').allTextContents(), ['5', '2', '5']);
assert.deepEqual(await sides.nth(1).locator('.battle-die b').allTextContents(), ['2', '6']);
assert.equal(await page.locator('.battle-roll').count(), 0, 'conversion must not animate another roll');
await page.getByRole('button', { name: 'Cavalry', exact: true }).click();
await page.getByRole('button', { name: 'Confirm', exact: true }).click();
await page.waitForTimeout(300);
assert.equal(JSON.parse(raw).players[0].units.length, 1);
assert.equal(JSON.parse(raw).players[1].units.length, 1);
assert.equal(JSON.parse(raw).events.at(-1).handler.request.BoolRequest, 'Do you want to retreat?');
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert.deepEqual(errors, []);
await page.close();
console.log(
`${width}px: actual Horse Master accepted through production viewer; final CV 12/8, one casualty each, unchanged rolls.`,
);
}
} finally {
await browser.close();
}

View file

@ -0,0 +1,147 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { battleCues, battleCursor } from './battle-playback.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'horse-master', {})).players.slice(2);
const items = (g: any) =>
g.log.flatMap((a: any) =>
a.rounds.flatMap((r: any) =>
r.turns.flatMap((t: any) => (t.actions ?? []).flatMap((a: any) => a.items ?? [])),
),
);
function respond(raw: string, response: object) {
return engine.tryMove(raw, JSON.stringify({ Response: response }), engine.currentPlayer(raw));
}
function battle(leader = 'Attila', cavalry = true) {
const g = JSON.parse(
readFileSync(new URL('../../server/tests/test_games/combat/retreat.json', import.meta.url), 'utf8'),
);
g.players.push(...structuredClone(npcs));
for (let p = 0; p < 2; p++) {
g.players[p].civilization = p === 0 ? 'India' : 'Huns';
g.players[p].advances = ['Farming', 'Mining', 'Tactics', ...(p === 1 ? ['SteelWeapons'] : [])];
g.players[p].units = [
{ id: 0, position: p === 0 ? 'C2' : 'C1', unit_type: p === 0 ? 'Infantry' : { Leader: leader } },
{ id: 1, position: p === 0 ? 'C2' : 'C1', unit_type: p === 0 || !cavalry ? 'Infantry' : 'Cavalry' },
];
g.players[p].next_unit_id = 2;
g.players[p].action_cards = [p === 0 ? 31 : 9];
}
g.dice_roll_outcomes = [10, 2, 9, 3, 9];
let raw = engine.tryMove(
JSON.stringify(g),
JSON.stringify({ Movement: { Move: { units: [0, 1], destination: 'C1', payment: {} } } }),
0,
);
raw = respond(raw, { SelectHandCards: [{ ActionCard: 31 }] });
raw = respond(raw, { Payment: [{ ore: 1 }] });
return respond(raw, { SelectHandCards: [{ ActionCard: 9 }] });
}
for (const accept of [true, false])
test(`Horse Master defender fixed dice: accept=${accept}`, () => {
const beforeRaw = battle();
const before = JSON.parse(beforeRaw);
assert.match(before.events.at(-1).handler.request.BoolRequest, /Horse Master/);
assert.equal(before.players[0].units.length, 2);
assert.equal(before.players[1].units.length, 2);
const rolled = items(before).filter((i: any) => i.CombatRoll);
assert.deepEqual(
rolled.map((i: any) => i.CombatRoll.combat_value),
[12, 12],
);
assert.deepEqual(
rolled[0].CombatRoll.rolls.map((d: any) => [d.value, d.unit_type, d.bonus]),
[
[5, 'Infantry', false],
[2, 'Elephant', false],
[5, 'Infantry', false],
],
);
assert.deepEqual(
rolled[1].CombatRoll.rolls.map((d: any) => [d.value, d.unit_type, d.bonus]),
[
[2, 'Cavalry', true],
[6, 'Infantry', false],
],
);
let raw = respond(beforeRaw, { Bool: accept });
let after = JSON.parse(raw);
assert.deepEqual(
items(after).slice(0, items(before).length),
items(before),
'never rewrite original dice or reports',
);
const final = [0, 1].map(
(p) =>
items(after)
.filter((i: any) => i.player === p && i.CombatHitReport)
.at(-1).CombatHitReport,
);
// Both final reports are emitted before either side removes casualties.
assert.deepEqual(final, [
{ combat_value: 12, hit_cancels: accept ? 1 : 0, extra_hits: 0, casualties: accept ? 1 : 2 },
{ combat_value: accept ? 8 : 12, hit_cancels: 0, extra_hits: 0, casualties: accept ? 1 : 2 },
]);
const cue = battleCues(after, battleCursor(before)).at(-1)!;
assert.equal(cue.roll, false, 'conversion is not another dice animation');
assert.equal(cue.combat.defender.value, accept ? 8 : 12);
assert.equal(cue.combat.attacker.hits, accept ? 1 : 2);
assert.deepEqual(cue.combat.defender.dice, battleCues(before, 0).at(-1)!.combat.defender.dice);
if (accept) {
assert.equal(after.events.at(-1).handler.request.SelectUnits.needed.start, 1);
raw = respond(raw, { SelectUnits: [1] });
after = JSON.parse(raw);
assert.equal(after.players[0].units.length, 1);
assert.equal(after.players[1].units.length, 1);
after.dice_roll_outcomes = [3, 3, 3, 3];
after = JSON.parse(respond(JSON.stringify(after), { Bool: false }));
assert.equal(after.events.at(-1).event_type.CombatRoundEnd.combat.stats.round, 2);
assert.equal(after.events.at(-1).handler.request.BoolRequest, 'Do you want to retreat?');
assert.equal(after.players[0].units.length, 1);
assert.equal(after.players[1].units.length, 1);
} else {
assert.equal(after.players[0].units?.length ?? 0, 0);
assert.equal(after.players[1].units?.length ?? 0, 0);
}
});
for (const [leader, cavalry] of [
['Bleda', true],
['Attila', false],
] as const)
test(`Horse Master requires Attila and an activated cavalry: ${leader}/${cavalry}`, () => {
const g = JSON.parse(battle(leader, cavalry));
assert.ok(!g.events?.some((e: any) => e.handler?.request.BoolRequest?.startsWith('Horse Master')));
});
test('published engine 0.4.165 pending Horse Master preserves its original outcome', () => {
const frozen = JSON.parse(
readFileSync(
new URL('../../server/tests/fixtures/legacy_horse_master_165.json', import.meta.url),
'utf8',
),
);
assert.equal(frozen.engine, '0.4.165');
assert.equal(frozen.pending.players[0].units?.length ?? 0, 0);
const resumed = JSON.parse(respond(JSON.stringify(frozen.pending), { Bool: true }));
for (const key of ['players', 'events', 'state', 'rng', 'dice_roll_outcomes', 'log', 'log_index']) {
assert.deepEqual(resumed[key], frozen.accepted[key], `old pending battle preserves ${key}`);
}
});
test('published 0.4.165 legal history replays full and partial cursors with a new-battle boundary', () => {
const frozen = JSON.parse(
readFileSync(
new URL('../../server/tests/fixtures/legacy_horse_master_165.json', import.meta.url),
'utf8',
),
);
for (const { to, state } of frozen.cursors) {
const replay = JSON.parse(engine.replay(JSON.stringify(frozen.history), { to }));
for (const key of ['players', 'events', 'state', 'rng', 'log_index']) {
assert.deepEqual(replay[key], state[key], `old legal cursor ${to} preserves ${key}`);
}
assert.equal(replay.finalized_combat_from, to + 1);
}
});