diff --git a/server/src/action_queue.rs b/server/src/action_queue.rs index 3e75e697..31218375 100644 --- a/server/src/action_queue.rs +++ b/server/src/action_queue.rs @@ -43,40 +43,78 @@ pub fn offer(game: &Game, player: usize) -> Option<(String, String)> { { "Choosing an advance" } - (PersistentEventType::Incident(i), EventOrigin::Incident(id), - PersistentEventRequest::SelectPositions(request)) - if i.active_player == player && *id == i.incident_id - && [27, 28, 34, 35].contains(id) && handler.priority == 11 - && i.selected_player == Some(game.active_player()) - && request.choices.iter().all(|position| - game.player(game.active_player()).cities.iter().any(|city| city.position == *position)) => + ( + PersistentEventType::Incident(i), + EventOrigin::Incident(id), + PersistentEventRequest::SelectPositions(request), + ) if i.active_player == player + && *id == i.incident_id + && [27, 28, 34, 35].contains(id) + && handler.priority == 11 + && i.selected_player == Some(game.active_player()) + && request.choices.iter().all(|position| { + game.player(game.active_player()) + .cities + .iter() + .any(|city| city.position == *position) + }) => { "Placing a settler" } - (PersistentEventType::Incident(i), EventOrigin::Incident(id), - PersistentEventRequest::Payment(requests)) - if i.active_player == player && *id == i.incident_id - && !i.consumed && !i.replaced_by_sacrifice && i.selected_player.is_none() - && game.cache.get_incident(*id).action_card.is_some() - && handler.priority == 10 - && requests.iter().any(|request| request.name == "Pay to gain the Action Card") => + ( + PersistentEventType::Incident(i), + EventOrigin::Incident(id), + PersistentEventRequest::Payment(requests), + ) if i.active_player == player + && *id == i.incident_id + && !i.consumed + && !i.replaced_by_sacrifice + && i.selected_player.is_none() + && game.cache.get_incident(*id).action_card.is_some() + && handler.priority == 10 + && requests + .iter() + .any(|request| request.name == "Pay to gain the Action Card") => { game.cache.get_incident(*id).name.as_str() } - (PersistentEventType::Incident(i), EventOrigin::Incident(id), - PersistentEventRequest::SelectPlayer(_)) - if i.active_player == player && *id == 57 && i.incident_id == *id - && handler.priority == 1 && i.selected_player == Some(game.active_player()) => + ( + PersistentEventType::Incident(i), + EventOrigin::Incident(id), + PersistentEventRequest::SelectPlayer(_), + ) if i.active_player == player + && *id == 57 + && i.incident_id == *id + && handler.priority == 1 + && i.selected_player == Some(game.active_player()) => { "Choose a player" } + ( + PersistentEventType::Incident(i), + EventOrigin::Incident(47), + PersistentEventRequest::ResourceReward(_), + ) if i.active_player == player + && i.incident_id == 47 + && !i.consumed + && !i.replaced_by_sacrifice + && i.selected_player.is_none() + && handler.priority == 0 => + { + // Only Era of Stability's reward, never its earlier exhausted-land + // choice or another incident's resource/mood effects. + "Choose resources" + } _ => return None, }; - // Passing a Great Person to another recipient (or choosing a Diplomat - // partner) continues the same unresolved reaction. Preserve queued actions - // and the explicit Wait preference while that reaction progresses. - if let Some(plan) = game.action_plan.as_ref().filter(|plan| - plan.player == player && plan.error.is_none()) { + // Passing a Great Person to another recipient, choosing a Diplomat partner, + // or handing off Era of Stability rewards continues the same unresolved + // reaction. Preserve queued actions and the explicit Wait preference. + if let Some(plan) = game + .action_plan + .as_ref() + .filter(|plan| plan.player == player && plan.error.is_none()) + { return Some((plan.key.clone(), label.into())); } let key = format!( diff --git a/server/src/board_history.rs b/server/src/board_history.rs index e8e7ca24..8de97dcb 100644 --- a/server/src/board_history.rs +++ b/server/src/board_history.rs @@ -158,15 +158,23 @@ fn title(action: &Action) -> String { } pub fn execute(game: Game, action: Action, player: usize) -> Result { - if matches!(action, Action::QueueChoice { .. } | Action::QueueMoves { .. }) { + if matches!( + action, + Action::QueueChoice { .. } | Action::QueueMoves { .. } + ) { return try_execute_action(game, action, player); } - let undo = matches!(action, Action::Undo); + let history_navigation = matches!(action, Action::Undo | Action::Redo); let mut game = execute_one(game, action, player)?; crate::early_choices::prune_objectives(&mut game); + // Navigating history must not start fresh automatic actions or resume plans: + // those could otherwise award credits (and make Undo immediately redo itself). + if history_navigation { + return Ok(game); + } // Save automatic responses as ordinary actions. Replay then reproduces them // without needing past settings; undo never immediately replays a skipped choice. - while !undo && game.context == crate::game::GameContext::Play { + while game.context == crate::game::GameContext::Play { if let Some(response) = crate::early_choices::take_ready(&mut game) { let player = game.active_player(); game = execute_one(game, Action::Response(response), player)?; @@ -175,10 +183,18 @@ pub fn execute(game: Game, action: Action, player: usize) -> Result Result ActionCard { )) }, |game, s, a| { - game.information_revealed(); // can't undo swap - the other player saw your card + if s.choice.is_empty() { + // Keep the existing undo boundary, but declining reveals no card. + game.lock_undo(); + } else { + game.information_revealed(); // the other player saw your card + } let _ = swap_spy_cards( game, diff --git a/server/src/content/civilizations/celts.rs b/server/src/content/civilizations/celts.rs index 1377ebd5..aaae4e5f 100644 --- a/server/src/content/civilizations/celts.rs +++ b/server/src/content/civilizations/celts.rs @@ -162,7 +162,9 @@ pub(crate) fn loyalty_controller(game: &Game, c: &Combat) -> Option { .find(|p| { p.index != c.opponent(barb) && p.active_leader() == Some(Leader::Viriatus) - && game.map.within_revealed_distance(leader_position(p), c.defender_position(), 2) + && game + .map + .within_revealed_distance(leader_position(p), c.defender_position(), 2) }) .map(|p| p.index) } @@ -194,9 +196,33 @@ fn viriatus() -> LeaderInfo { .add_hand_card_request(|e|&mut e.loyalty,0,|game,p,r|{ let barb=r.combat.players().into_iter().find(|id|game.player(*id).civilization.is_barbarian())?; if get_combat_strength(barb,r).deny_tactics_card{return None;} - let cards=p.get(game).action_cards.iter().filter(|id|crate::tactics_card::can_play_tactics_card(game,barb,game.cache.get_action_card(**id),&r.combat)).map(|id|HandCard::ActionCard(*id)).collect(); + let cards=p.get(game).action_cards.iter().filter(|id|crate::tactics_card::can_play_tactics_card(game,barb,game.cache.get_action_card(**id),r)).map(|id|HandCard::ActionCard(*id)).collect(); Some(HandCardsRequest::new(cards,0..=1,"Loyalty · Play a tactics card for the Barbarians")) - },|game,s,r|{if let Some(HandCard::ActionCard(id))=s.choice.first(){let barb=r.combat.players().into_iter().find(|id|game.player(*id).civilization.is_barbarian()).unwrap();game.player_mut(barb).custom_data.insert("Loyalty controller".into(),crate::player::Data::Number(s.player_index as u32));update_combat_strength(game,barb,r,|_,_,strength,_|strength.tactics_card=Some(*id));crate::action_card::discard_action_card(game,s.player_index,*id,&s.origin,HandCardLocation::PlayToDiscardFaceDown);}}).build()) + }, |game, s, r| { + if let Some(HandCard::ActionCard(id)) = s.choice.first() { + let barb = r.combat.players().into_iter() + .find(|id| game.player(*id).civilization.is_barbarian()) + .expect("Loyalty requires a Barbarian combatant"); + assert!( + !get_combat_strength(barb, r).deny_tactics_card + && crate::tactics_card::can_play_tactics_card( + game, barb, game.cache.get_action_card(*id), r, + ), + "Tactics card requirements are not met" + ); + game.player_mut(barb).custom_data.insert( + "Loyalty controller".into(), + crate::player::Data::Number(s.player_index as u32), + ); + update_combat_strength(game, barb, r, |_, _, strength, _| { + strength.tactics_card = Some(*id); + }); + crate::action_card::discard_action_card( + game, s.player_index, *id, &s.origin, + HandCardLocation::PlayToDiscardFaceDown, + ); + } + }).build()) } fn rapid_recruitment(mut b: LeaderAbilityBuilder) -> LeaderAbilityBuilder { for i in 0..8u32 { diff --git a/server/src/content/tactics_cards.rs b/server/src/content/tactics_cards.rs index b5eb3f2e..6886d22f 100644 --- a/server/src/content/tactics_cards.rs +++ b/server/src/content/tactics_cards.rs @@ -8,7 +8,8 @@ use crate::game::Game; use crate::position::Position; use crate::resource_pile::ResourcePile; use crate::tactics_card::{ - CombatLocation, CombatRole, FighterRequirement, TacticsCard, TacticsCardTarget, + CombatLocation, CombatRole, FighterRequirement, OpponentTacticsStatus, TacticsCard, + TacticsCardTarget, opponent_tactics_status, }; use crate::unit::set_unit_position; use crate::utils::a_or_an; @@ -131,7 +132,8 @@ pub(crate) fn high_ground(id: u8) -> TacticsCard { "Unless you attack a city: Your opponent can't use dice-symbol abilities this round.", ) .location_requirement(CombatLocation::Land) - .checker(|player, game, combat| { + .checker(|player, game, round| { + let combat = &round.combat; combat.role(player) == CombatRole::Defender || combat.defender_city(game).is_none() }) .target(TacticsCardTarget::Opponent) @@ -253,7 +255,7 @@ pub(crate) fn tactical_retreat(id: u8) -> TacticsCard { ) .fighter_requirement(FighterRequirement::Army) .role_requirement(CombatRole::Defender) - .checker(|_, game, c| !tactical_retreat_targets(c, game).is_empty()) + .checker(|_, game, round| !tactical_retreat_targets(&round.combat, game).is_empty()) .add_position_request( |event| &mut event.combat_round_start_tactics, 0, @@ -311,6 +313,9 @@ pub(crate) fn scout(id: u8) -> TacticsCard { "Scout", "Ignore the enemy tactics card and take it to your hand.", ) + .checker(|player, game, round| { + opponent_tactics_status(game, player, round) != OpponentTacticsStatus::None + }) .add_simple_persistent_event_listener( |event| &mut event.combat_round_start_reveal_tactics, 0, diff --git a/server/src/game.rs b/server/src/game.rs index 4f0d5def..b3f9c2f1 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -145,6 +145,10 @@ pub struct Game { pub current_player_index: usize, pub log: Vec, pub board_history: crate::board_history::BoardHistory, + /// Monotonic platform credits; deliberately outside the undoable position. + pub(crate) time_increments: Vec, + /// Transient signal for one saved atomic action, not a persisted undo cursor. + pub(crate) timing_revealed: bool, // index for the next action log pub log_index: usize, pub undo_limit: usize, @@ -247,6 +251,7 @@ impl Game { } pub(crate) fn information_revealed(&mut self) { + self.timing_revealed = true; self.lock_undo(); } @@ -254,7 +259,7 @@ impl Game { self.lock_undo(); } - fn lock_undo(&mut self) { + pub(crate) fn lock_undo(&mut self) { if self.context != GameContext::AI { self.undo_limit = self.log_index; current_turn_log_mut(self).clear_undo(); diff --git a/server/src/game_api.rs b/server/src/game_api.rs index 248a110e..9144d88f 100644 --- a/server/src/game_api.rs +++ b/server/src/game_api.rs @@ -1,6 +1,7 @@ use super::player::Player; use crate::action::execute_action; use crate::card::{HandCard, HandCardLocation}; +use crate::combat_listeners::CombatEventPhase; use crate::content::effects::PermanentEffect; use crate::content::persistent_events::{ EventResponse, PersistentEventRequest, PersistentEventType, @@ -146,8 +147,15 @@ pub fn civilizations(game: Game) -> Vec { #[must_use] pub fn strip_secret(mut game: Game, player_index: Option) -> Game { - if game.action_plan.as_ref().is_some_and(|p| Some(p.player) != player_index) {game.action_plan=None;} - game.early_choices.retain(|c| Some(c.player) == player_index); + if game + .action_plan + .as_ref() + .is_some_and(|p| Some(p.player) != player_index) + { + game.action_plan = None; + } + game.early_choices + .retain(|c| Some(c.player) == player_index); if let Some(draft) = &mut game.civilization_draft { for i in 0..draft.offers.len() { if player_index != Some(i) { @@ -210,7 +218,7 @@ fn strip_action(action: &mut ActionLogAction, player_index: Option) { for item in &mut action.items { if let ActionLogEntry::HandCard { card, from, to } = &mut item.entry - && is_visible_card_info(player_index, from, to) + && !is_visible_card_info(player_index, from, to) { match &card { HandCard::ActionCard(_) => *card = HandCard::ActionCard(0), @@ -226,13 +234,13 @@ fn is_visible_card_info( from: &HandCardLocation, to: &HandCardLocation, ) -> bool { - from.player() == player_index - || to.player() == player_index + player_index.is_some_and(|player| from.player() == Some(player) || to.player() == Some(player)) || from.is_public() || to.is_public() } fn strip_events(game: &mut Game, player_index: Option) { + let mut pending_tactics = Vec::new(); for s in &mut game.events { match &mut s.event_type { PersistentEventType::CustomAction(a) @@ -248,11 +256,29 @@ fn strip_events(game: &mut Game, player_index: Option) { } } } - PersistentEventType::CombatRoundStart(r) => { - if r.attacker_strength.tactics_card.is_some() { - // defender shouldn't see attacker's tactics card - r.attacker_strength.tactics_card = Some(0); + PersistentEventType::CombatRoundStart(r) + if matches!( + r.phase, + CombatEventPhase::AllowTacticsCard + | CombatEventPhase::Loyalty + | CombatEventPhase::Default + ) => + { + // Committing immediately adds the card to the discard pile. Save + // the real IDs before replacing them with the presence sentinel. + for (card, participant) in [ + (r.attacker_strength.tactics_card, r.combat.attacker()), + (r.defender_strength.tactics_card, r.combat.defender()), + ] { + if let Some(card) = card.filter(|id| *id != 0) { + pending_tactics.push((card, participant)); + } } + // Either side may commit first (Loyalty can supply the defender). + // Keep presence for eligibility/status, but never disclose the ID + // before reveal. Owners still see their own card in the transfer log. + r.attacker_strength.tactics_card = r.attacker_strength.tactics_card.map(|_| 0); + r.defender_strength.tactics_card = r.defender_strength.tactics_card.map(|_| 0); } PersistentEventType::SelectObjectives(o) if Some(s.player.index) != player_index => { // player shouldn't see other player's objectives @@ -279,4 +305,24 @@ fn strip_events(game: &mut Game, player_index: Option) { } } } + pending_tactics.sort_unstable(); + pending_tactics.dedup(); + for (card, participant) in pending_tactics { + // The hand owner may be the Loyalty controller, not the combatant. + // Match discard_card's insertion end and mask only this commitment: + // an earlier, publicly discarded copy of the same ID can remain here. + let owner = crate::content::civilizations::celts::delegated_player(game, participant); + let discarded = &mut game.action_cards_discarded; + let position = if game.players[owner] + .wonders_owned + .contains(Wonder::GreatMausoleum) + { + discarded.iter().position(|id| *id == card) + } else { + discarded.iter().rposition(|id| *id == card) + }; + if let Some(position) = position { + discarded[position] = 0; + } + } } diff --git a/server/src/game_api_wrapper.rs b/server/src/game_api_wrapper.rs index 2388ae69..0e15a630 100644 --- a/server/src/game_api_wrapper.rs +++ b/server/src/game_api_wrapper.rs @@ -62,7 +62,9 @@ pub fn set_player_settings( if settings.skip_raze_city.is_some() { p.settings.skip_raze_city = settings.skip_raze_city; } - if settings.keep_government.is_some() { p.settings.keep_government = settings.keep_government; } + if settings.keep_government.is_some() { + p.settings.keep_government = settings.keep_government; + } Ok(from_game(game)) } @@ -181,8 +183,12 @@ pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) -> if let Some(raw) = move_data.as_string() && let Ok(crate::action::Action::QueueMoves { key, .. }) = serde_json::from_str(&raw) { - return crate::action_queue::offer(&game, player).is_some_and(|(current,_)| current == key) - || game.action_plan.as_ref().is_some_and(|p|p.player==player && p.key==key && p.error.is_some()); + return crate::action_queue::offer(&game, player) + .is_some_and(|(current, _)| current == key) + || game + .action_plan + .as_ref() + .is_some_and(|p| p.player == player && p.key == key && p.error.is_some()); } if let Some(raw) = move_data.as_string() && let Ok(crate::action::Action::QueueChoice { key, response }) = serde_json::from_str(&raw) @@ -208,9 +214,19 @@ pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) -> #[wasm_bindgen(js_name = "isLiveUpdate")] pub fn is_live_update(data: String) -> bool { let game = get_game(data); - game.early_choice_update || game - .civilization_draft - .is_some_and(|draft| draft.live_update) + game.early_choice_update + || game + .civilization_draft + .is_some_and(|draft| draft.live_update) +} + +/// Protocol clock hook: a JS array of cumulative human-seat credits, not JSON. +#[wasm_bindgen(js_name = "timeIncrements")] +pub fn time_increments(data: String) -> JsValue { + with_view_game(data, |game| { + serde_wasm_bindgen::to_value(&crate::timing::time_increments(game)) + .expect("time increments should serialize") + }) } #[wasm_bindgen(js_name = "logLength")] diff --git a/server/src/game_data.rs b/server/src/game_data.rs index de5a541c..353603dc 100644 --- a/server/src/game_data.rs +++ b/server/src/game_data.rs @@ -64,6 +64,12 @@ pub struct GameData { skip_serializing_if = "crate::board_history::BoardHistory::is_empty" )] board_history: crate::board_history::BoardHistory, + #[serde( + default, + skip_serializing_if = "Vec::is_empty", + deserialize_with = "crate::timing::deserialize_counters" + )] + time_increments: Vec, log_index: usize, undo_limit: usize, actions_left: u32, @@ -136,6 +142,8 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { successful_cultural_influence: data.successful_cultural_influence, log: data.log, board_history: data.board_history, + time_increments: data.time_increments, + timing_revealed: false, log_index: data.log_index, undo_limit: data.undo_limit, round: data.round, @@ -161,7 +169,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { if game.options.legacy_undo.take().as_deref() == Some("SamePlayer") { game.undo_limit = game.log_index; if !game.log.is_empty() { - game.information_revealed(); + game.lock_undo(); } } for player_data in data.players { @@ -192,6 +200,7 @@ pub fn data(game: Game) -> GameData { current_player_index: game.current_player_index, log: game.log, board_history: game.board_history, + time_increments: game.time_increments, log_index: game.log_index, undo_limit: game.undo_limit, actions_left: game.actions_left, @@ -232,6 +241,7 @@ pub fn cloned_data(game: &Game) -> GameData { current_player_index: game.current_player_index, log: game.log.clone(), board_history: game.board_history.clone(), + time_increments: game.time_increments.clone(), log_index: game.log_index, undo_limit: game.undo_limit, actions_left: game.actions_left, diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs index 6d0d759e..b193bcc3 100644 --- a/server/src/game_setup.rs +++ b/server/src/game_setup.rs @@ -210,6 +210,8 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game { current_player_index: starting_player, log: Vec::new(), board_history: Default::default(), + time_increments: vec![], + timing_revealed: false, log_index: 0, undo_limit: 0, actions_left: ACTIONS, diff --git a/server/src/lib.rs b/server/src/lib.rs index 9552e105..861e457d 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -13,10 +13,9 @@ extern crate core; pub mod ability_initializer; pub mod action; -pub mod early_choices; -pub mod action_queue; pub mod action_card; mod action_cost; +pub mod action_queue; pub mod advance; #[cfg(not(target_arch = "wasm32"))] pub mod ai; @@ -43,11 +42,11 @@ pub mod construct; pub mod consts; pub mod content; pub mod cultural_influence; +pub mod early_choices; pub mod events; mod explore; pub mod game; pub mod game_api; -mod move_summary; pub mod game_api_wrapper; pub mod game_data; pub mod game_setup; @@ -58,6 +57,7 @@ mod leader_ability; pub mod log; pub mod map; mod move_routes; +mod move_summary; pub mod movement; pub mod objective_card; pub mod payment; @@ -75,6 +75,7 @@ mod special_advance; pub mod status_phase; pub mod structure; pub mod tactics_card; +pub mod timing; mod undo; pub mod unit; pub mod utils; diff --git a/server/src/payment.rs b/server/src/payment.rs index 85df82fe..15280709 100644 --- a/server/src/payment.rs +++ b/server/src/payment.rs @@ -427,6 +427,78 @@ pub fn can_convert( ) } +// Bounds describe only directions, not amounts: if no remaining conversion can +// decrease a resource, an excess can never become affordable. For an exact +// payment, a missing resource must likewise still be producible. The total is +// included to reject under/overpayment of one-for-one exchanges immediately. +// These are necessary conditions only; the ordinary search still proves every +// accepted payment, including chained exchanges, discounts and alternatives. +#[derive(Clone, Copy, Default)] +struct ConversionBounds { + decreases: u16, + increases: u16, +} + +fn payment_amounts(pile: &ResourcePile) -> [u16; 9] { + let amounts = [ + pile.food, + pile.wood, + pile.ore, + pile.ideas, + pile.gold, + pile.mood_tokens, + pile.culture_tokens, + pile.captives, + ] + .map(u16::from); + [ + amounts[0], + amounts[1], + amounts[2], + amounts[3], + amounts[4], + amounts[5], + amounts[6], + amounts[7], + amounts.into_iter().sum(), + ] +} + +impl ConversionBounds { + fn include(&mut self, from: &ResourcePile, to: &ResourcePile) { + for (i, (from, to)) in payment_amounts(from) + .into_iter() + .zip(payment_amounts(to)) + .enumerate() + { + if from > to { + self.decreases |= 1 << i; + } + if from < to { + self.increases |= 1 << i; + } + } + } + + fn allows(&self, current: &ResourcePile, available: &[u16; 9], exact: bool) -> bool { + payment_amounts(current) + .into_iter() + .zip(available) + .enumerate() + .all(|(i, (current, &available))| { + (current <= available || self.decreases & (1 << i) != 0) + && (!exact || current >= available || self.increases & (1 << i) != 0) + }) + } +} + +struct ConversionStep<'a> { + from: &'a ResourcePile, + to: &'a ResourcePile, + upper_limit: u8, + bounds: ConversionBounds, +} + fn find_conversion( available: &ResourcePile, current: &ResourcePile, @@ -435,6 +507,55 @@ fn find_conversion( discount_left: u8, may_overpay: bool, exact: bool, +) -> Option { + // Flatten in exactly the old traversal order. Bounds for each suffix are + // built once, instead of rescanning conversions at every search node. + let mut steps: Vec<_> = conversions + .iter() + .enumerate() + .flat_map(|(i, conversion)| { + let upper_limit = match conversion.payment_conversion_type { + PaymentConversionType::Unlimited => u8::MAX, + PaymentConversionType::MayOverpay(i) | PaymentConversionType::MayNotOverpay(i) => i, + }; + conversion + .from + .iter() + .skip(if i == 0 { skip_from } else { 0 }) + .map(move |from| ConversionStep { + from, + to: &conversion.to, + upper_limit, + bounds: ConversionBounds::default(), + }) + }) + .collect(); + let mut bounds = ConversionBounds::default(); + for step in steps.iter_mut().rev() { + if step.upper_limit > 0 { + bounds.include(step.from, step.to); + } + step.bounds = bounds; + } + find_payment_steps( + available, + &payment_amounts(available), + current, + &steps, + discount_left, + may_overpay, + exact, + ) +} + +fn find_payment_steps( + available: &ResourcePile, + available_amounts: &[u16; 9], + current: &ResourcePile, + steps: &[ConversionStep<'_>], + discount_left: u8, + may_overpay: bool, + exact: bool, ) -> Option { if (if exact { available == current @@ -444,73 +565,49 @@ fn find_conversion( { return Some(current.clone()); } - - if conversions.is_empty() { + let (step, rest) = steps.split_first()?; + if !step.bounds.allows(current, available_amounts, exact) { return None; } - let conversion = &conversions[0]; - if skip_from >= conversion.from.len() { - return find_conversion( - available, - current, - &conversions[1..], - 0, - discount_left, - may_overpay, - exact, - ); - } - let from = &conversion.from[skip_from]; - let upper_limit = match conversion.payment_conversion_type { - PaymentConversionType::Unlimited => u8::MAX, - PaymentConversionType::MayOverpay(i) | PaymentConversionType::MayNotOverpay(i) => i, - }; - - for amount in 1..=upper_limit { - if !current.has_at_least_times(from, amount) - || (conversion.to.is_empty() && amount > discount_left) + for amount in 1..=step.upper_limit { + if !current.has_at_least_times(step.from, amount) + || (step.to.is_empty() && amount > discount_left) { - return find_conversion( - available, - current, - conversions, - skip_from + 1, - discount_left, - may_overpay, - exact, - ); + break; } - - let mut current = current.clone(); + let mut next = current.clone(); for _ in 0..amount { - current -= from.clone(); - current += conversion.to.clone(); + next -= step.from.clone(); + next += step.to.clone(); } - let new_discount_left = if conversion.to.is_empty() { + let new_discount_left = if step.to.is_empty() { discount_left - amount } else { discount_left }; - - let can = find_conversion( + if let Some(payment) = find_payment_steps( available, - ¤t, - conversions, - skip_from + 1, + available_amounts, + &next, + rest, new_discount_left, may_overpay, exact, - ); - if can.is_some() { - return can; + ) { + return Some(payment); } } - // A usable conversion can still lead to an unaffordable payment. Try the - // remaining alternatives against the original cost before giving up. - find_conversion( - available, current, conversions, skip_from + 1, - discount_left, may_overpay, exact, + // A usable conversion can still lead to an unaffordable payment. Keep the + // original cost available to the remaining conversions as well. + find_payment_steps( + available, + available_amounts, + current, + rest, + discount_left, + may_overpay, + exact, ) } @@ -953,3 +1050,7 @@ impl CustomCost { } } } + +#[cfg(test)] +#[path = "payment_search_tests.rs"] +mod search_tests; diff --git a/server/src/payment_search_tests.rs b/server/src/payment_search_tests.rs new file mode 100644 index 00000000..7210622a --- /dev/null +++ b/server/src/payment_search_tests.rs @@ -0,0 +1,260 @@ +//! Differential regression for the search pruning. Keep the original exhaustive +//! traversal here as a small-input oracle, independent of bounds/flattening. +use super::*; + +fn exhaustive_conversion( + available: &ResourcePile, + current: &ResourcePile, + conversions: &[&PaymentConversion], + skip_from: usize, + discount_left: u8, + may_overpay: bool, + exact: bool, +) -> Option { + if (if exact { + available == current + } else { + available.has_at_least(current) + }) && (discount_left == 0 || may_overpay) + { + return Some(current.clone()); + } + + if conversions.is_empty() { + return None; + } + let conversion = &conversions[0]; + if skip_from >= conversion.from.len() { + return exhaustive_conversion( + available, + current, + &conversions[1..], + 0, + discount_left, + may_overpay, + exact, + ); + } + let from = &conversion.from[skip_from]; + + let upper_limit = match conversion.payment_conversion_type { + PaymentConversionType::Unlimited => u8::MAX, + PaymentConversionType::MayOverpay(i) | PaymentConversionType::MayNotOverpay(i) => i, + }; + + for amount in 1..=upper_limit { + if !current.has_at_least_times(from, amount) + || (conversion.to.is_empty() && amount > discount_left) + { + return exhaustive_conversion( + available, + current, + conversions, + skip_from + 1, + discount_left, + may_overpay, + exact, + ); + } + + let mut current = current.clone(); + for _ in 0..amount { + current -= from.clone(); + current += conversion.to.clone(); + } + let new_discount_left = if conversion.to.is_empty() { + discount_left - amount + } else { + discount_left + }; + + let can = exhaustive_conversion( + available, + ¤t, + conversions, + skip_from + 1, + new_discount_left, + may_overpay, + exact, + ); + if can.is_some() { + return can; + } + } + // A usable conversion can still lead to an unaffordable payment. Try the + // remaining alternatives against the original cost before giving up. + exhaustive_conversion( + available, + current, + conversions, + skip_from + 1, + discount_left, + may_overpay, + exact, + ) +} + +#[test] +fn pruning_preserves_exact_and_affordable_payments() { + let gold = PaymentConversion::resource_options( + base_resources(), + ResourcePile::gold(1), + PaymentConversionType::Unlimited, + ); + let mut architecture_from = base_resources(); + architecture_from.extend([ResourcePile::culture_tokens(1), ResourcePile::gold(1)]); + let architecture = PaymentConversion::resource_options( + architecture_from, + ResourcePile::mood_tokens(1), + PaymentConversionType::Unlimited, + ); + let mut scenarios = vec![ + ( + ResourcePile::new(2, 1, 0, 0, 0, 0, 1), + vec![gold.clone(), architecture], + 0, + false, + ), + // Expanding, chained and reversed-order exchanges must not be mistaken + // for fixed-total payments or currently unaffordable final payments. + ( + ResourcePile::food(2), + vec![ + PaymentConversion::unlimited(ResourcePile::wood(1), ResourcePile::gold(1)), + PaymentConversion::unlimited(ResourcePile::food(1), ResourcePile::wood(2)), + ], + 0, + false, + ), + ( + ResourcePile::food(2) + ResourcePile::wood(2), + vec![ + PaymentConversion::limited( + ResourcePile::food(1) + ResourcePile::wood(1), + ResourcePile::mood_tokens(1), + 1, + ), + PaymentConversion::unlimited(ResourcePile::mood_tokens(1), ResourcePile::gold(2)), + ], + 0, + false, + ), + ( + ResourcePile::culture_tokens(2) + ResourcePile::mood_tokens(1), + vec![ + PaymentConversion::unlimited( + ResourcePile::mood_tokens(1), + ResourcePile::culture_tokens(1), + ), + PaymentConversion::unlimited( + ResourcePile::culture_tokens(1), + ResourcePile::mood_tokens(1), + ), + ], + 0, + false, + ), + ( + ResourcePile::culture_tokens(2) + ResourcePile::mood_tokens(1), + vec![PaymentConversion::resource_options( + vec![ + ResourcePile::culture_tokens(1), + ResourcePile::mood_tokens(1), + ], + ResourcePile::captives(1), + PaymentConversionType::Unlimited, + )], + 0, + false, + ), + ]; + for (discount, may_overpay) in [ + (PaymentConversionType::MayNotOverpay(1), false), + (PaymentConversionType::MayOverpay(1), true), + ] { + scenarios.push(( + ResourcePile::food(2) + ResourcePile::wood(1), + vec![ + gold.clone(), + PaymentConversion::resource_options( + base_resources(), + ResourcePile::empty(), + discount, + ), + ], + 1, + may_overpay, + )); + } + for (current, conversions, discount_left, may_overpay) in scenarios { + for order in conversions.iter().permutations(conversions.len()) { + // Exhaust every small stock/payment across all six relevant types. + for mut index in 0..3_usize.pow(6) { + let mut pile = ResourcePile::empty(); + for resource in [ + ResourceType::Food, + ResourceType::Wood, + ResourceType::Gold, + ResourceType::MoodTokens, + ResourceType::CultureTokens, + ResourceType::Captives, + ] { + *pile.get_mut(&resource) = (index % 3) as u8; + index /= 3; + } + for exact in [false, true] { + for skip_from in [0, 1] { + assert_eq!( + find_conversion( + &pile, + ¤t, + &order, + skip_from, + discount_left, + may_overpay, + exact + ), + exhaustive_conversion( + &pile, + ¤t, + &order, + skip_from, + discount_left, + may_overpay, + exact + ), + "current={current:?}, available={pile:?}, conversions={order:?}, exact={exact}, skip={skip_from}" + ); + } + } + } + } + } +} + +#[test] +fn alternative_costs_keep_their_own_payment_totals() { + let mut cost = PaymentOptions::new( + ResourcePile::food(2), + vec![PaymentConversion::unlimited( + ResourcePile::food(1), + ResourcePile::gold(1), + )], + vec![], + check_event_origin(), + ); + cost.alternatives.push(ResourcePile::food(1)); + cost.alternatives.push(ResourcePile::culture_tokens(3)); + for payment in [ + ResourcePile::food(2), + ResourcePile::food(1), + ResourcePile::gold(2), + ResourcePile::gold(1), + ResourcePile::culture_tokens(3), + ] { + assert!(cost.is_valid_payment(&payment), "{payment}"); + assert_eq!(cost.first_valid_payment(&payment), Some(payment)); + } + assert!(!cost.is_valid_payment(&ResourcePile::culture_tokens(2))); + assert!(!cost.is_valid_payment(&ResourcePile::gold(3))); +} diff --git a/server/src/replay.rs b/server/src/replay.rs index 47525493..ef247681 100644 --- a/server/src/replay.rs +++ b/server/src/replay.rs @@ -17,6 +17,12 @@ pub struct ReplayGameData { players: Vec, #[serde(default)] dropped_players: Vec, + #[serde( + default, + skip_serializing_if = "Vec::is_empty", + deserialize_with = "crate::timing::deserialize_counters" + )] + time_increments: Vec, } #[derive(Serialize, Deserialize, PartialEq)] @@ -142,6 +148,9 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { game.players[player.id].settings = player.settings; } game.dropped_players = data.dropped_players; + // Clock totals belong to the live session, not the historical position. + // Reconstructing any cursor must neither earn nor revoke existing credits. + game.time_increments = data.time_increments; if full_replay { game.finish_after_drop(); } diff --git a/server/src/tactics_card.rs b/server/src/tactics_card.rs index 7de7d49a..dff9bb99 100644 --- a/server/src/tactics_card.rs +++ b/server/src/tactics_card.rs @@ -3,10 +3,10 @@ use crate::ability_initializer::{ }; use crate::action_card; use crate::action_card::ActionCard; -use crate::advance::AdvanceBuilder; +use crate::advance::{Advance, AdvanceBuilder}; use crate::card::{HandCard, HandCardLocation}; use crate::combat::{Combat, CombatModifier, get_combat_strength, update_combat_strength}; -use crate::combat_listeners::{CombatRoundEnd, CombatRoundStart, CombatStrength}; +use crate::combat_listeners::{CombatEventPhase, CombatRoundEnd, CombatRoundStart, CombatStrength}; use crate::content::persistent_events::HandCardsRequest; use crate::events::{EventOrigin, EventPlayer}; use crate::game::Game; @@ -102,7 +102,58 @@ impl CombatRole { } } -type TacticsChecker = Arc bool + Sync + Send>; +#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum OpponentTacticsStatus { + Played, + Pending, + None, +} + +pub(crate) fn opponent_tactics_status( + game: &Game, + player: usize, + round: &CombatRoundStart, +) -> OpponentTacticsStatus { + let combat = &round.combat; + let opponent = combat.opponent(player); + // Only the presence of a face-down card is public. Some(0) in a + // filtered view counts too; never inspect its identity or the hand. + if get_combat_strength(opponent, round).tactics_card.is_some() { + return OpponentTacticsStatus::Played; + } + if !game.player(opponent).is_human() { + // Ordinary Barbarians/Pirates cannot play tactics. A card supplied + // by Viriatus's earlier Loyalty phase is handled above. + return OpponentTacticsStatus::None; + } + if get_combat_strength(opponent, round).deny_tactics_card + || !game.player(opponent).can_use_advance(Advance::Tactics) + || (opponent == combat.defender() + && combat.first_round() + && combat.modifiers.contains(&CombatModifier::TrojanHorse)) + { + return OpponentTacticsStatus::None; + } + let pending = match round.phase { + // Loyalty happens before either participant's normal choice, even + // when the Barbarians receiving Scouts are the defender. + CombatEventPhase::AllowTacticsCard | CombatEventPhase::Loyalty => true, + // The attacker chooses first, face down. The defender may still + // play a card, but a defending Scout cannot target a passed attacker. + CombatEventPhase::Default => combat.role(player) == CombatRole::Attacker, + _ => false, + }; + if pending { + OpponentTacticsStatus::Pending + } else { + OpponentTacticsStatus::None + } +} + +// Check the live round supplied by the event listener, not game.current_event(): +// its saved snapshot can predate a choice just made by the other participant. +type TacticsChecker = Arc bool + Sync + Send>; #[derive(Clone)] pub struct TacticsCard { @@ -181,7 +232,7 @@ impl TacticsCardBuilder { pub(crate) fn checker( mut self, - checker: impl Fn(usize, &Game, &Combat) -> bool + Clone + 'static + Sync + Send, + checker: impl Fn(usize, &Game, &CombatRoundStart) -> bool + Clone + 'static + Sync + Send, ) -> Self { self.checker = Some(Arc::new(checker)); self @@ -320,7 +371,7 @@ pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder { return None; } - let cards = available_tactics_cards(game, p, &s.combat); + let cards = available_tactics_cards(game, p, s); if cards.is_empty() { return None; } @@ -349,12 +400,7 @@ pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder { panic!("Expected ActionCard, got {:?}", s.choice[0]); }; assert!( - can_play_tactics_card( - game, - player, - game.cache.get_action_card(card), - &r.combat - ), + can_play_tactics_card(game, player, game.cache.get_action_card(card), r), "Tactics card requirements are not met" ); update_combat_strength(game, player, r, move |_game, _c, s, _role| { @@ -372,12 +418,12 @@ pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder { ) } -fn available_tactics_cards(game: &Game, player: usize, combat: &Combat) -> Vec { +fn available_tactics_cards(game: &Game, player: usize, round: &CombatRoundStart) -> Vec { game.players[player] .action_cards .iter() .map(|id| game.cache.get_action_card(*id)) - .filter(|a| can_play_tactics_card(game, player, a, combat)) + .filter(|a| can_play_tactics_card(game, player, a, round)) .map(|a| HandCard::ActionCard(a.id)) .collect() } @@ -386,8 +432,9 @@ pub(crate) fn can_play_tactics_card( game: &Game, player: usize, card: &ActionCard, - combat: &Combat, + round: &CombatRoundStart, ) -> bool { + let combat = &round.combat; match &card.tactics_card { Some(card) => { let position_met = card @@ -417,10 +464,7 @@ pub(crate) fn can_play_tactics_card( CombatLocation::Land => combat.is_land_battle(game), }); - let checker_met = card - .checker - .as_ref() - .is_none_or(|c| c(player, game, combat)); + let checker_met = card.checker.as_ref().is_none_or(|c| c(player, game, round)); position_met && fighter_met && location_met && checker_met } diff --git a/server/src/timing.rs b/server/src/timing.rs new file mode 100644 index 00000000..5ba666e6 --- /dev/null +++ b/server/src/timing.rs @@ -0,0 +1,80 @@ +//! Platform clock credits, separate from the turn-local undo cursor and RNG. +//! +//! Only the live, saved-action boundary (`board_history`) calls `execute`. +//! Rules previews, queue validation and historical replay use the lower-level +//! executor and cannot earn credits. Automatic responses and resumed plans pass +//! through the same boundary, attributed to their own actor, not the submitter. +use crate::action::{Action, try_execute_action}; +use crate::game::{Game, GameContext, GameState}; +use serde::{Deserialize, Deserializer}; + +/// The protocol requires JavaScript-safe integers, even for very long games. +const MAX_INCREMENT: u64 = (1_u64 << 53) - 1; + +/// Cumulative credits in platform seat order, including dropped human players, +/// never NPCs. Missing counters in older saves mean zero, not historical credit. +#[must_use] +pub fn time_increments(game: &Game) -> Vec { + game.players + .iter() + .filter(|player| player.is_human()) + .map(|player| game.time_increments.get(player.index).copied().unwrap_or(0)) + .collect() +} + +pub(crate) fn deserialize_counters<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let counters = Vec::::deserialize(deserializer)?; + if counters.iter().any(|&value| value > MAX_INCREMENT) { + return Err(serde::de::Error::custom( + "time increment is not a safe integer", + )); + } + Ok(counters) +} + +pub(crate) fn execute(mut game: Game, action: Action, actor: usize) -> Result { + let eligible = game.context == GameContext::Play + && !matches!( + action, + Action::Undo + | Action::Redo + | Action::StartTurn + | Action::QueueChoice { .. } + | Action::QueueMoves { .. } + ); + let before_player = game.active_player(); + // Committing a simultaneous draft seat relinquishes control of that seat. + // Revisions must not credit again, including when loading a pre-hook save. + let draft_commit = game + .civilization_draft + .as_ref() + .map(|draft| draft.ready.get(actor).is_some_and(|ready| !ready)); + game.timing_revealed = false; + let mut next = try_execute_action(game, action, actor)?; + let revealed = std::mem::take(&mut next.timing_revealed); + let boundary = draft_commit.unwrap_or_else(|| { + revealed || next.active_player() != before_player || next.state == GameState::Finished + }); + if eligible + && boundary + && next + .players + .get(actor) + .is_some_and(|player| player.is_human()) + { + // Human seats precede NPCs and never disappear, including after a drop. + let humans = next + .players + .iter() + .filter(|player| player.is_human()) + .count(); + next.time_increments.resize(humans, 0); + if let Some(counter) = next.time_increments.get_mut(actor) { + *counter = counter.saturating_add(1).min(MAX_INCREMENT); + } + } + Ok(next) +} diff --git a/server/src/undo.rs b/server/src/undo.rs index 5ed0be53..9c842694 100644 --- a/server/src/undo.rs +++ b/server/src/undo.rs @@ -5,7 +5,14 @@ use crate::movement::execute_movement_action; use json_patch::{PatchOperation, patch}; use serde_json::Value; -const IGNORE_PATHS: [&str; 5] = ["/log/", "/log_index", "/early_choices", "/early_choice_update", "/action_plan"]; +const IGNORE_PATHS: [&str; 6] = [ + "/log/", + "/log_index", + "/early_choices", + "/early_choice_update", + "/action_plan", + "/time_increments", +]; pub(crate) fn clean_patch(mut patch: Vec) -> Vec { patch.retain(|op| { diff --git a/server/src/unit.rs b/server/src/unit.rs index 1548c57c..7fb89a3e 100644 --- a/server/src/unit.rs +++ b/server/src/unit.rs @@ -761,7 +761,7 @@ fn save_carried_units(game: &mut Game, player: usize, pos: Position) { return; } - game.information_revealed(); // strange bug when redoing this + game.lock_undo(); // redo workaround, not a hidden-information reveal let mut embark = vec![]; diff --git a/server/src/web_view/combat_estimate.rs b/server/src/web_view/combat_estimate.rs index b476cefc..816be727 100644 --- a/server/src/web_view/combat_estimate.rs +++ b/server/src/web_view/combat_estimate.rs @@ -79,6 +79,40 @@ pub(super) fn estimate(game: &Game, seat: usize, input: &Value) -> Result