Use committed asynchronous combat preparation and preserve replay branches
This commit is contained in:
parent
a6cd817a15
commit
40bda526f5
53 changed files with 4472 additions and 747 deletions
65
docs/asynchronous-combat-preparation.md
Normal file
65
docs/asynchronous-combat-preparation.md
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
# Asynchronous combat preparation — release preparation
|
||||
|
||||
Prepared for viewer **0.1.221** and engine **0.4.154**. This implements the requested
|
||||
asynchronous interpretation, **not a claim about an official ruling**. Local
|
||||
preparation is not publication: matching pushed CI and hosted verification remain
|
||||
mandatory before calling the release shipped.
|
||||
|
||||
For a new battle, the ordinary decision sequence is:
|
||||
|
||||
1. Attacker's battle-start abilities (including Steel Weapons and Siegecraft).
|
||||
2. Existing tactics-eligibility and Loyalty steps.
|
||||
3. Attacker's tactics card or pass.
|
||||
4. Defender's battle-start abilities, then defender's tactics card or pass.
|
||||
5. Reveal, card effects (including actual Martyr sacrifice choices), then rolls.
|
||||
|
||||
**Special-case exception:** tactics-eligibility effects and Loyalty still run
|
||||
before either ordinary tactics selection. In particular, Loyalty may let a third
|
||||
player supply a Barbarian defender's card first. Moving this after the attacker's
|
||||
choice would change card eligibility (including Scouts); this implementation preserves
|
||||
those rules instead of silently redefining them. Subsequent rounds retain their
|
||||
existing eligibility/Loyalty, attacker tactics, defender tactics, reveal sequence.
|
||||
Battle-start abilities run once, not each round.
|
||||
|
||||
These are normal committed responses, not editable private queues. The opponent
|
||||
can know whether a card was played, but its identity remains hidden until reveal.
|
||||
The existing masking of the matching discard-pile occurrence is retained.
|
||||
Other early choices still use QueueChoice. Obsolete `/tactics` plans are removed
|
||||
on load/prune and never automatically consumed.
|
||||
|
||||
## Saved state and history
|
||||
|
||||
`Combat.asynchronous_preparation` selects the new sequence for that battle.
|
||||
Absence means legacy; an already-open legacy battle finishes in the old order.
|
||||
`CombatRoundStart.preparation` persists the exact first-round continuation,
|
||||
including both strengths, across saves and ordinary response handling. Start
|
||||
ability listeners still receive their original `Combat` payload; their serializer
|
||||
wraps the resulting combat back into that continuation.
|
||||
|
||||
`asynchronous_combat_from` is a **format/history boundary**, not a release version.
|
||||
New games start at zero. A legacy live save records the current action index when
|
||||
its first new battle starts. Historical replay without a boundary uses the old
|
||||
sequence through the recorded history and enables the new sequence only beyond
|
||||
that history. With a boundary, replay uses the recorded switch point while
|
||||
reconstructing. Before returning a playable replay cursor, the boundary is clamped
|
||||
to its next action: discarded future history must not force new branch battles
|
||||
into legacy order. Redo preserves the recorded boundary; a fresh action replacing
|
||||
an undone future clamps it likewise. The boundary is excluded from gameplay undo
|
||||
patches: undoing a newly branched battle must not resurrect the discarded future's
|
||||
switch and make redo run it as legacy. Already-open battles retain their own mode.
|
||||
Historical
|
||||
golden fixtures explicitly select the legacy path; focused preparation tests
|
||||
exercise the new one. No old recorded responses are reordered.
|
||||
|
||||
## Local preview
|
||||
|
||||
The existing “Tactics · Steel Weapons” scenario starts at Rome's Steel Weapons
|
||||
payment. Confirming immediately opens Rome's normal Tactics panel; only after
|
||||
playing/passing does Greece become active. Restart scenario returns to Rome's
|
||||
payment. The map/layout code is unchanged.
|
||||
|
||||
The frozen synthetic 217-action fixture in `server/tests/fixtures/legacy_combat_history.json`
|
||||
was independently replayed by production engine 0.4.153. Its expected state is
|
||||
checked through actual `engine.replay`, not by merely applying responses to a
|
||||
mutated battle fixture. Native tests also cover full-save and partial-history
|
||||
branches, branch replay, and undo/redo switch handling.
|
||||
|
|
@ -49,6 +49,8 @@ pub enum CombatRetreatState {
|
|||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct Combat {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub asynchronous_preparation: bool,
|
||||
pub attackers: Vec<u32>,
|
||||
pub retreat: CombatRetreatState,
|
||||
#[serde(default)]
|
||||
|
|
@ -61,6 +63,7 @@ impl Combat {
|
|||
#[must_use]
|
||||
pub fn new(attackers: Vec<u32>, can_retreat: bool, stats: CombatStats) -> Self {
|
||||
Self {
|
||||
asynchronous_preparation: false,
|
||||
attackers,
|
||||
modifiers: vec![],
|
||||
retreat: if can_retreat {
|
||||
|
|
@ -219,7 +222,11 @@ pub fn initiate_combat(
|
|||
&attackers,
|
||||
None,
|
||||
);
|
||||
let combat = Combat::new(attackers, can_retreat, stats);
|
||||
let mut combat = Combat::new(attackers, can_retreat, stats);
|
||||
// Persist the history boundary, rather than reinterpret old logged responses.
|
||||
let index = crate::game_api::log_length(game);
|
||||
let from = *game.asynchronous_combat_from.get_or_insert(index);
|
||||
combat.asynchronous_preparation = index >= from;
|
||||
log_round(game, &combat);
|
||||
start_combat(game, combat);
|
||||
}
|
||||
|
|
@ -261,6 +268,10 @@ pub(crate) fn log_round(game: &mut Game, c: &Combat) {
|
|||
|
||||
pub(crate) fn start_combat(game: &mut Game, combat: Combat) {
|
||||
stop_current_move(game);
|
||||
if combat.asynchronous_preparation {
|
||||
combat_loop(game, CombatRoundStart::new(combat));
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(c) = game.trigger_persistent_event(
|
||||
&combat.players(),
|
||||
|
|
|
|||
|
|
@ -84,8 +84,20 @@ impl CombatEventPhase {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
|
||||
pub enum PreparationStep {
|
||||
AttackerAbilities,
|
||||
Eligibility,
|
||||
Loyalty,
|
||||
AttackerTactics,
|
||||
DefenderAbilities,
|
||||
DefenderTactics,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct CombatRoundStart {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub preparation: Option<PreparationStep>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub displaced_unit: Option<u32>,
|
||||
pub combat: Combat,
|
||||
|
|
@ -103,6 +115,8 @@ impl CombatRoundStart {
|
|||
#[must_use]
|
||||
pub fn new(combat: Combat) -> Self {
|
||||
Self {
|
||||
preparation: (combat.asynchronous_preparation && combat.first_round())
|
||||
.then_some(PreparationStep::AttackerAbilities),
|
||||
combat,
|
||||
displaced_unit: None,
|
||||
attacker_strength: CombatStrength::new(),
|
||||
|
|
@ -277,8 +291,11 @@ const ROUND_START_TYPES: &[CombatEventPhase; 5] = &[
|
|||
|
||||
pub(crate) fn combat_round_start(
|
||||
game: &mut Game,
|
||||
start: CombatRoundStart,
|
||||
mut start: CombatRoundStart,
|
||||
) -> Option<CombatRoundStart> {
|
||||
if start.preparation.is_some() {
|
||||
start = prepare_first_round(game, start)?;
|
||||
}
|
||||
event_with_tactics(
|
||||
game,
|
||||
start,
|
||||
|
|
@ -299,6 +316,84 @@ pub(crate) fn combat_round_start(
|
|||
)
|
||||
}
|
||||
|
||||
// Start listeners still receive Combat; the serialized continuation contains the
|
||||
// entire round, including the attacker's hidden selection while the defender pays.
|
||||
fn prepare_first_round(game: &mut Game, mut round: CombatRoundStart) -> Option<CombatRoundStart> {
|
||||
use PreparationStep::*;
|
||||
while let Some(step) = round.preparation.clone() {
|
||||
match step {
|
||||
AttackerAbilities | DefenderAbilities => {
|
||||
let player = if step == AttackerAbilities {
|
||||
round.combat.attacker()
|
||||
} else {
|
||||
round.combat.defender()
|
||||
};
|
||||
let saved = round.clone();
|
||||
round.combat = game.trigger_persistent_event(
|
||||
&[player],
|
||||
|e| &mut e.combat_start,
|
||||
round.combat.clone(),
|
||||
move |combat| {
|
||||
let mut continuation = saved.clone();
|
||||
continuation.combat = combat;
|
||||
PersistentEventType::CombatRoundStart(continuation)
|
||||
},
|
||||
)?;
|
||||
}
|
||||
Eligibility => {
|
||||
round = game.trigger_persistent_event(
|
||||
&round.combat.players(),
|
||||
|e| &mut e.combat_round_start_allow_tactics,
|
||||
round,
|
||||
PersistentEventType::CombatRoundStart,
|
||||
)?;
|
||||
}
|
||||
Loyalty => {
|
||||
if let Some(player) =
|
||||
crate::content::civilizations::celts::loyalty_controller(game, &round.combat)
|
||||
{
|
||||
round = game.trigger_persistent_event(
|
||||
&[player],
|
||||
|e| &mut e.loyalty,
|
||||
round,
|
||||
PersistentEventType::CombatRoundStart,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
AttackerTactics | DefenderTactics => {
|
||||
let player = if step == AttackerTactics {
|
||||
round.combat.attacker()
|
||||
} else {
|
||||
round.combat.defender()
|
||||
};
|
||||
round = game.trigger_persistent_event(
|
||||
&[player],
|
||||
|e| &mut e.combat_round_start,
|
||||
round,
|
||||
PersistentEventType::CombatRoundStart,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
round.preparation = match step {
|
||||
AttackerAbilities => Some(Eligibility),
|
||||
Eligibility => Some(Loyalty),
|
||||
Loyalty => Some(AttackerTactics),
|
||||
AttackerTactics => Some(DefenderAbilities),
|
||||
DefenderAbilities => Some(DefenderTactics),
|
||||
DefenderTactics => None,
|
||||
};
|
||||
round.phase = match round.preparation {
|
||||
Some(AttackerAbilities | Eligibility) => CombatEventPhase::AllowTacticsCard,
|
||||
Some(Loyalty) => CombatEventPhase::Loyalty,
|
||||
Some(AttackerTactics | DefenderAbilities | DefenderTactics) => {
|
||||
CombatEventPhase::Default
|
||||
}
|
||||
None => CombatEventPhase::RevealTacticsCard,
|
||||
};
|
||||
}
|
||||
Some(round)
|
||||
}
|
||||
|
||||
const ROUND_END_TYPES: &[CombatEventPhase; 3] = &[
|
||||
CombatEventPhase::TacticsCard,
|
||||
CombatEventPhase::Default,
|
||||
|
|
|
|||
|
|
@ -31,99 +31,6 @@ pub struct Offer {
|
|||
pub selected: Option<EventResponse>,
|
||||
}
|
||||
|
||||
// A plan belongs to this battle round, not to a transient event phase.
|
||||
fn tactics_key(game: &Game, combat: &crate::combat::Combat) -> String {
|
||||
format!(
|
||||
"{}:{}:{}:{}:{}:{}:{}/tactics",
|
||||
game.age,
|
||||
game.round,
|
||||
game.current_player_index,
|
||||
game.actions_left,
|
||||
combat.attacker(),
|
||||
combat.defender_position(),
|
||||
combat.stats.round
|
||||
)
|
||||
}
|
||||
|
||||
fn tactics_offer(game: &Game, player: usize) -> Option<Offer> {
|
||||
use crate::combat_listeners::{CombatEventPhase, CombatRoundStart};
|
||||
let event = game.events.iter().rev().find(|e| {
|
||||
matches!(
|
||||
e.event_type,
|
||||
PersistentEventType::CombatStart(_) | PersistentEventType::CombatRoundStart(_)
|
||||
)
|
||||
})?;
|
||||
let round = match &event.event_type {
|
||||
PersistentEventType::CombatStart(c) => CombatRoundStart::new(c.clone()),
|
||||
PersistentEventType::CombatRoundStart(r)
|
||||
if matches!(
|
||||
r.phase,
|
||||
CombatEventPhase::AllowTacticsCard
|
||||
| CombatEventPhase::Loyalty
|
||||
| CombatEventPhase::Default
|
||||
) =>
|
||||
{
|
||||
if r.phase == CombatEventPhase::Default
|
||||
&& (event.players_used.contains(&player) || event.player.index == player)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
r.clone()
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let c = &round.combat;
|
||||
if !c.players().contains(&player)
|
||||
|| !game
|
||||
.player(player)
|
||||
.can_use_advance(crate::advance::Advance::Tactics)
|
||||
|| crate::combat::get_combat_strength(player, &round).deny_tactics_card
|
||||
|| (player == c.defender()
|
||||
&& c.first_round()
|
||||
&& c.modifiers
|
||||
.contains(&crate::combat::CombatModifier::TrojanHorse))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut options = vec![option("No tactics", EventResponse::SelectHandCards(vec![]))];
|
||||
for id in game
|
||||
.player(player)
|
||||
.action_cards
|
||||
.iter()
|
||||
.filter(|id| **id != 0)
|
||||
{
|
||||
let card = game.cache.get_action_card(*id);
|
||||
let Some(tactics) = &card.tactics_card else {
|
||||
continue;
|
||||
};
|
||||
// Scout's enemy-card requirement is deliberately provisional; never
|
||||
// inspect a hidden enemy commitment to build an early offer.
|
||||
if tactics.name == "Scout"
|
||||
|| crate::tactics_card::can_play_tactics_card(game, player, card, &round)
|
||||
{
|
||||
options.push(OptionChoice {
|
||||
label: tactics.name.clone(),
|
||||
description: tactics.description.clone(),
|
||||
response: EventResponse::SelectHandCards(vec![HandCard::ActionCard(*id)]),
|
||||
});
|
||||
}
|
||||
}
|
||||
if options.len() == 1 {
|
||||
return None;
|
||||
}
|
||||
let key = tactics_key(game, c);
|
||||
Some(Offer {
|
||||
selected: game
|
||||
.early_choices
|
||||
.iter()
|
||||
.find(|s| s.player == player && s.key == key)
|
||||
.map(|s| s.response.clone()),
|
||||
key,
|
||||
title: "Tactics".into(),
|
||||
options,
|
||||
})
|
||||
}
|
||||
|
||||
fn scope(game: &Game, index: usize) -> Option<String> {
|
||||
let name = match &game.events.get(index)?.event_type {
|
||||
PersistentEventType::StatusPhase(phase) => format!("status:{phase:?}"),
|
||||
|
|
@ -191,28 +98,8 @@ fn objective_offers(game: &Game, player: usize) -> Vec<Offer> {
|
|||
}
|
||||
|
||||
pub fn prune_objectives(game: &mut Game) {
|
||||
// Navigation and interrupted/skipped rounds must not leave a plan that can
|
||||
// attach to a later battle at the same location.
|
||||
let combat_keys: Vec<_> = game
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match &event.event_type {
|
||||
PersistentEventType::CombatStart(c) => Some(tactics_key(game, c)),
|
||||
PersistentEventType::CombatRoundStart(r)
|
||||
if matches!(
|
||||
r.phase,
|
||||
crate::combat_listeners::CombatEventPhase::AllowTacticsCard
|
||||
| crate::combat_listeners::CombatEventPhase::Loyalty
|
||||
| crate::combat_listeners::CombatEventPhase::Default
|
||||
) =>
|
||||
{
|
||||
Some(tactics_key(game, &r.combat))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
game.early_choices
|
||||
.retain(|c| !c.key.ends_with("/tactics") || combat_keys.contains(&c.key));
|
||||
// Obsolete combat plans must never consume an ordinary response.
|
||||
game.early_choices.retain(|c| !c.key.ends_with("/tactics"));
|
||||
let invalid: Vec<_> = game
|
||||
.early_choices
|
||||
.iter()
|
||||
|
|
@ -309,9 +196,6 @@ pub fn offers(game: &Game, player: usize) -> Vec<Offer> {
|
|||
return vec![];
|
||||
}
|
||||
let mut result = current_offers(game, player);
|
||||
if let Some(offer) = tactics_offer(game, player) {
|
||||
result.push(offer);
|
||||
}
|
||||
if let Some(offer) = advance_offer(game, player) {
|
||||
result.push(offer);
|
||||
}
|
||||
|
|
@ -469,9 +353,7 @@ fn current_offers(game: &Game, player: usize) -> Vec<Offer> {
|
|||
}
|
||||
|
||||
pub fn can_save(game: &Game, player: usize, key: &str, response: Option<&EventResponse>) -> bool {
|
||||
(player != game.active_player()
|
||||
|| key.ends_with("/tactics")
|
||||
|| (game.events.is_empty() && key.contains(":objective:")))
|
||||
(player != game.active_player() || (game.events.is_empty() && key.contains(":objective:")))
|
||||
&& offers(game, player).iter().any(|offer| {
|
||||
offer.key == key
|
||||
&& response.is_none_or(|r| offer.options.iter().any(|o| &o.response == r))
|
||||
|
|
@ -506,14 +388,6 @@ pub fn save(
|
|||
}
|
||||
|
||||
pub fn expire_current_event(game: &mut Game) {
|
||||
if let Some(PersistentEventType::CombatRoundStart(r)) =
|
||||
game.events.last().map(|e| &e.event_type)
|
||||
{
|
||||
if r.phase == crate::combat_listeners::CombatEventPhase::Default {
|
||||
let key = tactics_key(game, &r.combat);
|
||||
game.early_choices.retain(|c| c.key != key);
|
||||
}
|
||||
}
|
||||
if game.events.last().is_some_and(|e| {
|
||||
matches!(
|
||||
e.event_type,
|
||||
|
|
@ -552,31 +426,6 @@ pub fn take_ready(game: &mut Game) -> Option<EventResponse> {
|
|||
let player = game.active_player();
|
||||
let event = game.events.last()?;
|
||||
let handler = event.player.handler.as_ref()?;
|
||||
if let PersistentEventType::CombatRoundStart(r) = &event.event_type {
|
||||
if r.phase != crate::combat_listeners::CombatEventPhase::Default
|
||||
|| handler.origin
|
||||
!= crate::events::EventOrigin::Advance(crate::advance::Advance::Tactics)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let key = tactics_key(game, &r.combat);
|
||||
let at = game
|
||||
.early_choices
|
||||
.iter()
|
||||
.position(|c| c.player == player && c.key == key)?;
|
||||
let valid = match (&handler.request, &game.early_choices[at].response) {
|
||||
(
|
||||
PersistentEventRequest::SelectHandCards(request),
|
||||
EventResponse::SelectHandCards(cards),
|
||||
) => {
|
||||
request.needed.contains(&(cards.len() as u8))
|
||||
&& cards.iter().all(|c| request.choices.contains(c))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let choice = game.early_choices.remove(at);
|
||||
return valid.then_some(choice.response);
|
||||
}
|
||||
let (index, suffix) = match &event.event_type {
|
||||
PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)) => {
|
||||
(game.events.len() - 1, "first".into())
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ pub struct Game {
|
|||
pub cache: Cache,
|
||||
pub context: GameContext, // transient
|
||||
pub options: GameOptions,
|
||||
pub asynchronous_combat_from: Option<usize>,
|
||||
pub version: u16, // JSON schema version
|
||||
pub state: GameState,
|
||||
pub events: Vec<PersistentEventState>,
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ pub struct GameData {
|
|||
#[serde(default)]
|
||||
#[serde(skip_serializing_if = "u16::is_zero")]
|
||||
version: u16,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
asynchronous_combat_from: Option<usize>,
|
||||
#[serde(default)]
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
seed: String,
|
||||
|
|
@ -134,7 +136,11 @@ pub struct GameData {
|
|||
pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
|
||||
let mut game = Game {
|
||||
action_plan: data.action_plan,
|
||||
early_choices: data.early_choices,
|
||||
early_choices: data
|
||||
.early_choices
|
||||
.into_iter()
|
||||
.filter(|c| !c.key.ends_with("/tactics"))
|
||||
.collect(),
|
||||
early_choice_update: data.early_choice_update,
|
||||
uncommitted_calendar: data.uncommitted_calendar,
|
||||
calendar_knowledge: data.calendar_knowledge,
|
||||
|
|
@ -143,6 +149,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
|
|||
cache,
|
||||
options: data.options,
|
||||
version: data.version,
|
||||
asynchronous_combat_from: data.asynchronous_combat_from,
|
||||
state: data.state,
|
||||
players: Vec::new(),
|
||||
map: Map::from_data(data.map),
|
||||
|
|
@ -202,6 +209,7 @@ pub fn data(game: Game) -> GameData {
|
|||
GameData {
|
||||
options: game.options,
|
||||
version: game.version,
|
||||
asynchronous_combat_from: game.asynchronous_combat_from,
|
||||
state: game.state,
|
||||
events: game.events,
|
||||
action_plan: game.action_plan,
|
||||
|
|
@ -247,6 +255,7 @@ pub fn cloned_data(game: &Game) -> GameData {
|
|||
GameData {
|
||||
options: game.options.clone(),
|
||||
version: game.version,
|
||||
asynchronous_combat_from: game.asynchronous_combat_from,
|
||||
state: game.state.clone(),
|
||||
events: game.events.clone(),
|
||||
action_plan: game.action_plan.clone(),
|
||||
|
|
|
|||
|
|
@ -194,6 +194,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
|
|||
secrets_stripped: false,
|
||||
seed: setup.seed.clone(),
|
||||
context: GameContext::Play,
|
||||
asynchronous_combat_from: Some(0),
|
||||
version: JSON_SCHEMA_VERSION,
|
||||
options: GameOptions {
|
||||
legacy_undo: None,
|
||||
|
|
|
|||
|
|
@ -452,6 +452,12 @@ pub(crate) fn add_log_action(game: &mut Game, item: Action) {
|
|||
let player = game.active_player();
|
||||
let origin = action_origin(&item, game.player(player)).clone();
|
||||
let i = game.log_index;
|
||||
if current_turn_log(game).actions.len() > i {
|
||||
// A fresh action replaces the undone future. Redo bypasses this path and
|
||||
// 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));
|
||||
}
|
||||
let l = &mut current_turn_log_mut(game).actions;
|
||||
remove_redo_actions(l, i);
|
||||
l.push(ActionLogAction::new(item, player, origin, active_events));
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ pub struct ReplayGameData {
|
|||
#[serde(default)]
|
||||
options: GameOptions,
|
||||
seed: String,
|
||||
#[serde(default)]
|
||||
asynchronous_combat_from: Option<usize>,
|
||||
log: Vec<ActionLogAge>,
|
||||
log_index: usize,
|
||||
// Look-only information boundaries are intentionally absent from the log.
|
||||
|
|
@ -108,6 +110,10 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
|
|||
builder = builder.assigned_civilizations(civilizations);
|
||||
}
|
||||
let mut game = setup_game(&builder.build());
|
||||
game.asynchronous_combat_from = Some(
|
||||
data.asynchronous_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.
|
||||
|
|
@ -152,6 +158,13 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
|
|||
"Replay target {to} is not a complete action boundary"
|
||||
));
|
||||
}
|
||||
// The returned position is playable, not a promise to execute the discarded
|
||||
// future. Preserve the recorded switch while reconstructing, then enable new
|
||||
// battles at the first action beyond this cursor. An open battle keeps its
|
||||
// own persisted preparation mode, so legacy continuations remain legacy.
|
||||
game.asynchronous_combat_from = game
|
||||
.asynchronous_combat_from
|
||||
.map(|from| from.min(to.saturating_add(1)));
|
||||
for player in data.players {
|
||||
game.players[player.id].settings = player.settings;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use crate::movement::execute_movement_action;
|
|||
use json_patch::{PatchOperation, patch};
|
||||
use serde_json::Value;
|
||||
|
||||
const IGNORE_PATHS: [&str; 7] = [
|
||||
const IGNORE_PATHS: [&str; 8] = [
|
||||
"/calendar_knowledge",
|
||||
"/log/",
|
||||
"/log_index",
|
||||
|
|
@ -13,6 +13,10 @@ const IGNORE_PATHS: [&str; 7] = [
|
|||
"/early_choice_update",
|
||||
"/action_plan",
|
||||
"/time_increments",
|
||||
// A format boundary describes retained history, not reversible gameplay.
|
||||
// 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",
|
||||
];
|
||||
|
||||
pub(crate) fn clean_patch(mut patch: Vec<PatchOperation>) -> Vec<PatchOperation> {
|
||||
|
|
|
|||
|
|
@ -344,17 +344,7 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
|
|||
}).collect::<Vec<_>>();
|
||||
let early_offers: Vec<_> = crate::early_choices::offers(game, seat)
|
||||
.into_iter()
|
||||
// Combat queues use the same waiting-player surface as other early choices.
|
||||
// Never offer tactics before this player's combat-start choices (notably
|
||||
// Steel Weapons) have finished. Keep engine queue authorization separate.
|
||||
.filter(|_| seat != active || game.events.is_empty())
|
||||
.filter(|o| {
|
||||
!o.key.ends_with("/tactics")
|
||||
|| !game.events.iter().any(|event| {
|
||||
matches!(event.event_type, PersistentEventType::CombatStart(_))
|
||||
&& !event.players_used.contains(&seat)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let early_advance = early_offers.iter().find(|o| o.key.ends_with("/advance"));
|
||||
let early_advance_choices: Vec<_> = early_advance
|
||||
|
|
|
|||
|
|
@ -51,9 +51,18 @@ pub(super) fn describe(game: &Game) -> Value {
|
|||
activated.modifiers.push(modifier);
|
||||
let bonus =
|
||||
strength(game, &activated, player).extra_combat_value - s.extra_combat_value;
|
||||
let pending = game.events.iter().any(|event| {
|
||||
matches!(event.event_type, PersistentEventType::CombatStart(_))
|
||||
&& !event.players_used.contains(&player)
|
||||
let pending = game.events.iter().any(|event| match &event.event_type {
|
||||
PersistentEventType::CombatStart(_) => !event.players_used.contains(&player),
|
||||
PersistentEventType::CombatRoundStart(round) => {
|
||||
use crate::combat_listeners::PreparationStep;
|
||||
if player == c.attacker() {
|
||||
round.preparation == Some(PreparationStep::AttackerAbilities)
|
||||
} else {
|
||||
round.preparation.is_some()
|
||||
&& round.preparation != Some(PreparationStep::DefenderTactics)
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
inactive.push(if pending {
|
||||
format!("Steel Weapons pending: +{bonus} value if activated")
|
||||
|
|
|
|||
401
server/tests/combat_preparation_tests.rs
Normal file
401
server/tests/combat_preparation_tests.rs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
use serde_json::{Value, json};
|
||||
use server::{
|
||||
board_history,
|
||||
cache::Cache,
|
||||
early_choices,
|
||||
game::{Game, GameContext},
|
||||
game_data::GameData,
|
||||
};
|
||||
|
||||
fn load(value: Value) -> Game {
|
||||
let data: GameData = serde_json::from_value(value).unwrap();
|
||||
let cache = Cache::new(&data.options);
|
||||
Game::from_data(data, cache, GameContext::Play)
|
||||
}
|
||||
fn data(game: &Game) -> Value {
|
||||
serde_json::to_value(game.cloned_data()).unwrap()
|
||||
}
|
||||
fn play(game: Game, player: usize, action: Value) -> Game {
|
||||
board_history::execute(game, serde_json::from_value(action).unwrap(), player).unwrap()
|
||||
}
|
||||
fn battle() -> Game {
|
||||
let mut v: Value =
|
||||
serde_json::from_str(include_str!("test_games/tactics_cards/peltasts.json")).unwrap();
|
||||
for p in [0, 1] {
|
||||
v["players"][p]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!("SteelWeapons"));
|
||||
}
|
||||
v["players"][0]["action_cards"] = json!([3, 6, 11]);
|
||||
v["players"][1]["action_cards"] = json!([4, 7, 23]);
|
||||
play(
|
||||
load(v),
|
||||
0,
|
||||
json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}),
|
||||
)
|
||||
}
|
||||
fn steel(g: Game, p: usize) -> Game {
|
||||
play(g, p, json!({"Response":{"Payment":[{"ore":1}]}}))
|
||||
}
|
||||
fn tactics(g: Game, p: usize, card: Option<u8>) -> Game {
|
||||
let cards: Vec<_> = card
|
||||
.into_iter()
|
||||
.map(|id| json!({"ActionCard":id}))
|
||||
.collect();
|
||||
play(g, p, json!({"Response":{"SelectHandCards":cards}}))
|
||||
}
|
||||
fn request(g: &Game) -> Value {
|
||||
serde_json::to_value(&g.current_event_handler().unwrap().request).unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn attacker_finishes_before_defender_and_reload_keeps_hidden_card() {
|
||||
let g = battle();
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("Payment").is_some());
|
||||
assert!(
|
||||
early_choices::offers(&g, 0)
|
||||
.iter()
|
||||
.all(|o| !o.key.ends_with("/tactics"))
|
||||
);
|
||||
let g = steel(load(data(&g)), 0);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
let g = tactics(load(data(&g)), 0, Some(3));
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("Payment").is_some());
|
||||
assert!(!g.player(0).action_cards.contains(&3));
|
||||
let hidden = data(&server::game_api::strip_secret(g.clone(), Some(1)));
|
||||
assert_eq!(
|
||||
hidden["events"][0]["event_type"]["CombatRoundStart"]["attacker_strength"]["tactics_card"],
|
||||
json!(0)
|
||||
);
|
||||
assert!(
|
||||
!hidden["action_cards_discarded"]
|
||||
.as_array()
|
||||
.is_some_and(|cards| cards.contains(&json!(3)))
|
||||
);
|
||||
let g = steel(load(data(&g)), 1);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
let g = tactics(load(data(&g)), 1, Some(4));
|
||||
assert!(!g.player(1).action_cards.contains(&4));
|
||||
}
|
||||
#[test]
|
||||
fn skipping_is_an_ordinary_committed_response() {
|
||||
let g = tactics(steel(battle(), 0), 0, None);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("Payment").is_some());
|
||||
assert!(g.player(0).action_cards.contains(&3));
|
||||
let _ = tactics(steel(g, 1), 1, None);
|
||||
}
|
||||
#[test]
|
||||
fn obsolete_combat_plans_are_discarded_but_other_plans_survive_load() {
|
||||
let mut v = data(&battle());
|
||||
v["early_choices"] = json!([
|
||||
{"player":0,"key":"old/tactics","response":{"SelectHandCards":[]}},
|
||||
{"player":1,"key":"1:status/advance","response":{"SelectAdvance":"Fishing"}}
|
||||
]);
|
||||
let g = load(v);
|
||||
assert_eq!(g.early_choices.len(), 1);
|
||||
assert_eq!(g.early_choices[0].key, "1:status/advance");
|
||||
assert!(!early_choices::can_save(&g, 0, "old/tactics", None));
|
||||
}
|
||||
#[test]
|
||||
fn legacy_battle_continuation_keeps_both_payments_before_tactics() {
|
||||
let mut v = data(&battle());
|
||||
let round = v["events"][0]["event_type"]["CombatRoundStart"].clone();
|
||||
let mut combat = round["combat"].clone();
|
||||
combat
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("asynchronous_preparation");
|
||||
v["events"][0]["event_type"] = json!({"CombatStart":combat});
|
||||
let g = steel(load(v), 0);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("Payment").is_some());
|
||||
let g = steel(g, 1);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
}
|
||||
|
||||
fn fixture(name: &str) -> Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(format!("tests/test_games/{name}.json")).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
fn attack(v: Value) -> Game {
|
||||
play(
|
||||
load(v),
|
||||
0,
|
||||
json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}),
|
||||
)
|
||||
}
|
||||
#[test]
|
||||
fn no_steel_and_free_metallurgy_do_not_add_a_payment_step() {
|
||||
for metallurgy in [false, true] {
|
||||
let mut v = fixture("tactics_cards/peltasts");
|
||||
v["players"][1]["action_cards"] = json!([4]);
|
||||
if metallurgy {
|
||||
v["players"][0]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.extend([json!("SteelWeapons"), json!("Metallurgy")]);
|
||||
}
|
||||
let g = attack(v);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
if metallurgy {
|
||||
let round = &data(&g)["events"][0]["event_type"]["CombatRoundStart"];
|
||||
assert!(
|
||||
round["combat"]["modifiers"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("SteelWeaponsAttacker"))
|
||||
);
|
||||
}
|
||||
let g = tactics(g, 0, None);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn siegecraft_stays_before_attacker_card_and_defender_steel() {
|
||||
let mut v = fixture("tactics_cards/peltasts");
|
||||
v["players"][0]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.extend([json!("SteelWeapons"), json!("Siegecraft")]);
|
||||
v["players"][1]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!("SteelWeapons"));
|
||||
v["players"][1]["cities"][0]["city_pieces"] = json!({"fortress":1});
|
||||
let g = steel(attack(v), 0);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert_eq!(request(&g)["Payment"].as_array().unwrap().len(), 2);
|
||||
let g = play(
|
||||
load(data(&g)),
|
||||
0,
|
||||
json!({"Response":{"Payment":[{"wood":2},{"ore":2}]}}),
|
||||
);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
let g = tactics(g, 0, None);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert_eq!(request(&g)["Payment"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn naval_steel_is_not_offered_and_martyr_still_requires_sacrifice_after_both_cards() {
|
||||
let mut v = fixture("tactics_cards/martyr");
|
||||
for p in [0, 1] {
|
||||
v["players"][p]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!("SteelWeapons"));
|
||||
}
|
||||
let g = play(
|
||||
load(v),
|
||||
0,
|
||||
json!({"Movement":{"Move":{"units":[7,8],"destination":"D2","payment":{}}}}),
|
||||
);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
let g = tactics(g, 0, Some(6));
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
let g = tactics(g, 1, Some(24));
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("SelectUnits").is_some());
|
||||
let g = play(load(data(&g)), 0, json!({"Response":{"SelectUnits":[7]}}));
|
||||
assert!(request(&g).get("SelectUnits").is_some());
|
||||
let _ = play(g, 0, json!({"Response":{"SelectUnits":[2]}}));
|
||||
}
|
||||
#[test]
|
||||
fn replay_format_boundary_is_explicit_and_absent_in_historical_records() {
|
||||
let g = server::game_api::init(
|
||||
2,
|
||||
"combat-replay-format".into(),
|
||||
server::game::GameOptions::default(),
|
||||
);
|
||||
let player = g.active_player();
|
||||
let g = play(g, player, json!({"Playing":"EndTurn"}));
|
||||
let mut v = data(&g);
|
||||
let replayed =
|
||||
server::replay::replay(serde_json::from_value(v.clone()).unwrap(), None).unwrap();
|
||||
assert_eq!(replayed.asynchronous_combat_from, Some(0));
|
||||
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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_payment_undo_redo_is_deterministic_but_committed_tactics_cannot_be_revised() {
|
||||
let start = battle();
|
||||
let paid = steel(start, 0);
|
||||
assert!(paid.can_undo());
|
||||
let before = data(&paid);
|
||||
let undone = play(paid, 0, json!("Undo"));
|
||||
assert_eq!(undone.active_player(), 0);
|
||||
assert!(request(&undone).get("Payment").is_some());
|
||||
let redone = play(undone, 0, json!("Redo"));
|
||||
for field in ["players", "events", "rng", "asynchronous_combat_from"] {
|
||||
assert_eq!(data(&redone)[field], before[field], "{field}");
|
||||
}
|
||||
let committed = tactics(redone, 0, Some(3));
|
||||
assert!(!committed.can_undo());
|
||||
let rejected = server::action::try_execute_action(
|
||||
committed,
|
||||
serde_json::from_value(json!({"Response":{"SelectHandCards":[]}})).unwrap(),
|
||||
0,
|
||||
);
|
||||
assert!(rejected.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_rounds_do_not_repeat_battle_start_payments() {
|
||||
let mut g = battle();
|
||||
g.dice_roll_outcomes = vec![0; 40];
|
||||
let g = tactics(steel(tactics(steel(g, 0), 0, None), 1), 1, None);
|
||||
assert!(request(&g).get("BoolRequest").is_some(), "{}", request(&g));
|
||||
let g = play(g, 0, json!({"Response":{"Bool":false}}));
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
let round = &data(&g)["events"][0]["event_type"]["CombatRoundStart"];
|
||||
assert_eq!(round["combat"]["stats"]["round"], json!(2));
|
||||
assert_eq!(round["preparation"], Value::Null);
|
||||
assert_eq!(round["combat"]["modifiers"].as_array().unwrap().len(), 2);
|
||||
let g = tactics(g, 0, None);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(request(&g).get("SelectHandCards").is_some());
|
||||
}
|
||||
|
||||
fn historical_replay(to: usize) -> Game {
|
||||
server::replay::replay(
|
||||
serde_json::from_str(include_str!("fixtures/legacy_combat_history.json")).unwrap(),
|
||||
Some(to),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn historical_combat_replay_branches_enable_new_battles() {
|
||||
// Generated from a seeded game using legacy sequencing, not a mutated board
|
||||
// fixture. Includes completed battles and an open human-vs-human battle.
|
||||
let open = historical_replay(217);
|
||||
let expected: Value =
|
||||
serde_json::from_str(include_str!("fixtures/legacy_combat_history.expected.json")).unwrap();
|
||||
for (key, value) in expected.as_object().unwrap() {
|
||||
assert_eq!(&data(&open)[key], value, "0.4.153 compatibility: {key}");
|
||||
}
|
||||
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));
|
||||
let before = historical_replay(216);
|
||||
assert_eq!(before.asynchronous_combat_from, Some(217));
|
||||
let next = play(
|
||||
before,
|
||||
0,
|
||||
json!({"Movement":{"Move":{"destination":"E5","units":[3]}}}),
|
||||
);
|
||||
let round = &data(&next)["events"][0]["event_type"]["CombatRoundStart"];
|
||||
assert_eq!(round["combat"]["asynchronous_preparation"], 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"]);
|
||||
let continued = tactics(open, 1, None);
|
||||
assert!(
|
||||
continued.events.is_empty(),
|
||||
"legacy battle finishes normally"
|
||||
);
|
||||
|
||||
// Full replay of a legacy save ending before the next battle is playable too.
|
||||
let mut saved: Value =
|
||||
serde_json::from_str(include_str!("fixtures/legacy_combat_history.json")).unwrap();
|
||||
let turn = saved["log"].as_array_mut().unwrap().last_mut().unwrap()["rounds"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.last_mut()
|
||||
.unwrap()["turns"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.last_mut()
|
||||
.unwrap();
|
||||
turn["actions"].as_array_mut().unwrap().pop();
|
||||
saved["log_index"] = json!(saved["log_index"].as_u64().unwrap() - 1);
|
||||
let full = server::replay::replay(serde_json::from_value(saved).unwrap(), None).unwrap();
|
||||
let next = play(
|
||||
full,
|
||||
0,
|
||||
json!({"Movement":{"Move":{"destination":"E5","units":[3]}}}),
|
||||
);
|
||||
assert_eq!(
|
||||
data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"],
|
||||
json!(true)
|
||||
);
|
||||
|
||||
// A branch earlier than the original history's switch cannot inherit it.
|
||||
let earlier = historical_replay(167);
|
||||
let next = play(
|
||||
earlier,
|
||||
1,
|
||||
json!({"Movement":{"Move":{"destination":"F7","units":[1]}}}),
|
||||
);
|
||||
assert_eq!(
|
||||
data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"],
|
||||
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);
|
||||
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));
|
||||
let redone = play(undone, player, json!("Redo"));
|
||||
assert_eq!(redone.asynchronous_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));
|
||||
let undone = play(branched, player, json!("Undo"));
|
||||
assert_eq!(undone.asynchronous_combat_from, Some(next));
|
||||
let redone = play(undone, player, json!("Redo"));
|
||||
assert_eq!(redone.asynchronous_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);
|
||||
for p in [0, 1] {
|
||||
v["players"][p]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!("SteelWeapons"));
|
||||
}
|
||||
let action = json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}});
|
||||
let legacy = play(load(v), 0, action.clone());
|
||||
assert!(
|
||||
data(&legacy)["events"][0]["event_type"]
|
||||
.get("CombatStart")
|
||||
.is_some()
|
||||
);
|
||||
let undone = play(legacy, 0, json!("Undo"));
|
||||
let branch = play(undone, 0, action);
|
||||
let expected = data(&branch);
|
||||
assert_eq!(
|
||||
expected["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"],
|
||||
json!(true)
|
||||
);
|
||||
let undone = play(branch, 0, json!("Undo"));
|
||||
let redone = play(undone, 0, json!("Redo"));
|
||||
assert_eq!(data(&redone)["events"], expected["events"]);
|
||||
assert_eq!(
|
||||
data(&redone)["asynchronous_combat_from"],
|
||||
expected["asynchronous_combat_from"]
|
||||
);
|
||||
}
|
||||
|
|
@ -140,6 +140,12 @@ fn clean_json(expected: &str) -> String {
|
|||
// 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();
|
||||
if value["asynchronous_combat_from"] == serde_json::json!(usize::MAX) {
|
||||
value
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("asynchronous_combat_from");
|
||||
}
|
||||
// Only public action-log items qualify, never arbitrary arrays or game state.
|
||||
if let Some(ages) = value
|
||||
.get_mut("log")
|
||||
|
|
@ -463,7 +469,12 @@ pub fn load_game(path: &GamePath) -> Game {
|
|||
let game_data: GameData = serde_json::from_str(&read_game_str(path))
|
||||
.unwrap_or_else(|e| panic!("the game file should be deserializable {path}: {e}",));
|
||||
let cache = Cache::new(&game_data.options);
|
||||
let game = Game::from_data(game_data, cache, GameContext::Play);
|
||||
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.asynchronous_combat_from.is_none() {
|
||||
game.asynchronous_combat_from = Some(usize::MAX);
|
||||
}
|
||||
if update_expected() {
|
||||
write_result(&to_json(&game), path);
|
||||
}
|
||||
|
|
|
|||
483
server/tests/fixtures/legacy_combat_history.expected.json
vendored
Normal file
483
server/tests/fixtures/legacy_combat_history.expected.json
vendored
Normal file
|
|
@ -0,0 +1,483 @@
|
|||
{
|
||||
"players": [
|
||||
{
|
||||
"id": 0,
|
||||
"resources": {
|
||||
"wood": 4,
|
||||
"mood_tokens": 3,
|
||||
"culture_tokens": 2
|
||||
},
|
||||
"resource_limit": {
|
||||
"food": 2,
|
||||
"wood": 7,
|
||||
"ore": 7,
|
||||
"ideas": 7,
|
||||
"gold": 7
|
||||
},
|
||||
"cities": [
|
||||
{
|
||||
"city_pieces": {
|
||||
"market": 0
|
||||
},
|
||||
"mood_state": "Angry",
|
||||
"position": "D2"
|
||||
},
|
||||
{
|
||||
"city_pieces": {
|
||||
"market": 1
|
||||
},
|
||||
"mood_state": "Neutral",
|
||||
"position": "D4"
|
||||
}
|
||||
],
|
||||
"units": [
|
||||
{
|
||||
"position": "D5",
|
||||
"unit_type": "Elephant",
|
||||
"movement_restrictions": [
|
||||
"Battle"
|
||||
],
|
||||
"id": 3
|
||||
},
|
||||
{
|
||||
"position": "E2",
|
||||
"unit_type": "Infantry",
|
||||
"id": 5
|
||||
}
|
||||
],
|
||||
"civilization": "Phoenicia",
|
||||
"available_leaders": [
|
||||
"Ithobaal",
|
||||
"Hiram",
|
||||
"Pygmalion"
|
||||
],
|
||||
"advances": [
|
||||
"Bartering",
|
||||
"Currency",
|
||||
"Farming",
|
||||
"Fishing",
|
||||
"FreeEducation",
|
||||
"Husbandry",
|
||||
"Irrigation",
|
||||
"Mining",
|
||||
"Myths",
|
||||
"Navigation",
|
||||
"Priesthood",
|
||||
"Roads",
|
||||
"StateReligion",
|
||||
"Tactics",
|
||||
"Writing"
|
||||
],
|
||||
"incident_tokens": 1,
|
||||
"next_unit_id": 6
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"resources": {
|
||||
"wood": 5,
|
||||
"culture_tokens": 1
|
||||
},
|
||||
"resource_limit": {
|
||||
"food": 7,
|
||||
"wood": 7,
|
||||
"ore": 7,
|
||||
"ideas": 7,
|
||||
"gold": 7
|
||||
},
|
||||
"cities": [
|
||||
{
|
||||
"mood_state": "Angry",
|
||||
"position": "D7"
|
||||
},
|
||||
{
|
||||
"mood_state": "Happy",
|
||||
"position": "E5"
|
||||
},
|
||||
{
|
||||
"mood_state": "Neutral",
|
||||
"position": "F7"
|
||||
}
|
||||
],
|
||||
"units": [
|
||||
{
|
||||
"position": "E5",
|
||||
"unit_type": "Settler",
|
||||
"id": 3
|
||||
},
|
||||
{
|
||||
"position": "E5",
|
||||
"unit_type": "Infantry",
|
||||
"id": 4
|
||||
},
|
||||
{
|
||||
"position": "D7",
|
||||
"unit_type": "Settler",
|
||||
"id": 5
|
||||
}
|
||||
],
|
||||
"civilization": "India",
|
||||
"available_leaders": [
|
||||
"SriGupta",
|
||||
"Ashoka",
|
||||
"Akbar"
|
||||
],
|
||||
"advances": [
|
||||
"Arts",
|
||||
"Cartography",
|
||||
"Engineering",
|
||||
"Farming",
|
||||
"Fishing",
|
||||
"Math",
|
||||
"Mining",
|
||||
"Navigation",
|
||||
"Roads",
|
||||
"Sanitation",
|
||||
"Storage",
|
||||
"Tactics",
|
||||
"Writing"
|
||||
],
|
||||
"incident_tokens": 2,
|
||||
"completed_objectives": [
|
||||
{
|
||||
"card": 13,
|
||||
"name": "Wood Supplies"
|
||||
},
|
||||
{
|
||||
"card": 16,
|
||||
"name": "Goal Focused"
|
||||
}
|
||||
],
|
||||
"wonder_cards": [
|
||||
"Colosseum"
|
||||
],
|
||||
"action_cards": [
|
||||
33,
|
||||
9,
|
||||
30,
|
||||
12
|
||||
],
|
||||
"objective_cards": [
|
||||
17,
|
||||
15,
|
||||
19,
|
||||
4
|
||||
],
|
||||
"next_unit_id": 6
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"cities": [
|
||||
{
|
||||
"mood_state": "Neutral",
|
||||
"position": "B2"
|
||||
},
|
||||
{
|
||||
"mood_state": "Angry",
|
||||
"position": "B3"
|
||||
}
|
||||
],
|
||||
"units": [
|
||||
{
|
||||
"position": "E8",
|
||||
"unit_type": "Infantry",
|
||||
"id": 1
|
||||
},
|
||||
{
|
||||
"position": "C3",
|
||||
"unit_type": "Elephant",
|
||||
"id": 2
|
||||
},
|
||||
{
|
||||
"position": "C3",
|
||||
"unit_type": "Infantry",
|
||||
"id": 4
|
||||
},
|
||||
{
|
||||
"position": "C3",
|
||||
"unit_type": "Infantry",
|
||||
"id": 5
|
||||
},
|
||||
{
|
||||
"position": "B2",
|
||||
"unit_type": "Infantry",
|
||||
"id": 6
|
||||
},
|
||||
{
|
||||
"position": "B3",
|
||||
"unit_type": "Infantry",
|
||||
"id": 7
|
||||
}
|
||||
],
|
||||
"civilization": "Barbarians",
|
||||
"next_unit_id": 8
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"civilization": "Pirates",
|
||||
"next_unit_id": 0
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"event_type": {
|
||||
"CombatRoundStart": {
|
||||
"combat": {
|
||||
"attackers": [
|
||||
3
|
||||
],
|
||||
"retreat": "CanRetreat",
|
||||
"stats": {
|
||||
"round": 1,
|
||||
"battleground": "City",
|
||||
"attacker": {
|
||||
"position": "D5",
|
||||
"player": 0,
|
||||
"present": {
|
||||
"elephants": 1
|
||||
}
|
||||
},
|
||||
"defender": {
|
||||
"position": "E5",
|
||||
"player": 1,
|
||||
"present": {
|
||||
"settlers": 1,
|
||||
"infantry": 1
|
||||
}
|
||||
},
|
||||
"city_mood": "Happy"
|
||||
}
|
||||
},
|
||||
"attacker_strength": {},
|
||||
"defender_strength": {}
|
||||
}
|
||||
},
|
||||
"players_used": [
|
||||
0
|
||||
],
|
||||
"player": 1,
|
||||
"last_priority_used": 0,
|
||||
"handler": {
|
||||
"priority": 0,
|
||||
"request": {
|
||||
"SelectHandCards": {
|
||||
"choices": [
|
||||
{
|
||||
"ActionCard": 9
|
||||
},
|
||||
{
|
||||
"ActionCard": 12
|
||||
},
|
||||
{
|
||||
"ActionCard": 30
|
||||
},
|
||||
{
|
||||
"ActionCard": 33
|
||||
}
|
||||
],
|
||||
"needed": {
|
||||
"start": 0,
|
||||
"end": 1
|
||||
},
|
||||
"description": "Play Tactics Card"
|
||||
}
|
||||
},
|
||||
"origin": {
|
||||
"Advance": "Tactics"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"rng": "222724077733091596346276912534125779896",
|
||||
"map": {
|
||||
"tiles": [
|
||||
[
|
||||
"A3",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"A5",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"A7",
|
||||
"Unexplored"
|
||||
],
|
||||
[
|
||||
"B2",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"B3",
|
||||
"Mountain"
|
||||
],
|
||||
[
|
||||
"B4",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"B5",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"B6",
|
||||
"Unexplored"
|
||||
],
|
||||
[
|
||||
"B7",
|
||||
"Unexplored"
|
||||
],
|
||||
[
|
||||
"C2",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"C3",
|
||||
"Barren"
|
||||
],
|
||||
[
|
||||
"C4",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"C5",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"C6",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"C7",
|
||||
"Unexplored"
|
||||
],
|
||||
[
|
||||
"C8",
|
||||
"Mountain"
|
||||
],
|
||||
[
|
||||
"D1",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"D2",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"D3",
|
||||
"Mountain"
|
||||
],
|
||||
[
|
||||
"D4",
|
||||
"Mountain"
|
||||
],
|
||||
[
|
||||
"D5",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"D6",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"D7",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"D8",
|
||||
"Barren"
|
||||
],
|
||||
[
|
||||
"E2",
|
||||
"Mountain"
|
||||
],
|
||||
[
|
||||
"E3",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"E4",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"E5",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"E6",
|
||||
"Barren"
|
||||
],
|
||||
[
|
||||
"E7",
|
||||
{
|
||||
"Exhausted": "Fertile"
|
||||
}
|
||||
],
|
||||
[
|
||||
"E8",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"F2",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"F3",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"F4",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"F5",
|
||||
"Forest"
|
||||
],
|
||||
[
|
||||
"F6",
|
||||
"Barren"
|
||||
],
|
||||
[
|
||||
"F7",
|
||||
"Fertile"
|
||||
],
|
||||
[
|
||||
"G3",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"G5",
|
||||
"Water"
|
||||
],
|
||||
[
|
||||
"G7",
|
||||
"Water"
|
||||
]
|
||||
],
|
||||
"unexplored_blocks": [
|
||||
{
|
||||
"position": {
|
||||
"top_tile": "B6",
|
||||
"rotation": 0
|
||||
},
|
||||
"block": {
|
||||
"terrain": [
|
||||
"Water",
|
||||
"Fertile",
|
||||
"Fertile",
|
||||
"Barren"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"state": {
|
||||
"Movement": {
|
||||
"movement_actions_left": 2,
|
||||
"moved_units": [
|
||||
3
|
||||
]
|
||||
}
|
||||
},
|
||||
"actions_left": 2,
|
||||
"current_player_index": 0
|
||||
}
|
||||
3015
server/tests/fixtures/legacy_combat_history.json
vendored
Normal file
3015
server/tests/fixtures/legacy_combat_history.json
vendored
Normal file
File diff suppressed because it is too large
Load diff
17
server/tests/fixtures/legacy_combat_history.md
vendored
Normal file
17
server/tests/fixtures/legacy_combat_history.md
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Legacy combat replay regression
|
||||
|
||||
Synthetic seeded game (`historical-combat-0`), generated locally with legal AI
|
||||
choices and legacy combat sequencing; no production game or player data.
|
||||
`legacy_combat_history.json` contains only replay input: setup metadata and 217
|
||||
ordinary recorded actions. It includes completed battles and a pending battle at
|
||||
217. Cursor 167 precedes another battle; cursor 216 precedes the final battle.
|
||||
|
||||
The history was independently replayed with the frozen, downloaded production
|
||||
engine **0.4.153** (tarball SHA-256
|
||||
`0f65a03b0610cc8b52b2ce13e12f505bddfb2d680014bf0c5846844e816f9177`).
|
||||
`legacy_combat_history.expected.json` records its resulting
|
||||
players, events, RNG, board and turn state. Keep these fixtures frozen rather than
|
||||
regenerating them with normal golden game snapshots. Tests must reconstruct the
|
||||
legacy position exactly, finish an open legacy battle normally, and use new
|
||||
preparation when starting a battle from either a full-save or partial-history
|
||||
branch. Explicit switches and undo/redo have separate regressions.
|
||||
|
|
@ -22,6 +22,7 @@ const HIGH_MORALE: u8 = 6;
|
|||
|
||||
fn setup(attacker_cards: &[u8], defender_cards: &[u8]) -> Game {
|
||||
let mut game = JsonTest::new("tactics_cards").load_game("scout");
|
||||
game.asynchronous_combat_from = Some(0);
|
||||
game.players[0].action_cards = attacker_cards.to_vec();
|
||||
game.players[1].action_cards = defender_cards.to_vec();
|
||||
game
|
||||
|
|
|
|||
|
|
@ -1,275 +0,0 @@
|
|||
use serde_json::{Value, json};
|
||||
use server::{
|
||||
board_history,
|
||||
cache::Cache,
|
||||
early_choices,
|
||||
game::{Game, GameContext},
|
||||
game_data::GameData,
|
||||
};
|
||||
|
||||
fn load(value: Value) -> Game {
|
||||
let data: GameData = serde_json::from_value(value).unwrap();
|
||||
let cache = Cache::new(&data.options);
|
||||
Game::from_data(data, cache, GameContext::Play)
|
||||
}
|
||||
fn data(game: &Game) -> Value {
|
||||
serde_json::to_value(game.cloned_data()).unwrap()
|
||||
}
|
||||
fn play(game: Game, player: usize, action: Value) -> Game {
|
||||
board_history::execute(game, serde_json::from_value(action).unwrap(), player).unwrap()
|
||||
}
|
||||
fn battle() -> Game {
|
||||
let mut v: Value =
|
||||
serde_json::from_str(include_str!("test_games/tactics_cards/peltasts.json")).unwrap();
|
||||
for p in [0, 1] {
|
||||
v["players"][p]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!("SteelWeapons"));
|
||||
}
|
||||
v["players"][0]["action_cards"] = json!([3, 6, 11]);
|
||||
v["players"][1]["action_cards"] = json!([4, 7, 23]);
|
||||
play(
|
||||
load(v),
|
||||
0,
|
||||
json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}),
|
||||
)
|
||||
}
|
||||
fn key(g: &Game, p: usize) -> String {
|
||||
early_choices::offers(g, p)
|
||||
.into_iter()
|
||||
.find(|o| o.key.ends_with("/tactics"))
|
||||
.unwrap()
|
||||
.key
|
||||
}
|
||||
fn queue(g: Game, p: usize, card: Option<u8>) -> Game {
|
||||
let k = key(&g, p);
|
||||
let cards: Vec<Value> = card
|
||||
.into_iter()
|
||||
.map(|id| json!({"ActionCard":id}))
|
||||
.collect();
|
||||
play(
|
||||
g,
|
||||
p,
|
||||
json!({"QueueChoice":{"key":k,"response":{"SelectHandCards":cards}}}),
|
||||
)
|
||||
}
|
||||
fn steel(g: Game, p: usize) -> Game {
|
||||
play(g, p, json!({"Response":{"Payment":[{"ore":1}]}}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_metadata_edits_leave_payment_hand_rng_history_and_timing_untouched() {
|
||||
let g = battle();
|
||||
let original = data(&g);
|
||||
let enemy = data(&server::game_api::strip_secret(g.clone(), Some(1)));
|
||||
let spectator = data(&server::game_api::strip_secret(g.clone(), None));
|
||||
let k = key(&g, 0);
|
||||
let mut g = queue(g, 0, Some(3));
|
||||
for card in [None, Some(6), Some(3)] {
|
||||
g = queue(g, 0, card);
|
||||
}
|
||||
assert_eq!(
|
||||
data(&server::game_api::strip_secret(g.clone(), Some(1))),
|
||||
enemy
|
||||
);
|
||||
assert_eq!(
|
||||
data(&server::game_api::strip_secret(g.clone(), None)),
|
||||
spectator
|
||||
);
|
||||
let mut edited = data(&g);
|
||||
edited.as_object_mut().unwrap().remove("early_choices");
|
||||
edited
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("early_choice_update");
|
||||
assert_eq!(edited, original);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
g = play(g, 0, json!({"QueueChoice":{"key":k,"response":null}}));
|
||||
let mut cancelled = data(&g);
|
||||
cancelled
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("early_choice_update");
|
||||
assert_eq!(cancelled, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consume_only_at_real_prompt_once_and_keep_card_facedown_until_other_choice() {
|
||||
let g = queue(battle(), 0, Some(3));
|
||||
let k = key(&g, 0);
|
||||
let g = steel(g, 0);
|
||||
assert!(g.player(0).action_cards.contains(&3));
|
||||
assert_eq!(g.early_choices.len(), 1);
|
||||
let g = steel(load(data(&g)), 1);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(!g.player(0).action_cards.contains(&3));
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(g.current_event_handler().is_some());
|
||||
let hidden = data(&server::game_api::strip_secret(g.clone(), Some(1)));
|
||||
assert_eq!(
|
||||
hidden["events"][0]["event_type"]["CombatRoundStart"]["attacker_strength"]["tactics_card"],
|
||||
json!(0)
|
||||
);
|
||||
assert!(!early_choices::can_save(&g, 0, &k, None));
|
||||
assert!(!early_choices::can_save(&g, 1, &k, None)); // live tactics is not a queued choice
|
||||
let done = play(
|
||||
g,
|
||||
1,
|
||||
json!({"Response":{"SelectHandCards":[{"ActionCard":4}]}}),
|
||||
);
|
||||
assert!(done.early_choices.is_empty());
|
||||
assert!(!done.player(1).action_cards.contains(&4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_players_queue_and_automatic_execution_matches_ordinary_responses() {
|
||||
let g = battle();
|
||||
let queued = queue(queue(g.clone(), 0, Some(3)), 1, Some(4));
|
||||
let queued = steel(steel(queued, 0), 1);
|
||||
let normal = steel(steel(g, 0), 1);
|
||||
let normal = play(
|
||||
normal,
|
||||
0,
|
||||
json!({"Response":{"SelectHandCards":[{"ActionCard":3}]}}),
|
||||
);
|
||||
let normal = play(
|
||||
normal,
|
||||
1,
|
||||
json!({"Response":{"SelectHandCards":[{"ActionCard":4}]}}),
|
||||
);
|
||||
for field in [
|
||||
"players",
|
||||
"events",
|
||||
"rng",
|
||||
"dice_roll_log",
|
||||
"log",
|
||||
"time_increments",
|
||||
"action_cards_discarded",
|
||||
] {
|
||||
assert_eq!(data(&queued)[field], data(&normal)[field], "{field}");
|
||||
}
|
||||
assert!(queued.early_choices.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_card_and_scout_after_enemy_pass_fall_back_to_real_prompt() {
|
||||
let mut g = queue(battle(), 0, Some(3));
|
||||
g.players[0].action_cards.retain(|c| *c != 3);
|
||||
let g = steel(steel(g, 0), 1);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(g.early_choices.is_empty());
|
||||
let g = queue(queue(battle(), 0, None), 1, Some(23));
|
||||
let g = steel(steel(g, 0), 1);
|
||||
assert_eq!(g.active_player(), 1);
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(g.player(1).action_cards.contains(&23));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_tactics_ability_expires_instead_of_surviving_battle() {
|
||||
let mut g = queue(battle(), 1, Some(4));
|
||||
if let server::content::persistent_events::PersistentEventType::CombatStart(c) =
|
||||
&mut g.events[0].event_type
|
||||
{
|
||||
c.modifiers
|
||||
.push(server::combat::CombatModifier::TrojanHorse);
|
||||
}
|
||||
let g = queue(g, 0, None);
|
||||
let g = steel(steel(g, 0), 1);
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(g.player(1).action_cards.contains(&4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_battle_start_removes_plan_and_redo_does_not_resurrect_it() {
|
||||
let g = queue(battle(), 0, Some(3));
|
||||
let g = play(g, 0, json!("Undo"));
|
||||
assert!(g.early_choices.is_empty());
|
||||
let g = play(g, 0, json!("Redo"));
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(g.player(0).action_cards.contains(&3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_hand_during_seat_switch_never_becomes_an_offer() {
|
||||
let g = server::game_api::strip_secret(battle(), Some(0));
|
||||
assert!(
|
||||
early_choices::offers(&g, 1)
|
||||
.iter()
|
||||
.all(|o| !o.key.ends_with("/tactics"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn martyr_queue_does_not_choose_sacrifices_or_other_effect_responses() {
|
||||
let mut g = battle();
|
||||
g.players[0].action_cards.push(24);
|
||||
let g = queue(queue(g, 0, Some(24)), 1, Some(4));
|
||||
let g = steel(steel(g, 0), 1);
|
||||
assert!(g.early_choices.is_empty());
|
||||
let handler = g.current_event_handler().unwrap();
|
||||
assert!(matches!(
|
||||
handler.request,
|
||||
server::content::persistent_events::PersistentEventRequest::SelectUnits(_)
|
||||
));
|
||||
assert_eq!(g.active_player(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_defender_can_queue_during_attackers_normal_tactics_prompt() {
|
||||
let g = steel(steel(battle(), 0), 1);
|
||||
assert_eq!(g.active_player(), 0);
|
||||
let k = key(&g, 1);
|
||||
let g = queue(g, 1, Some(4));
|
||||
assert_eq!(g.active_player(), 0);
|
||||
assert!(g.player(1).action_cards.contains(&4));
|
||||
let g = play(
|
||||
g,
|
||||
0,
|
||||
json!({"Response":{"SelectHandCards":[{"ActionCard":3}]}}),
|
||||
);
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(!g.player(1).action_cards.contains(&4));
|
||||
assert!(!early_choices::can_save(&g, 1, &k, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_offers_tactics_only_after_own_steel_and_only_while_waiting() {
|
||||
let offered = |g: &Game, p| {
|
||||
server::web_view::view(g, Some(p))["earlyChoices"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|o| o["key"].as_str().unwrap().ends_with("/tactics"))
|
||||
};
|
||||
let g = battle();
|
||||
assert!(!offered(&g, 0));
|
||||
assert!(!offered(&g, 1));
|
||||
let g = steel(g, 0);
|
||||
assert!(offered(&g, 0));
|
||||
assert!(!offered(&g, 1));
|
||||
let g = queue(g, 0, Some(3));
|
||||
let g = steel(g, 1);
|
||||
assert!(!offered(&g, 1)); // defender now has the ordinary live tactics request
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_round_and_finished_battle_plans_are_pruned() {
|
||||
let mut g = queue(battle(), 0, Some(3));
|
||||
let old_key = key(&g, 0);
|
||||
if let server::content::persistent_events::PersistentEventType::CombatStart(c) =
|
||||
&mut g.events[0].event_type
|
||||
{
|
||||
c.stats.round += 1;
|
||||
}
|
||||
assert_ne!(key(&g, 0), old_key);
|
||||
early_choices::prune_objectives(&mut g);
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(!early_choices::can_save(&g, 0, &old_key, None));
|
||||
let mut g = queue(g, 0, Some(3));
|
||||
g.events.clear();
|
||||
early_choices::prune_objectives(&mut g);
|
||||
assert!(g.early_choices.is_empty());
|
||||
assert!(g.player(0).action_cards.contains(&3));
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
"civilization": "ChooseCivilization"
|
||||
},
|
||||
"version": 2,
|
||||
"asynchronous_combat_from": 0,
|
||||
"state": "ChooseCivilization",
|
||||
"players": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1522,3 +1522,47 @@ skips, and four localization-source tests passed. One full native rerun hit the
|
|||
pre-existing random-actions Tributes eligibility rejection; a subsequent complete
|
||||
workspace rerun passed without skipping or changing it. No Tributes rule changes
|
||||
are included. Svelte reports zero errors/warnings.
|
||||
|
||||
# Viewer 0.1.221 / engine 0.4.154 — prepared locally
|
||||
|
||||
Replaces combat tactics queues with committed ordinary preparation: attacker
|
||||
battle-start abilities and tactics, then defender battle-start abilities and
|
||||
tactics, then reveal/effects/rolls. Eligibility, Scouts, Loyalty (including a third
|
||||
player's Barbarian card), Martyr sacrifice and later-round rules are unchanged.
|
||||
No production moves or save repairs are involved. Other early-choice queues are
|
||||
retained; obsolete combat plans are pruned and never auto-consumed.
|
||||
|
||||
Old open combats retain legacy order. Historical replay uses its recorded format
|
||||
boundary (or legacy order when absent), then clamps the boundary to the returned
|
||||
cursor's next action. This permits new battles on both full and partial replay
|
||||
branches without reinterpreting old recorded responses. Undo/redo retains the
|
||||
recorded mode; replacing an undone future starts a new branch. The frozen synthetic
|
||||
217-action history was independently reconstructed by production engine 0.4.153;
|
||||
actual engine.replay regression checks compare its board, players, events and RNG.
|
||||
See `docs/asynchronous-combat-preparation.md` for the exact ordering contract.
|
||||
|
||||
Release preparation includes Rust 1.94.1 formatting/lint/native tests, Svelte,
|
||||
frontend/localization tests, bridge and production builds, packaged-engine
|
||||
protocol/replay/privacy checks, and built-viewer combat/payment/forces, tactics,
|
||||
journal, playback and split-WASM browser regressions. Local-host regression pays
|
||||
both Steel Weapons choices, commits both normal Tactics choices, checks opponent
|
||||
and spectator privacy, and asserts actual dice rolls with no combat queue.
|
||||
|
||||
Package-lock version and achievement source-integrity manifest are updated;
|
||||
artwork is generated only for validation, not published. Gallery, achievements,
|
||||
other game metadata and game-length labels/order/Standard default must remain
|
||||
unchanged. No special-rule changes, Fossil refresh or unrelated edits are included.
|
||||
|
||||
**Not yet shipped.** Frozen artifacts and verification evidence are prepared in
|
||||
`/tmp/release221`. Publish only after the matching source commit is pushed and
|
||||
both Check and Web viewer CI succeed. Use the supported publisher with the frozen
|
||||
0.4.154 tarball, then independently compare every hosted viewer asset and engine
|
||||
byte and run downloaded-engine checks. Do not reuse the 0.1.220 publish script.
|
||||
|
||||
Local verification result: **530 native tests passed, one existing ignored**,
|
||||
including 13 focused preparation/replay/undo tests. **1,090 frontend tests**,
|
||||
four gallery tests, 21 achievement tests without artifact-dependent skips, and
|
||||
four localization-source tests passed. Svelte reports zero errors/warnings;
|
||||
both 17-language catalogs validate. Rust 1.94.1 Clippy completes with existing
|
||||
warnings. Six actual-engine preparation tests also run against the extracted
|
||||
release tarball. No production publication is implied by these local results.
|
||||
|
|
|
|||
4
web-client/package-lock.json
generated
4
web-client/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.220",
|
||||
"version": "0.1.221",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.220",
|
||||
"version": "0.1.221",
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.11.0",
|
||||
"lucide-svelte": "^0.577.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.220",
|
||||
"version": "0.1.221",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -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": "6e1aa90692d42347f0e179bfdeb825efa2726405556ce9d3fa02779104309a4c",
|
||||
"web-client/package-lock.json": "f198e8d7b6e5cedc731a145c57146ac5db75f70ef6baf4683a066b5b054a07ab",
|
||||
"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"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/clash-server",
|
||||
"version": "0.4.153",
|
||||
"version": "0.4.154",
|
||||
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
|
||||
"license": "MIT",
|
||||
"type": "commonjs",
|
||||
|
|
|
|||
|
|
@ -9,8 +9,31 @@ const state = async () => {
|
|||
return JSON.parse(data.state);
|
||||
};
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
|
||||
await page.goto(base);
|
||||
const testWidth = Number(process.env.CLASH_TEST_WIDTH ?? 1400);
|
||||
const page = await browser.newPage({ viewport: { width: testWidth, height: 900 } });
|
||||
const submitted = [];
|
||||
page.on('request', (request) => {
|
||||
if (request.url().endsWith('/api/move') && request.method() === 'POST') {
|
||||
const body = request.postDataJSON();
|
||||
submitted.push(typeof body.move === 'string' ? JSON.parse(body.move) : body.move);
|
||||
}
|
||||
});
|
||||
if (process.env.VIEWER_URL) {
|
||||
await page.route('**/bundle/**', async (route) => {
|
||||
const name = new URL(route.request().url()).pathname.slice('/bundle/'.length);
|
||||
const response = await fetch(new URL(name, process.env.VIEWER_URL));
|
||||
assert(response.ok, name);
|
||||
await route.fulfill({
|
||||
contentType: name.endsWith('.wasm')
|
||||
? 'application/wasm'
|
||||
: name.endsWith('.json')
|
||||
? 'application/json'
|
||||
: 'text/javascript',
|
||||
body: Buffer.from(await response.arrayBuffer()),
|
||||
});
|
||||
});
|
||||
}
|
||||
await page.goto(`${base}/?built`);
|
||||
await page.locator('#scenario option[value="tactics"]').waitFor({ state: 'attached' });
|
||||
await page.locator('#scenario').selectOption('tactics');
|
||||
const steel = page.frameLocator('iframe').getByRole('region', { name: 'Steel Weapons', exact: true });
|
||||
|
|
@ -36,10 +59,71 @@ try {
|
|||
assert.equal((await state()).players[0].resources.gold, initial.players[0].resources.gold - 1);
|
||||
const game = page.frameLocator('iframe');
|
||||
const tactics = game.getByRole('region', { name: 'Tactics', exact: true });
|
||||
await tactics.waitFor();
|
||||
const ownTactics = await state();
|
||||
assert.equal(ownTactics.events.at(-1).player, 0);
|
||||
assert.deepEqual(ownTactics.map, initial.map);
|
||||
for (const width of [1400, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.screenshot({ path: `/tmp/clash-async-own-tactics-${width}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: testWidth, height: 900 });
|
||||
await tactics.getByRole('button', { name: 'Select Routing', exact: true }).click();
|
||||
await tactics.getByRole('button', { name: 'Queue tactics', exact: true }).click();
|
||||
await tactics.getByRole('button', { name: 'Play tactics', exact: true }).click();
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal((await state()).early_choices.length, 1);
|
||||
const committed = await state();
|
||||
assert.equal(committed.early_choices?.length ?? 0, 0);
|
||||
assert.equal(committed.events.at(-1).player, 1);
|
||||
assert.equal(committed.events.at(-1).event_type.CombatRoundStart.preparation, 'DefenderAbilities');
|
||||
for (const width of [1400, 390]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.screenshot({ path: `/tmp/clash-async-combat-${width}.png` });
|
||||
}
|
||||
// The attacker has committed, not queued: the other seat and spectator see
|
||||
// only a played-card marker until both ordinary Tactics responses complete.
|
||||
for (const seat of ['1', 'spectator']) {
|
||||
const hidden = JSON.parse((await (await fetch(`${base}/api/state?seat=${seat}`)).json()).state);
|
||||
assert.equal(hidden.events.at(-1).event_type.CombatRoundStart.attacker_strength.tactics_card, 0);
|
||||
assert(!hidden.action_cards_discarded?.includes(3));
|
||||
assert.equal(hidden.early_choices?.length ?? 0, 0);
|
||||
}
|
||||
await page.setViewportSize({ width: testWidth, height: 900 });
|
||||
await page.locator('#seat').selectOption('1');
|
||||
await steel.waitFor();
|
||||
await steel.getByRole('button', { name: 'Gold', exact: false }).click();
|
||||
await steel.getByRole('button', { name: 'Confirm', exact: true }).click();
|
||||
await tactics.waitFor();
|
||||
const defenderPaid = await state();
|
||||
assert.equal(defenderPaid.players[1].resources.gold, initial.players[1].resources.gold - 1);
|
||||
assert.equal(defenderPaid.events.at(-1).player, 1);
|
||||
assert.equal(await game.getByRole('button', { name: /Queue tactics/ }).count(), 0);
|
||||
await tactics.getByRole('button', { name: 'Select Peltasts', exact: true }).click();
|
||||
await tactics.getByRole('button', { name: 'Play tactics', exact: true }).click();
|
||||
await page.waitForFunction(async () => {
|
||||
const raw = JSON.parse((await (await fetch('/api/state?seat=0')).json()).state);
|
||||
return raw.log
|
||||
.flatMap((a) => a.rounds.flatMap((r) => r.turns.flatMap((t) => t.actions ?? [])))
|
||||
.some((a) => a.items?.some((i) => i.CombatRoll));
|
||||
});
|
||||
const rolled = await state();
|
||||
const actions = rolled.log.flatMap((a) => a.rounds.flatMap((r) => r.turns.flatMap((t) => t.actions ?? [])));
|
||||
const rolls = (items) => items.flatMap((a) => a.items ?? []).filter((i) => i.CombatRoll).length;
|
||||
const initialActions = initial.log.flatMap((a) =>
|
||||
a.rounds.flatMap((r) => r.turns.flatMap((t) => t.actions ?? [])),
|
||||
);
|
||||
assert(rolls(actions) >= rolls(initialActions) + 2, 'both sides actually rolled after the commitments');
|
||||
assert.deepEqual(
|
||||
submitted,
|
||||
[
|
||||
{ Response: { Payment: [{ gold: 1 }] } },
|
||||
{ Response: { SelectHandCards: [{ ActionCard: 3 }] } },
|
||||
{ Response: { Payment: [{ gold: 1 }] } },
|
||||
{ Response: { SelectHandCards: [{ ActionCard: 4 }] } },
|
||||
],
|
||||
'both normal payments and card responses commit exactly once; no queue action',
|
||||
);
|
||||
assert.equal(rolled.early_choices?.length ?? 0, 0);
|
||||
await page.locator('#seat').selectOption('0');
|
||||
await page.locator('#restart-scenario').click();
|
||||
await steel.waitFor();
|
||||
const restarted = await state();
|
||||
|
|
@ -54,7 +138,7 @@ try {
|
|||
!document.querySelector('#restart-scenario')?.disabled,
|
||||
);
|
||||
console.log(
|
||||
'Host select contrast in both themes; Steel fixture selection, payment/restart and fresh-tab restart passed.',
|
||||
`${testWidth}px: both Steel payments and ordinary Tactics commits, handoff, hidden-card privacy, both dice rolls, no combat queue, host themes and restart passed.`,
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
|
||||
export const previewScenarios = [
|
||||
{ id: 'tactics', label: 'Tactics · Steel Weapons', note: 'Local engine match. Queue tactics privately, then switch seats to resolve Steel Weapons and play the battle.' },
|
||||
{ id: 'tactics', label: 'Tactics · Steel Weapons', note: 'Local asynchronous sequence: attacker Steel Weapons and tactics, then defender Steel Weapons and tactics, then reveal.' },
|
||||
{ id: 'advance', label: 'Free advance', note: 'Research lets you save an early choice.' },
|
||||
{ id: 'raze', label: 'Raze city', note: 'Cities lets you save an early choice.' },
|
||||
{ id: 'objectives-before', label: 'Objectives · during turn', note: 'Queue in Objectives now; conditions are checked again before scoring.' },
|
||||
|
|
|
|||
|
|
@ -1,93 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { chromium } from 'playwright';
|
||||
const base = process.env.CLASH_PREVIEW_URL ?? 'http://localhost:8679';
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'],
|
||||
});
|
||||
assert.ok(['localhost', '127.0.0.1'].includes(new URL(base).hostname), 'local preview only');
|
||||
const state = async (seat) => await (await fetch(`${base}/api/state?seat=${seat}`)).json();
|
||||
try {
|
||||
for (const [width, height] of [
|
||||
[1400, 900],
|
||||
[390, 740],
|
||||
[320, 640],
|
||||
]) {
|
||||
await fetch(`${base}/api/scenarios`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ id: 'tactics' }),
|
||||
});
|
||||
const page = await browser.newPage({ viewport: { width, height } });
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(e.message));
|
||||
await page.goto(`${base}/?built`);
|
||||
await page.locator('#seat').selectOption('0');
|
||||
const game = page.frameLocator('iframe');
|
||||
const panel = game.getByRole('region', { name: 'Steel Weapons', exact: true });
|
||||
await panel.waitFor();
|
||||
assert.equal(await panel.locator('.tactics-queue').count(), 0);
|
||||
assert.equal(await game.getByRole('region', { name: 'Choose ahead', exact: true }).count(), 0);
|
||||
await page.screenshot({ path: `/tmp/clash-tactics-steel-${width}.png` });
|
||||
await panel.getByRole('button', { name: 'Gold', exact: false }).click();
|
||||
const before = JSON.parse((await state(0)).state);
|
||||
await panel.getByRole('button', { name: 'Confirm', exact: true }).click();
|
||||
await panel.waitFor({ state: 'hidden' });
|
||||
const paid = JSON.parse((await state(0)).state);
|
||||
assert.equal(paid.players[0].resources.gold, before.players[0].resources.gold - 1);
|
||||
assert.equal(paid.players[0].resources.ore, before.players[0].resources.ore);
|
||||
const commit = async (name) => {
|
||||
const response = page.waitForResponse(
|
||||
(r) => r.url().endsWith('/api/move') && r.request().method() === 'POST',
|
||||
);
|
||||
await choices.getByRole('button', { name, exact: true }).click();
|
||||
assert.equal((await response).status(), 200);
|
||||
};
|
||||
const choices = game.getByRole('region', { name: 'Tactics', exact: true });
|
||||
await choices.waitFor();
|
||||
assert.equal(await game.getByRole('region', { name: 'Choose ahead', exact: true }).count(), 0);
|
||||
assert(await choices.evaluate((el) => el.scrollWidth <= el.clientWidth + 1));
|
||||
await page.screenshot({ path: `/tmp/clash-tactics-queue-${width}.png` });
|
||||
await choices.getByRole('button', { name: 'Select Routing', exact: true }).click();
|
||||
assert.doesNotMatch(await choices.innerText(), /Discards the selected card/);
|
||||
await commit('Queue tactics');
|
||||
await choices.getByText('Queued', { exact: true }).waitFor();
|
||||
const queued = JSON.parse((await state(0)).state);
|
||||
for (const field of ['players', 'events', 'log', 'log_index', 'board_history', 'time_increments'])
|
||||
assert.deepEqual(queued[field], paid[field], field);
|
||||
assert.equal(queued.early_choices.length, 1);
|
||||
assert.equal(JSON.parse((await state(1)).state).early_choices, undefined);
|
||||
await choices.getByRole('button', { name: 'Select High Morale', exact: true }).click();
|
||||
assert.doesNotMatch(await choices.innerText(), /Discards the selected card/);
|
||||
await commit('Queue tactics');
|
||||
await commit('Cancel queued choice');
|
||||
await choices.getByText('Queued', { exact: true }).waitFor({ state: 'hidden' });
|
||||
await commit('Skip');
|
||||
await choices.getByText('Queued', { exact: true }).waitFor();
|
||||
assert.deepEqual(JSON.parse((await state(0)).state).early_choices[0].response, { SelectHandCards: [] });
|
||||
await choices.getByRole('button', { name: 'Select Routing', exact: true }).click();
|
||||
assert.doesNotMatch(await choices.innerText(), /Discards the selected card/);
|
||||
await commit('Queue tactics');
|
||||
await choices.getByText('Queued', { exact: true }).waitFor();
|
||||
await page.locator('#seat').selectOption('1');
|
||||
await panel.waitFor({ timeout: 10000 }).catch(async (e) => {
|
||||
console.log(await page.frames()[1].locator('body').innerText(), errors);
|
||||
throw e;
|
||||
});
|
||||
await panel.getByRole('button', { name: 'Confirm', exact: true }).click();
|
||||
const tactics = game.getByRole('region', { name: 'Tactics', exact: true });
|
||||
await tactics.waitFor();
|
||||
await tactics.getByRole('button', { name: 'Select Peltasts', exact: true }).click();
|
||||
assert.doesNotMatch(await tactics.innerText(), /Discards the selected card/);
|
||||
assert.equal(await tactics.getByRole('button', { name: 'Play tactics', exact: true }).count(), 1);
|
||||
assert.equal(await tactics.locator('.tactics-queue').count(), 0, 'current prompt is not a queued choice');
|
||||
await page.screenshot({ path: `/tmp/clash-tactics-live-${width}.png` });
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
console.log(
|
||||
`Steel first, automatic normal tactics queue/edit/cancel, privacy and ordinary live prompt: ${width}px passed`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
|
@ -102,7 +102,6 @@
|
|||
import CollectionCapacity from './CollectionCapacity.svelte';
|
||||
import ContextualCards from './ContextualCards.svelte';
|
||||
import DecisionPanel from './DecisionPanel.svelte';
|
||||
import { queuedTacticsDecision } from './queued-tactics';
|
||||
import EarlyChoices from './EarlyChoices.svelte';
|
||||
import EarlyChoiceBadge from './EarlyChoiceBadge.svelte';
|
||||
import CombatJournal from './CombatJournal.svelte';
|
||||
|
|
@ -137,14 +136,12 @@
|
|||
const planningQueue = $derived(!!queueControls?.pending && queueControls.seat === 0);
|
||||
let earlyPanel = $state<'cities' | 'abilities' | 'first' | null>(null);
|
||||
const earlyOffers = $derived(!$session.playback ? $session.view?.earlyChoices ?? [] : []);
|
||||
const tacticsQueue = $derived(!$session.view?.decision ? earlyOffers.find(o => o.key.endsWith('/tactics')) : undefined);
|
||||
const queuedTactics = $derived(queuedTacticsDecision($session.view, tacticsQueue));
|
||||
const earlyAdvance = $derived(earlyOffers.find(o => o.key.endsWith('/advance')));
|
||||
const earlyFirst = $derived(earlyOffers.filter(o => o.key.endsWith(':first')));
|
||||
const earlyCities = $derived(earlyOffers.filter(o => o.key.endsWith('/raze')));
|
||||
const earlyObjectives = $derived(earlyOffers.filter(o => o.key.includes(':objective:')));
|
||||
const earlyPeople = $derived(earlyOffers.filter(o => o.key.endsWith('/offer')));
|
||||
const earlyAbilities = $derived(earlyOffers.filter(o => !o.key.endsWith('/tactics') && !o.key.endsWith('/advance') && !o.key.endsWith('/raze') && !o.key.includes(':objective:') && !o.key.endsWith('/offer') && !o.key.endsWith('/government') && !o.key.endsWith(':first')));
|
||||
const earlyAbilities = $derived(earlyOffers.filter(o => !o.key.endsWith('/advance') && !o.key.endsWith('/raze') && !o.key.includes(':objective:') && !o.key.endsWith('/offer') && !o.key.endsWith('/government') && !o.key.endsWith(':first')));
|
||||
const panelOffers = $derived(earlyPanel === 'cities' ? earlyCities : earlyPanel === 'abilities' ? earlyAbilities : earlyPanel === 'first' ? earlyFirst : []);
|
||||
function openEarly(panel: 'cities' | 'abilities' | 'first') {
|
||||
earlyPanel = earlyPanel === panel ? null : panel;
|
||||
|
|
@ -1898,9 +1895,6 @@
|
|||
{controller}
|
||||
decision={$session.view.decision}
|
||||
onHighlight={(position) => world?.highlightCoordinate(position)}
|
||||
/>{/key}{:else if queuedTactics && tacticsQueue}{#key `${$session.seat}:${tacticsQueue.key}`}<DecisionPanel
|
||||
{controller} decision={queuedTactics} queue={tacticsQueue}
|
||||
onHighlight={(position) => world?.highlightCoordinate(position)}
|
||||
/>{/key}{/if}
|
||||
{#if $session.abilitiesOpen && $session.mode === 'overview' && !$session.view?.decision && !choiceDecision && !objectiveDecision}<AbilitiesPanel
|
||||
{controller}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@
|
|||
import { onDestroy } from 'svelte';
|
||||
import { untrack } from 'svelte';
|
||||
import { Check, Sparkles, Layers, BookOpen, ChevronRight, ArrowLeft, X, Zap, Wheat } from 'lucide-svelte';
|
||||
import type { TacticsQueue } from './queued-tactics';
|
||||
import type { Controller } from './controller';
|
||||
import type { Decision, Move, Pile, UnitKind } from './types';
|
||||
import { unitInfo } from './city';
|
||||
|
|
@ -34,18 +33,13 @@
|
|||
controller,
|
||||
decision,
|
||||
onHighlight,
|
||||
queue,
|
||||
}: { controller: Controller; decision: Decision; queue?: TacticsQueue; onHighlight: (position: string | null) => void } =
|
||||
}: { controller: Controller; decision: Decision; onHighlight: (position: string | null) => void } =
|
||||
$props();
|
||||
const session = $derived(controller.session);
|
||||
const announcedCard = $derived(pendingActionCard($session.view, decision));
|
||||
let announcedRulesOpen = $state(false);
|
||||
const panelId = $props.id();
|
||||
let queuedSelection = $state<number[]>(untrack(() => {
|
||||
const cards = (queue?.selected as {SelectHandCards?: unknown[]} | null)?.SelectHandCards ?? [];
|
||||
return decision.options.flatMap((o, i) => cards.some(c => JSON.stringify(c) === JSON.stringify(o.value)) ? [i] : []);
|
||||
}));
|
||||
const selected = $derived(queue ? queuedSelection : $session.decisionSelection);
|
||||
const selected = $derived($session.decisionSelection);
|
||||
const opponentTactics = $derived(opponentTacticsLabel(decision));
|
||||
const resourceChoice = $derived(decision.reward && decision.name === 'Select a resource to gain');
|
||||
const title = $derived(resourceChoice ? 'Gain resources' : printedCardName(decision.name));
|
||||
|
|
@ -139,7 +133,6 @@
|
|||
payments = payments.map((p, j) => (i === j ? payment : p));
|
||||
}
|
||||
const preview = $derived.by(() => {
|
||||
if (queue) return { action: {QueueChoice: {key: queue.key, response: {SelectHandCards: selected.map(i => decision.options[i].value)}}} as Move, error: '' };
|
||||
try {
|
||||
return {
|
||||
...controller.query<{ action: Move }>({
|
||||
|
|
@ -175,8 +168,7 @@
|
|||
return [...groups.values()].sort((a,b)=>a.order-b.order);
|
||||
});
|
||||
function toggle(i: number) {
|
||||
if (queue) queuedSelection = selected.includes(i) ? [] : [i];
|
||||
else controller.selectDecisionOption(i);
|
||||
controller.selectDecisionOption(i);
|
||||
}
|
||||
onDestroy(() => onHighlight(null));
|
||||
</script>
|
||||
|
|
@ -511,7 +503,7 @@
|
|||
Always keep cities in future ages
|
||||
</label>
|
||||
{/if}
|
||||
{#if !queue && (decision.tacticsSelection || decision.name === 'Siegecraft') && preview.action}
|
||||
{#if (decision.tacticsSelection || decision.name === 'Siegecraft') && preview.action}
|
||||
<CombatEstimate {controller} action={preview.action} />
|
||||
{/if}
|
||||
<div class="decision-footer" class:objective-exchange-footer={decision.objectiveExchange} class:map-decision-footer={mapChoice}>
|
||||
|
|
@ -535,11 +527,6 @@
|
|||
class="secondary"
|
||||
disabled={$session.pending}
|
||||
onclick={() => {
|
||||
if (queue) {
|
||||
queuedSelection = [];
|
||||
controller.submit({QueueChoice: {key: queue.key, response: {SelectHandCards: []}}});
|
||||
return;
|
||||
}
|
||||
const response = controller.query<{ action: Move }>({
|
||||
kind: 'decision',
|
||||
values: [],
|
||||
|
|
@ -552,7 +539,7 @@
|
|||
class="primary"
|
||||
disabled={!preview.action || $session.pending}
|
||||
onclick={() => preview.action && controller.submit(preview.action)}
|
||||
>{queue ? 'Queue tactics' : 'Play tactics'}<Check size={16} /></button
|
||||
>Play tactics<Check size={16} /></button
|
||||
>{/if}
|
||||
{:else}
|
||||
{#if decision.options.length && !mapChoice && !firstPlayerChoice}<div class="decision-count">
|
||||
|
|
@ -573,7 +560,7 @@
|
|||
title={preview.error || 'Confirm selection'}
|
||||
onclick={() => preview.action && controller.submit(preview.action)}
|
||||
>
|
||||
{selected.length === 0 && !decision.fields.length && decision.min === 0 ? 'Skip' : queue ? 'Queue tactics' : tribalStopChoice ? 'Continue' : 'Confirm'}{#if tribalStopChoice && selected.length}<ResourceAmount pile={{ food: 1 }} compact />{/if}<Check
|
||||
{selected.length === 0 && !decision.fields.length && decision.min === 0 ? 'Skip' : tribalStopChoice ? 'Continue' : 'Confirm'}{#if tribalStopChoice && selected.length}<ResourceAmount pile={{ food: 1 }} compact />{/if}<Check
|
||||
size={16}
|
||||
/>
|
||||
</button>
|
||||
|
|
@ -583,7 +570,6 @@
|
|||
</p>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if queue?.selected}<div class="choice-row"><span role="status">Queued</span><button disabled={$session.pending} onclick={() => { queuedSelection = []; controller.submit({QueueChoice: {key: queue!.key, response: null}}); }}>Cancel queued choice</button></div>{/if}
|
||||
{#if $session.error}<p class="inline-error" role="alert">{$session.error}</p>{/if}
|
||||
</section>
|
||||
|
||||
|
|
|
|||
|
|
@ -118,7 +118,8 @@ test('selected Steel Weapons and tactics responses are simulated before confirmi
|
|||
assert.notDeepEqual(withSteel, withoutSteel);
|
||||
raw = engine.tryMove(raw, JSON.stringify(paid), 0);
|
||||
raw = engine.tryMove(raw, JSON.stringify({ Response: { Payment: [{}, {}] } }), 0);
|
||||
raw = engine.tryMove(raw, JSON.stringify(paid), 1);
|
||||
// Attacker chooses tactics before the defender's battle-start payments.
|
||||
assert.equal(engine.currentPlayer(raw), 0);
|
||||
const visible = engine.stripSecret(raw, 0);
|
||||
const withTactic = estimate(visible, { Response: { SelectHandCards: [{ ActionCard: 1 }] } });
|
||||
const withoutTactic = estimate(visible, { Response: { SelectHandCards: [] } });
|
||||
|
|
|
|||
165
web-client/src/combat-preparation-engine.test.ts
Normal file
165
web-client/src/combat-preparation-engine.test.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
const engine = createRequire(import.meta.url)(process.env.CLASH_TEST_ENGINE ?? '../.engine/server.js');
|
||||
const apply = (raw: string, action: unknown, player = engine.currentPlayer(raw)) =>
|
||||
engine.tryMove(raw, JSON.stringify(action), player);
|
||||
const view = (raw: string, player: number) =>
|
||||
JSON.parse(engine.webView(engine.stripSecret(raw, player), player));
|
||||
const actions = (raw: string) =>
|
||||
JSON.parse(raw).log.flatMap((a: any) =>
|
||||
a.rounds.flatMap((r: any) => r.turns.flatMap((t: any) => t.actions ?? [])),
|
||||
);
|
||||
async function battle(legacy = false) {
|
||||
const g = JSON.parse(
|
||||
readFileSync(
|
||||
new URL('../../server/tests/test_games/tactics_cards/peltasts.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
if (legacy) g.asynchronous_combat_from = 999999;
|
||||
g.players = [
|
||||
...g.players.slice(0, 2),
|
||||
...JSON.parse(await engine.init(2, [], {}, 'combat-preparation', {})).players.slice(2),
|
||||
];
|
||||
for (const p of g.players.slice(0, 2)) {
|
||||
p.advances.push('SteelWeapons');
|
||||
p.resources.ore = 4;
|
||||
}
|
||||
g.players[0].action_cards = [3, 6, 11];
|
||||
g.players[1].action_cards = [4, 7, 23];
|
||||
return apply(
|
||||
JSON.stringify(g),
|
||||
{ Movement: { Move: { units: [0, 1, 2], destination: 'C1', payment: {} } } },
|
||||
0,
|
||||
);
|
||||
}
|
||||
test('actual engine completes each player preparation in order and replays ordinary responses', async () => {
|
||||
let raw = await battle();
|
||||
const before = raw;
|
||||
assert.equal(view(raw, 0).decision.name, 'Steel Weapons');
|
||||
raw = apply(raw, { Response: { Payment: [{ ore: 1 }] } });
|
||||
assert.equal(engine.currentPlayer(raw), 0);
|
||||
assert.equal(view(raw, 0).decision.name, 'Tactics');
|
||||
assert(!view(raw, 1).earlyChoices.some((o: any) => o.key.endsWith('/tactics')));
|
||||
raw = apply(raw, { Response: { SelectHandCards: [{ ActionCard: 3 }] } });
|
||||
assert.equal(engine.currentPlayer(raw), 1);
|
||||
assert.equal(view(raw, 1).decision.name, 'Steel Weapons');
|
||||
assert.equal(JSON.parse(raw).early_choices, undefined);
|
||||
assert(!JSON.parse(raw).players[0].action_cards.includes(3));
|
||||
for (const seat of [1, undefined]) {
|
||||
const hidden = JSON.parse(engine.stripSecret(raw, seat));
|
||||
assert.equal(hidden.events.at(-1).event_type.CombatRoundStart.attacker_strength.tactics_card, 0);
|
||||
assert(!hidden.action_cards_discarded?.includes(3));
|
||||
}
|
||||
raw = apply(raw, { Response: { Payment: [{ ore: 1 }] } });
|
||||
assert.equal(engine.currentPlayer(raw), 1);
|
||||
assert.equal(view(raw, 1).decision.name, 'Tactics');
|
||||
assert.equal(view(raw, 1).decision.opponentTactics, 'played');
|
||||
raw = apply(raw, { Response: { SelectHandCards: [{ ActionCard: 4 }] } });
|
||||
const added = actions(raw).slice(actions(before).length);
|
||||
assert.equal(added.filter((a: any) => a.action.Response?.SelectHandCards?.[0]?.ActionCard === 3).length, 1);
|
||||
let replay = before;
|
||||
for (const item of added) if (item.action !== 'StartTurn') replay = apply(replay, item.action, item.player);
|
||||
for (const field of ['players', 'events', 'rng', 'time_increments'])
|
||||
assert.deepEqual(JSON.parse(replay)[field], JSON.parse(raw)[field], field);
|
||||
});
|
||||
|
||||
test('legacy format replays both payments before either tactics response', async () => {
|
||||
let raw = await battle(true);
|
||||
const before = raw;
|
||||
raw = apply(raw, { Response: { Payment: [{ ore: 1 }] } }, 0);
|
||||
assert.equal(engine.currentPlayer(raw), 1);
|
||||
assert.equal(view(raw, 1).decision.name, 'Steel Weapons');
|
||||
raw = apply(raw, { Response: { Payment: [{ ore: 1 }] } }, 1);
|
||||
assert.equal(engine.currentPlayer(raw), 0);
|
||||
raw = apply(raw, { Response: { SelectHandCards: [{ ActionCard: 3 }] } }, 0);
|
||||
raw = apply(raw, { Response: { SelectHandCards: [{ ActionCard: 4 }] } }, 1);
|
||||
let replay = before;
|
||||
for (const item of actions(raw).slice(actions(before).length))
|
||||
if (item.action !== 'StartTurn') replay = apply(replay, item.action, item.player);
|
||||
for (const field of ['players', 'events', 'rng', 'time_increments'])
|
||||
assert.deepEqual(JSON.parse(replay)[field], JSON.parse(raw)[field], field);
|
||||
});
|
||||
|
||||
const historical = readFileSync(
|
||||
new URL('../../server/tests/fixtures/legacy_combat_history.json', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const attackNext = { Movement: { Move: { destination: 'E5', units: [3] } } };
|
||||
const mode = (raw: string) =>
|
||||
JSON.parse(raw).events?.at(-1)?.event_type.CombatRoundStart?.combat.asynchronous_preparation ?? false;
|
||||
test('engine.replay preserves legacy combats, but full-save and partial-history branches use new preparation', () => {
|
||||
const old = engine.replay(historical, {});
|
||||
assert.equal(engine.logLength(old), 217);
|
||||
const expected = JSON.parse(
|
||||
readFileSync(
|
||||
new URL('../../server/tests/fixtures/legacy_combat_history.expected.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
for (const [key, value] of Object.entries(expected))
|
||||
assert.deepEqual(JSON.parse(old)[key], value, `0.4.153 compatibility: ${key}`);
|
||||
assert.equal(mode(old), false);
|
||||
const finished = apply(old, { Response: { SelectHandCards: [] } }, 1);
|
||||
assert.equal(JSON.parse(finished).events?.length ?? 0, 0);
|
||||
for (const to of [167, 216]) {
|
||||
const branch = engine.replay(historical, { to });
|
||||
const next =
|
||||
to === 216
|
||||
? apply(branch, attackNext, 0)
|
||||
: apply(branch, { Movement: { Move: { destination: 'F7', units: [1] } } }, 1);
|
||||
assert.equal(mode(next), true);
|
||||
const replayed = engine.replay(next, {});
|
||||
for (const field of ['players', 'events', 'rng', 'asynchronous_combat_from'])
|
||||
assert.deepEqual(JSON.parse(replayed)[field], JSON.parse(next)[field], field);
|
||||
}
|
||||
const full = JSON.parse(historical);
|
||||
full.log.at(-1).rounds.at(-1).turns.at(-1).actions.pop();
|
||||
full.log_index--;
|
||||
const replayed = engine.replay(JSON.stringify(full), {});
|
||||
assert.equal(mode(apply(replayed, attackNext, 0)), true);
|
||||
});
|
||||
|
||||
test('engine.replay honors an explicit future switch only during reconstruction, not on a new branch', () => {
|
||||
const marked = JSON.parse(historical);
|
||||
marked.asynchronous_combat_from = 999999;
|
||||
assert.equal(mode(engine.replay(JSON.stringify(marked), {})), false);
|
||||
const branch = engine.replay(JSON.stringify(marked), { to: 216 });
|
||||
assert.equal(mode(apply(branch, attackNext, 0)), true);
|
||||
});
|
||||
|
||||
test('actual engine keeps undo/redo switch points but clamps a replacement branch', async () => {
|
||||
const setup = JSON.parse(await engine.init(2, [], {}, 'combat-undo-boundary', {}));
|
||||
setup.asynchronous_combat_from = 100;
|
||||
const research = { Playing: { Advance: { advance: 'Storage', payment: { food: 2 } } } };
|
||||
let raw = apply(JSON.stringify(setup), research);
|
||||
raw = apply(raw, 'Undo');
|
||||
assert.equal(JSON.parse(raw).asynchronous_combat_from, 100);
|
||||
raw = apply(raw, 'Redo');
|
||||
assert.equal(JSON.parse(raw).asynchronous_combat_from, 100);
|
||||
raw = apply(raw, 'Undo');
|
||||
const next = engine.logLength(raw) + 1;
|
||||
raw = apply(raw, research);
|
||||
assert.equal(JSON.parse(raw).asynchronous_combat_from, next);
|
||||
raw = apply(raw, 'Undo');
|
||||
assert.equal(JSON.parse(raw).asynchronous_combat_from, next);
|
||||
raw = apply(raw, 'Redo');
|
||||
assert.equal(JSON.parse(raw).asynchronous_combat_from, next);
|
||||
});
|
||||
|
||||
test('undo/redo of a newly branched battle cannot restore legacy order', async () => {
|
||||
let raw = await battle(true);
|
||||
const attack = actions(raw).at(-1).action;
|
||||
assert(JSON.parse(raw).events.at(-1).event_type.CombatStart);
|
||||
raw = apply(raw, 'Undo', 0);
|
||||
raw = apply(raw, attack, 0);
|
||||
assert.equal(mode(raw), true);
|
||||
const expected = JSON.parse(raw);
|
||||
raw = apply(raw, 'Undo', 0);
|
||||
raw = apply(raw, 'Redo', 0);
|
||||
assert.equal(mode(raw), true);
|
||||
for (const field of ['players', 'events', 'rng', 'asynchronous_combat_from'])
|
||||
assert.deepEqual(JSON.parse(raw)[field], expected[field], field);
|
||||
});
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Sæt taktik i kø",
|
||||
"Queued": "I kø",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Stålvåben afventer: +{p0} værdi hvis aktiveret",
|
||||
"No tactics": "Ingen taktik",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Taktik vormerken",
|
||||
"Queued": "Vorgemerkt",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Stahlwaffen ausstehend: +{p0} Wert bei Aktivierung",
|
||||
"No tactics": "Keine Taktik",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Προγραμμάτισε τακτική",
|
||||
"Queued": "Προγραμματίστηκε",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Εκκρεμούν ατσάλινα όπλα: +{p0} αξία αν ενεργοποιηθούν",
|
||||
"No tactics": "Χωρίς τακτική",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Queue tactics",
|
||||
"Queued": "Queued",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Steel Weapons pending: +{p0} value if activated",
|
||||
"No tactics": "No tactics",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "تاکتیک را در صف بگذار",
|
||||
"Queued": "در صف",
|
||||
"Steel Weapons pending: +{p0} value if activated": "سلاحهای فولادی در انتظار: +{p0} قدرت در صورت فعالسازی",
|
||||
"No tactics": "بدون تاکتیک",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Préparer la tactique",
|
||||
"Queued": "En attente",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Armes en acier en attente : +{p0} en valeur si activées",
|
||||
"No tactics": "Aucune tactique",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "रणनीति कतार में रखें",
|
||||
"Queued": "कतार में",
|
||||
"Steel Weapons pending: +{p0} value if activated": "इस्पात हथियार लंबित: सक्रिय होने पर +{p0} मूल्य",
|
||||
"No tactics": "कोई रणनीति नहीं",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Prepara tattica",
|
||||
"Queued": "In attesa",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Armi d’acciaio in attesa: +{p0} al valore se attivate",
|
||||
"No tactics": "Nessuna tattica",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "전술 예약",
|
||||
"Queued": "예약됨",
|
||||
"Steel Weapons pending: +{p0} value if activated": "강철 무기 대기 중: 활성화 시 전투력 +{p0}",
|
||||
"No tactics": "전술 없음",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Tactiek klaarzetten",
|
||||
"Queued": "Klaargezet",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Stalen wapens in afwachting: +{p0} waarde indien geactiveerd",
|
||||
"No tactics": "Geen tactiek",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Zaplanuj taktykę",
|
||||
"Queued": "Zaplanowano",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Broń stalowa oczekuje: +{p0} wartości po aktywacji",
|
||||
"No tactics": "Bez taktyki",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Preparar tática",
|
||||
"Queued": "Na fila",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Armas de aço pendentes: +{p0} de valor se ativadas",
|
||||
"No tactics": "Sem tática",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Pregătește tactica",
|
||||
"Queued": "În așteptare",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Arme de oțel în așteptare: +{p0} valoare dacă sunt activate",
|
||||
"No tactics": "Fără tactică",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Запланировать тактику",
|
||||
"Queued": "Запланировано",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Стальное оружие ожидает решения: +{p0} к силе при активации",
|
||||
"No tactics": "Без тактики",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "Xếp chiến thuật vào hàng đợi",
|
||||
"Queued": "Đã xếp hàng",
|
||||
"Steel Weapons pending: +{p0} value if activated": "Vũ khí thép đang chờ: +{p0} giá trị nếu kích hoạt",
|
||||
"No tactics": "Không dùng chiến thuật",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "预选战术",
|
||||
"Queued": "已预选",
|
||||
"Steel Weapons pending: +{p0} value if activated": "钢制武器待决定:激活后战斗值+{p0}",
|
||||
"No tactics": "不使用战术",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
{
|
||||
"Queue tactics": "預選戰術",
|
||||
"Queued": "已預選",
|
||||
"Steel Weapons pending: +{p0} value if activated": "鋼製武器待決定:啟用後戰鬥值+{p0}",
|
||||
"No tactics": "不使用戰術",
|
||||
|
|
|
|||
|
|
@ -1,42 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { queuedTacticsDecision, type TacticsQueue } from './queued-tactics.ts';
|
||||
import type { ActionCard, View } from './types.ts';
|
||||
const card = (id: number): ActionCard => ({
|
||||
id,
|
||||
name: 'Civil side',
|
||||
description: 'Civil rules',
|
||||
free: false,
|
||||
cost: {},
|
||||
tactics: { name: 'Routing', description: 'Battle rules' },
|
||||
reason: null,
|
||||
action: null,
|
||||
});
|
||||
const view = { actionCards: [card(3), card(0)] } as View;
|
||||
const offer: TacticsQueue = {
|
||||
key: 'battle/tactics',
|
||||
title: 'Tactics',
|
||||
selected: null,
|
||||
options: [
|
||||
[],
|
||||
[{ ActionCard: 3 }],
|
||||
[{ ActionCard: 4 }],
|
||||
[{ ActionCard: 0 }],
|
||||
[{ ActionCard: 3 }, { ActionCard: 4 }],
|
||||
].map((cards) => ({ label: 'offer', description: '', response: { SelectHandCards: cards } })),
|
||||
};
|
||||
test('queued tactics uses only single authorized cards in the owner hand, never hidden placeholders', () => {
|
||||
const decision = queuedTacticsDecision(view, offer)!;
|
||||
assert.equal(decision.tacticsSelection, true);
|
||||
assert.equal(decision.min, 0);
|
||||
assert.equal(decision.max, 1);
|
||||
assert.equal(decision.options.length, 1);
|
||||
assert.deepEqual(decision.options[0].value, { ActionCard: 3 });
|
||||
assert.equal(decision.options[0].card?.kind, 'action');
|
||||
assert.deepEqual(
|
||||
decision.options[0].card?.kind === 'action' && decision.options[0].card.tactics,
|
||||
card(3).tactics,
|
||||
);
|
||||
assert.equal(queuedTacticsDecision(null, offer), null);
|
||||
assert.equal(queuedTacticsDecision(view, undefined), null);
|
||||
});
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
import type { Decision, View } from './types';
|
||||
|
||||
export type TacticsQueue = NonNullable<View['earlyChoices']>[number];
|
||||
|
||||
/** Adapt only owner-authorized offer IDs to the normal hand-card decision UI. */
|
||||
export function queuedTacticsDecision(view: View | null, offer: TacticsQueue | undefined): Decision | null {
|
||||
if (!view || !offer) return null;
|
||||
return {
|
||||
reward: false,
|
||||
endOfAge: false,
|
||||
name: 'Tactics',
|
||||
description: '',
|
||||
min: 0,
|
||||
max: 1,
|
||||
fields: [],
|
||||
tacticsSelection: true,
|
||||
options: offer.options.flatMap((option) => {
|
||||
const cards = (option.response as { SelectHandCards?: { ActionCard?: number }[] }).SelectHandCards;
|
||||
const id = cards?.[0]?.ActionCard;
|
||||
if (!id || cards?.length !== 1) return [];
|
||||
const card = view.actionCards?.find((card) => card.id === id);
|
||||
return card?.tactics
|
||||
? [
|
||||
{
|
||||
value: { ActionCard: id },
|
||||
name: card.name,
|
||||
description: card.description,
|
||||
position: null,
|
||||
card: {
|
||||
kind: 'action' as const,
|
||||
name: card.name,
|
||||
description: card.description,
|
||||
tactics: card.tactics,
|
||||
},
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
|
@ -32,8 +32,12 @@ test('attacker can still pay to cancel both fortress abilities', () => {
|
|||
});
|
||||
for (const payment of [[{}, {}], [{ gold: 2 }, { gold: 2 }]]) {
|
||||
test(`saved defender prompt safely resolves ${JSON.stringify(payment)}`, () => {
|
||||
const g = attack(fixture());
|
||||
// Recreate the historical CombatStart format, not a corrupted new continuation.
|
||||
const initial = fixture();
|
||||
initial.asynchronous_combat_from = 999999;
|
||||
const g = attack(initial);
|
||||
const event = siege(g);
|
||||
assert(event.event_type.CombatStart);
|
||||
event.player = 1;
|
||||
event.players_used = [0];
|
||||
const after = move(g, { Response: { Payment: payment } }, 1);
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
const engine = createRequire(import.meta.url)(process.env.CLASH_TEST_ENGINE ?? '../.engine/server.js');
|
||||
const apply = (raw: string, action: unknown, player = engine.currentPlayer(raw)) =>
|
||||
engine.tryMove(raw, JSON.stringify(action), player);
|
||||
const view = (raw: string, player: number) =>
|
||||
JSON.parse(engine.webView(engine.stripSecret(raw, player), player));
|
||||
const actions = (raw: string) =>
|
||||
JSON.parse(raw).log.flatMap((a: any) =>
|
||||
a.rounds.flatMap((r: any) => r.turns.flatMap((t: any) => t.actions ?? [])),
|
||||
);
|
||||
async function battle() {
|
||||
const g = JSON.parse(
|
||||
readFileSync(
|
||||
new URL('../../server/tests/test_games/tactics_cards/peltasts.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
g.players = [
|
||||
...g.players.slice(0, 2),
|
||||
...JSON.parse(await engine.init(2, [], {}, 'tactics-queue', {})).players.slice(2),
|
||||
];
|
||||
for (const p of g.players.slice(0, 2)) {
|
||||
p.advances.push('SteelWeapons');
|
||||
p.resources.ore = 4;
|
||||
}
|
||||
g.players[0].action_cards = [3, 6, 11];
|
||||
g.players[1].action_cards = [4, 7, 23];
|
||||
return apply(
|
||||
JSON.stringify(g),
|
||||
{ Movement: { Move: { units: [0, 1, 2], destination: 'C1', payment: {} } } },
|
||||
0,
|
||||
);
|
||||
}
|
||||
test('actual packed engine queues privately after Steel; consumes once as a normal response and replays', async () => {
|
||||
let raw = await battle();
|
||||
assert(!view(raw, 0).earlyChoices.some((o: any) => o.key.endsWith('/tactics')));
|
||||
raw = apply(raw, { Response: { Payment: [{ ore: 1 }] } });
|
||||
const before = raw;
|
||||
const offer = view(raw, 0).earlyChoices.find((o: any) => o.key.endsWith('/tactics'));
|
||||
assert(offer);
|
||||
const command = JSON.stringify({
|
||||
QueueChoice: { key: offer.key, response: { SelectHandCards: [{ ActionCard: 3 }] } },
|
||||
});
|
||||
assert(engine.canMoveOutOfTurn(raw, command, 0));
|
||||
raw = engine.tryMove(raw, command, 0);
|
||||
assert(engine.isLiveUpdate(raw));
|
||||
for (const seat of [1, undefined])
|
||||
assert.deepEqual(JSON.parse(engine.stripSecret(raw, seat)), JSON.parse(engine.stripSecret(before, seat)));
|
||||
for (const field of ['players', 'events', 'rng', 'log', 'board_history', 'time_increments'])
|
||||
assert.deepEqual(JSON.parse(raw)[field], JSON.parse(before)[field], field);
|
||||
raw = apply(raw, { Response: { Payment: [{ ore: 1 }] } });
|
||||
assert.equal(engine.currentPlayer(raw), 1);
|
||||
assert.equal(JSON.parse(raw).early_choices, undefined);
|
||||
assert(!JSON.parse(raw).players[0].action_cards.includes(3));
|
||||
assert.equal(view(raw, 1).decision.opponentTactics, 'played');
|
||||
raw = apply(raw, { Response: { SelectHandCards: [{ ActionCard: 4 }] } });
|
||||
const added = actions(raw)
|
||||
.slice(actions(before).length)
|
||||
.map((a: any) => a.action);
|
||||
assert.equal(added.filter((a: any) => a.Response?.SelectHandCards?.[0]?.ActionCard === 3).length, 1);
|
||||
let replay = before;
|
||||
for (const action of added) if (action !== 'StartTurn') replay = apply(replay, action);
|
||||
for (const field of ['players', 'events', 'rng', 'time_increments'])
|
||||
assert.deepEqual(JSON.parse(replay)[field], JSON.parse(raw)[field], field);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue