diff --git a/server/src/action.rs b/server/src/action.rs index b79ef607..c31538d3 100644 --- a/server/src/action.rs +++ b/server/src/action.rs @@ -37,6 +37,7 @@ pub enum Action { Playing(PlayingAction), Movement(MovementAction), Response(EventResponse), + QueueChoice { key: String, response: Option }, Undo, Redo, #[serde(alias = "Setup")] @@ -73,6 +74,11 @@ pub fn try_execute_action( action: Action, player_index: usize, ) -> Result { + game.early_choice_update = false; + if let Action::QueueChoice { key, response } = &action { + crate::early_choices::save(&mut game, player_index, key, response.clone())?; + return Ok(game); + } if game.civilization_draft.is_some() { crate::game_setup::execute_draft_choice(&mut game, player_index, &action)?; return Ok(game); diff --git a/server/src/board_history.rs b/server/src/board_history.rs index 8fbb8163..8c5048d6 100644 --- a/server/src/board_history.rs +++ b/server/src/board_history.rs @@ -158,11 +158,27 @@ fn title(action: &Action) -> String { } pub fn execute(game: Game, action: Action, player: usize) -> Result { + if matches!(action, Action::QueueChoice { .. }) { + return try_execute_action(game, action, player); + } let undo = matches!(action, Action::Undo); let mut game = execute_one(game, action, player)?; + crate::early_choices::prune_objectives(&mut 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 && auto_keep_cities(&game) { + while !undo && 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)?; + crate::early_choices::prune_objectives(&mut game); + continue; + } + if auto_keep_government(&game) { + let player = game.active_player(); + game = execute_one(game, Action::Response(crate::content::persistent_events::EventResponse::Payment(vec![crate::resource_pile::ResourcePile::empty()])), player)?; + continue; + } + if !auto_keep_cities(&game) { break; } let player = game.active_player(); game = execute_one( game, @@ -175,6 +191,16 @@ pub fn execute(game: Game, action: Action, player: usize) -> Result bool { + use crate::content::persistent_events::{PersistentEventRequest, PersistentEventType}; + game.player(game.active_player()).settings.keep_government == Some(true) + && game.events.last().is_some_and(|event| { + matches!(event.event_type, PersistentEventType::StatusPhase(crate::status_phase::StatusPhaseState::ChangeGovernmentType(_))) + && event.player.handler.as_ref().is_some_and(|h| matches!(&h.request, + PersistentEventRequest::Payment(rs) if rs.len() == 1 && rs[0].optional && rs[0].name == "Pay to change government")) + }) +} + fn auto_keep_cities(game: &Game) -> bool { use crate::content::persistent_events::{PersistentEventRequest, PersistentEventType}; let Some(event) = game.events.last() else { diff --git a/server/src/content/persistent_events.rs b/server/src/content/persistent_events.rs index 33a46ec0..1e974c29 100644 --- a/server/src/content/persistent_events.rs +++ b/server/src/content/persistent_events.rs @@ -452,6 +452,7 @@ where (params.next_player)(&mut value); } } + crate::early_choices::expire_current_event(game); game.events.pop(); present_instant_objective_cards(game); diff --git a/server/src/early_choices.rs b/server/src/early_choices.rs new file mode 100644 index 00000000..5c3cae79 --- /dev/null +++ b/server/src/early_choices.rs @@ -0,0 +1,214 @@ +//! Private, editable commitments. They never change resolution order or reserve a +//! shared card. Only an ordinary, currently legal response can consume a plan. +use crate::card::HandCard; +use crate::content::persistent_events::{EventResponse, PersistentEventRequest, PersistentEventType}; +use crate::game::Game; +use crate::resource_pile::ResourcePile; +use crate::status_phase::StatusPhaseState; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SavedChoice { + pub player: usize, + pub key: String, + pub response: EventResponse, +} + +#[derive(Serialize)] +pub struct OptionChoice { + pub label: String, + pub description: String, + pub response: EventResponse, +} + +#[derive(Serialize)] +pub struct Offer { + pub key: String, + pub title: String, + pub options: Vec, + pub selected: Option, +} + +fn scope(game: &Game, index: usize) -> Option { + let name = match &game.events.get(index)?.event_type { + PersistentEventType::StatusPhase(phase) => format!("status:{phase:?}"), + PersistentEventType::Incident(i) => format!("person:{}:{}", i.incident_id, i.active_player), + _ => return None, + }; + Some(format!("{}:{}:{index}:{name}/", game.age, game.round)) +} + +fn option(label: impl Into, response: EventResponse) -> OptionChoice { + OptionChoice { label: label.into(), description: String::new(), response } +} + +fn objective_key(game: &Game, name: &str) -> String { + format!("{}:objective:{name}", game.age) +} + +fn objective_offers(game: &Game, player: usize) -> Vec { + let p = game.player(player); + let mut names: Vec<_> = p.objective_cards.iter().filter(|id| **id != 0).flat_map(|id| + crate::objective_card::status_phase_completable(game, p, *id)).collect(); + names.sort(); names.dedup(); + names.into_iter().map(|name| { + let key = objective_key(game, &name); + let mut options = vec![option("Skip", EventResponse::SelectHandCards(vec![]))]; + options.extend(p.objective_cards.iter().filter(|id| **id != 0).filter(|id| + crate::objective_card::status_phase_completable(game, p, **id).contains(&name)) + .map(|id| option(game.cache.get_objective_card(*id).name(), + EventResponse::SelectHandCards(vec![HandCard::ObjectiveCard(*id)])))); + let selected = game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone()); + Offer {key, title: name, options, selected} + }).collect() +} + +pub fn prune_objectives(game: &mut Game) { + let invalid: Vec<_> = game.early_choices.iter().enumerate().filter_map(|(index, choice)| { + if !choice.key.contains(":objective:") { return None; } + let valid = objective_offers(game, choice.player).iter().any(|o| o.key == choice.key + && o.options.iter().any(|v| v.response == choice.response)); + (!valid).then_some(index) + }).collect(); + for index in invalid.into_iter().rev() { game.early_choices.remove(index); } +} + +/// Expose only the current step, never future cards, random results, or another +/// player's hand. Earlier players may still change the available options. +pub fn offers(game: &Game, player: usize) -> Vec { + if player >= game.players.len() || !game.player(player).is_human() + || game.dropped_players.contains(&player) || game.civilization_draft.is_some() || matches!(game.state, crate::game::GameState::Finished) { + return vec![]; + } + if game.events.is_empty() { return objective_offers(game, player); } + let Some(index) = game.events.iter().rposition(|e| matches!(e.event_type, + PersistentEventType::StatusPhase(_) | PersistentEventType::Incident(_))) else { return vec![]; }; + let event = &game.events[index]; + let first = if matches!(event.event_type, PersistentEventType::StatusPhase(StatusPhaseState::ChangeGovernmentType(_))) { + let players: Vec<_> = game.human_players_sorted(game.starting_player_index).iter().map(|i| game.player(*i)).collect(); + if crate::status_phase::player_that_chooses_next_first_player(&players) == player { + let key = format!("{}:first", game.age); + vec![Offer { selected: game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone()), key, + title: "Choose first player".into(), options: game.human_players_sorted(game.starting_player_index).iter().map(|i| option(game.player(*i).civilization.name.clone(), EventResponse::SelectPlayer(*i))).collect() }] + } else { vec![] } + } else { vec![] }; + if event.players_used.contains(&player) { return first; } + // Nested research/event reactions must finish before early status choices are + // offered. Objective selection is the only supported nested request. + if game.events[index+1..].iter().any(|e| !matches!(e.event_type, PersistentEventType::SelectObjectives(_))) { + return vec![]; + } + let prefix = scope(game, index).expect("supported event"); + let p = game.player(player); + let mut result: Vec = first; + let mut add = |suffix: &str, title: String, options: Vec| { + if options.is_empty() { return; } + let key = format!("{prefix}{suffix}"); + let selected = game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone()); + result.push(Offer { key, title, options, selected }); + }; + match &event.event_type { + PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance) => { + let mut options: Vec<_> = game.cache.get_advances().values() + .filter(|a| p.can_advance_free(a.advance, game)) + .map(|a| OptionChoice { label: a.name.clone(), description: a.description.clone(), response: EventResponse::SelectAdvance(a.advance) }).collect(); + options.sort_by(|a,b| a.label.cmp(&b.label)); + add("advance", "Free Advance".into(), options); + } + PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => { + let mut options: Vec<_> = p.cities.iter().filter(|c| c.size() == 1) + .map(|c| option(c.position.to_string(), EventResponse::SelectPositions(vec![c.position]))).collect(); + if !options.is_empty() { + options.insert(0, option("Keep all cities", EventResponse::SelectPositions(vec![]))); + add("raze", "Raze city".into(), options); + } + } + PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives) => { + return objective_offers(game, player); + } + PersistentEventType::Incident(i) if !i.consumed && !i.replaced_by_sacrifice && i.selected_player.is_none() + && game.cache.get_incident(i.incident_id).action_card.is_some() => { + // Do not ask before event cancellation, placement or other base + // effects. Once an offer is visible, later players may precommit. + if !event.player.handler.as_ref().is_some_and(|h| matches!(&h.request, + PersistentEventRequest::Payment(rs) if rs.iter().any(|r| r.name == "Pay to gain the Action Card"))) { + return vec![]; + } + let cost = if player == i.active_player { 1 } else { 2 }; + let mut options = vec![option("Pass", EventResponse::Payment(vec![ResourcePile::empty()]))]; + // No inferred gold/captive conversion: a queued purchase spends + // precisely the displayed culture payment, or asks again. + if p.resources.culture_tokens >= cost { + options.push(option(format!("Take if offered · {cost} culture"), EventResponse::Payment(vec![ResourcePile::culture_tokens(cost)]))); + } + add("offer", game.cache.get_incident(i.incident_id).name.clone(), options); + } + _ => {} + } + result +} + +pub fn can_save(game: &Game, player: usize, key: &str, response: Option<&EventResponse>) -> bool { + (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))) +} + +pub fn save(game: &mut Game, player: usize, key: &str, response: Option) -> Result<(), String> { + if !can_save(game, player, key, response.as_ref()) { return Err("This early choice is no longer available".into()); } + game.early_choices.retain(|c| c.player != player || (c.key != key && !matches!((&c.response, &response), + (EventResponse::SelectHandCards(a), Some(EventResponse::SelectHandCards(b))) if !a.is_empty() && a == b && key.contains(":objective:")))); + if let Some(response) = response { game.early_choices.push(SavedChoice { player, key: key.into(), response }); } + // Metadata-only platform update; not a turn, journal entry or undo boundary. + game.early_choice_update = true; + Ok(()) +} + +pub fn expire_current_event(game: &mut Game) { + if game.events.last().is_some_and(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives))) { + let prefix = format!("{}:objective:", game.age); + game.early_choices.retain(|c| !c.key.starts_with(&prefix)); + } + if game.events.last().is_some_and(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)))) { + game.early_choices.retain(|c| c.key != format!("{}:first", game.age)); + } + if let Some(prefix) = scope(game, game.events.len().saturating_sub(1)) { + game.early_choices.retain(|c| !c.key.starts_with(&prefix)); + } +} + +/// Validate against the *real* request, including costs and prerequisites after +/// intervening events. Invalid plans are removed and the normal prompt remains. +pub fn take_ready(game: &mut Game) -> Option { + let player = game.active_player(); + let event = game.events.last()?; + let handler = event.player.handler.as_ref()?; + let (index, suffix) = match &event.event_type { + PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)) => (game.events.len()-1, "first".into()), + PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance) => (game.events.len()-1, "advance".into()), + PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => (game.events.len()-1, "raze".into()), + PersistentEventType::SelectObjectives(i) => { + let index = game.events.iter().rposition(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives)))?; + (index, format!("objective:{}", i.shown_objective.as_ref()?)) + } + PersistentEventType::Incident(_) if matches!(&handler.request, PersistentEventRequest::Payment(rs) + if rs.iter().any(|r| r.name == "Pay to gain the Action Card")) => (game.events.len()-1, "offer".into()), + _ => return None, + }; + let key = if suffix == "first" { format!("{}:first", game.age) } else if let Some(name) = suffix.strip_prefix("objective:") { + objective_key(game, name) + } else { format!("{}{suffix}", scope(game, index)?) }; + let at = game.early_choices.iter().position(|c| c.player == player && c.key == key)?; + let response = &game.early_choices[at].response; + let valid = match (&handler.request, response) { + (PersistentEventRequest::SelectPlayer(r), EventResponse::SelectPlayer(p)) => r.choices.contains(p), + (PersistentEventRequest::SelectAdvance(r), EventResponse::SelectAdvance(a)) => r.choices.contains(a), + (PersistentEventRequest::SelectPositions(r), EventResponse::SelectPositions(v)) => r.needed.contains(&(v.len() as u8)) && v.iter().all(|p| r.choices.contains(p)), + (PersistentEventRequest::SelectHandCards(r), EventResponse::SelectHandCards(v)) => r.needed.contains(&(v.len() as u8)) && v.iter().all(|c| r.choices.contains(c)), + (PersistentEventRequest::Payment(rs), EventResponse::Payment(v)) => rs.len() == 1 && v.len() == 1 + && game.player(player).resources.has_at_least(&v[0]) + && ((rs[0].optional && v[0].is_empty()) || rs[0].cost.is_valid_payment(&v[0])), + _ => false, + }; + let choice = game.early_choices.remove(at); + valid.then_some(choice.response) +} diff --git a/server/src/game.rs b/server/src/game.rs index 181dfece..ee723ae9 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -134,6 +134,8 @@ pub struct Game { pub version: u16, // JSON schema version pub state: GameState, pub events: Vec, + pub early_choices: Vec, + pub early_choice_update: bool, // in turn order starting from starting_player_index and wrapping around pub players: Vec, pub map: Map, diff --git a/server/src/game_api.rs b/server/src/game_api.rs index 1a68fa1a..5e4de54c 100644 --- a/server/src/game_api.rs +++ b/server/src/game_api.rs @@ -146,6 +146,7 @@ pub fn civilizations(game: Game) -> Vec { #[must_use] pub fn strip_secret(mut game: Game, player_index: Option) -> Game { + 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) { diff --git a/server/src/game_api_wrapper.rs b/server/src/game_api_wrapper.rs index ff793e1b..ad8a54fd 100644 --- a/server/src/game_api_wrapper.rs +++ b/server/src/game_api_wrapper.rs @@ -62,6 +62,7 @@ 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; } Ok(from_game(game)) } @@ -177,6 +178,11 @@ pub fn current_player(game: String) -> JsValue { #[wasm_bindgen(js_name = "canMoveOutOfTurn")] pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) -> bool { let game = get_game(data); + if let Some(raw) = move_data.as_string() + && let Ok(crate::action::Action::QueueChoice { key, response }) = serde_json::from_str(&raw) + { + return crate::early_choices::can_save(&game, player, &key, response.as_ref()); + } let Some(draft) = &game.civilization_draft else { return false; }; @@ -195,7 +201,8 @@ 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 { - get_game(data) + let game = get_game(data); + game.early_choice_update || game .civilization_draft .is_some_and(|draft| draft.live_update) } diff --git a/server/src/game_data.rs b/server/src/game_data.rs index 78f2f4ee..eead5e97 100644 --- a/server/src/game_data.rs +++ b/server/src/game_data.rs @@ -44,6 +44,10 @@ pub struct GameData { #[serde(default)] #[serde(skip_serializing_if = "Vec::is_empty")] events: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + early_choices: Vec, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + early_choice_update: bool, players: Vec, map: MapData, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -113,6 +117,8 @@ pub struct GameData { #[must_use] pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { let mut game = Game { + early_choices: data.early_choices, + early_choice_update: data.early_choice_update, context, cache, options: data.options, @@ -173,6 +179,8 @@ pub fn data(game: Game) -> GameData { version: game.version, state: game.state, events: game.events, + early_choices: game.early_choices, + early_choice_update: game.early_choice_update, players: game.players.into_iter().map(player_data).collect(), map: game.map.data(), civilization_draft: game.civilization_draft, @@ -210,6 +218,8 @@ pub fn cloned_data(game: &Game) -> GameData { version: game.version, state: game.state.clone(), events: game.events.clone(), + early_choices: game.early_choices.clone(), + early_choice_update: game.early_choice_update, players: game.players.iter().map(cloned_player_data).collect(), map: game.map.cloned_data(), civilization_draft: game.civilization_draft.clone(), diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs index 8f980aa9..3c4cdfd6 100644 --- a/server/src/game_setup.rs +++ b/server/src/game_setup.rs @@ -186,6 +186,8 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game { .shuffled(&mut rng); let all = &cache.get_abilities().clone(); let mut game = Game { + early_choices: vec![], + early_choice_update: false, seed: setup.seed.clone(), context: GameContext::Play, version: JSON_SCHEMA_VERSION, diff --git a/server/src/lib.rs b/server/src/lib.rs index 936495a6..7f4cc8a3 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -13,6 +13,7 @@ extern crate core; pub mod ability_initializer; pub mod action; +pub mod early_choices; pub mod action_card; mod action_cost; pub mod advance; diff --git a/server/src/log.rs b/server/src/log.rs index b6ddee62..620ceb03 100644 --- a/server/src/log.rs +++ b/server/src/log.rs @@ -457,7 +457,7 @@ fn action_origin(a: &Action, player: &Player) -> Option { Action::Movement(_) => Some(move_event_origin()), Action::Undo => panic!("Unexpected undo in log"), Action::Redo => panic!("Unexpected redo in log"), - Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None, + Action::QueueChoice { .. } | Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None, } } diff --git a/server/src/move_summary.rs b/server/src/move_summary.rs index 51b201d9..bc19946f 100644 --- a/server/src/move_summary.rs +++ b/server/src/move_summary.rs @@ -171,6 +171,7 @@ fn fallback(game: &Game, entry: &ActionLogAction) -> String { }, Action::Movement(_) => "Moved units".into(), Action::ChooseCivilization(name) => format!("Chose {name}"), + Action::QueueChoice { .. } => "Queued a choice".into(), Action::StartTurn => "Started turn".into(), Action::Response(_) => "Completed a decision".into(), Action::Undo => "Undid a move".into(), diff --git a/server/src/player.rs b/server/src/player.rs index 3fa45223..b59925f4 100644 --- a/server/src/player.rs +++ b/server/src/player.rs @@ -49,11 +49,13 @@ pub struct PlayerSettings { // None distinguishes an old save from an explicit opt-out. #[serde(default, skip_serializing_if = "Option::is_none")] pub skip_raze_city: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keep_government: Option, } impl PlayerSettings { pub fn is_empty(&self) -> bool { - self.skip_raze_city.is_none() + self.skip_raze_city.is_none() && self.keep_government.is_none() } } diff --git a/server/src/status_phase.rs b/server/src/status_phase.rs index 6b0114eb..f3c01f62 100644 --- a/server/src/status_phase.rs +++ b/server/src/status_phase.rs @@ -505,7 +505,7 @@ pub(crate) fn determine_first_player() -> Ability { .build() } -fn player_that_chooses_next_first_player(players: &[&Player]) -> usize { +pub(crate) fn player_that_chooses_next_first_player(players: &[&Player]) -> usize { players .iter() .find(|p| p.wonders_owned.contains(Wonder::GreatLighthouse)) diff --git a/server/src/undo.rs b/server/src/undo.rs index 4372a9a5..e8c88179 100644 --- a/server/src/undo.rs +++ b/server/src/undo.rs @@ -5,7 +5,7 @@ use crate::movement::execute_movement_action; use json_patch::{PatchOperation, patch}; use serde_json::Value; -const IGNORE_PATHS: [&str; 2] = ["/log/", "/log_index"]; +const IGNORE_PATHS: [&str; 4] = ["/log/", "/log_index", "/early_choices", "/early_choice_update"]; pub(crate) fn clean_patch(mut patch: Vec) -> Vec { patch.retain(|op| { diff --git a/server/src/web_view.rs b/server/src/web_view.rs index 67af9c7a..1319f68b 100644 --- a/server/src/web_view.rs +++ b/server/src/web_view.rs @@ -323,6 +323,11 @@ pub fn view(game: &Game, seat: Option) -> Value { "shogunateDraft":p.has_special_advance(crate::special_advance::SpecialAdvance::Shogunate)&&p.can_use_advance(Advance::Draft)&&!p.event_info.contains_key("Shogunate Draft"), "canActivate":city.can_activate(), "activationMood":after_activation.mood_state,"activationCapacity":after_activation.mood_modified_size(p)}) }).collect::>(); + let early_offers = if seat != active || game.events.is_empty() { crate::early_choices::offers(game, seat) } else { vec![] }; + let early_advance = early_offers.iter().find(|o| o.key.ends_with("/advance")); + let early_advance_choices: Vec<_> = early_advance.into_iter().flat_map(|o| &o.options).filter_map(|o| { + if let EventResponse::SelectAdvance(a) = o.response { Some(a) } else { None } + }).collect(); let advance_choice = if seat == active { game.current_event_handler() .and_then(|handler| match &handler.request { @@ -331,10 +336,12 @@ pub fn view(game: &Game, seat: Option) -> Value { } _ => None, }) + } else if early_advance.is_some() { + Some((&early_advance_choices, "free")) } else { None }; - let research_uses_event_marker = advance_choice.is_none() + let research_uses_event_marker = early_advance.is_some() || advance_choice.is_none() || game .current_event_handler() .is_some_and(|handler| decisions::advance_uses_event_marker(game, handler)); @@ -357,6 +364,7 @@ pub fn view(game: &Game, seat: Option) -> Value { else if !p.can_advance_free(*advance, game) { Some("Conflicts with your current advances".to_string()) } else if payment.is_none() { Some("Not enough resources".to_string()) } else { None }; let action = if reason.is_some() { None } + else if let Some(offer) = early_advance { Some(Action::QueueChoice { key: offer.key.clone(), response: Some(EventResponse::SelectAdvance(*advance)) }) } else if advance_choice.is_some() { Some(Action::Response(EventResponse::SelectAdvance(*advance))) } else { payment.clone().map(|payment| Action::Playing(PlayingAction::Advance(AdvanceAction::new(*advance, payment)))) }; let mut item = advance_description(game, *advance); @@ -414,6 +422,7 @@ pub fn view(game: &Game, seat: Option) -> Value { result["regions"] = json!(regions); result["unavailableSpecialActions"] = json!(special_actions.iter().filter(|a| !a["reason"].is_null()).collect::>()); result["activeEffects"] = json!(active_effects); + result["earlyChoices"] = json!(early_offers); result } diff --git a/web-client/bgs-settings.json b/web-client/bgs-settings.json index 96b46c05..721908f5 100644 --- a/web-client/bgs-settings.json +++ b/web-client/bgs-settings.json @@ -4,5 +4,11 @@ "label": "Skip end-of-age razing (keep all cities)", "type": "checkbox", "default": false + }, + { + "name": "keepGovernment", + "label": "Always keep current government", + "type": "checkbox", + "default": false } ] diff --git a/web-client/index.html b/web-client/index.html index 9a5e3883..e1b8f50e 100644 --- a/web-client/index.html +++ b/web-client/index.html @@ -11,8 +11,10 @@ height: 100%; background: #f7f3e8; } + body { display: flex; flex-direction: column; } #preview-bar { - height: 35px; + min-height: 35px; + flex-wrap: wrap; background: #233d35; color: #d8decb; font: 10px system-ui; @@ -56,7 +58,8 @@ iframe { display: block; width: 100%; - height: calc(100% - 35px); + flex: 1; + min-height: 0; border: 0; } #host-error { @@ -100,8 +103,10 @@ > Test sounds + Connecting to local game… + diff --git a/web-client/package-lock.json b/web-client/package-lock.json index ec976459..6696c8d8 100644 --- a/web-client/package-lock.json +++ b/web-client/package-lock.json @@ -1,12 +1,12 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.166", + "version": "0.1.167", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.166", + "version": "0.1.167", "dependencies": { "@boardgamers/protocol": "0.9.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index e9b3a0ac..1618363d 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.166", + "version": "0.1.167", "private": true, "type": "module", "scripts": { diff --git a/web-client/scripts/preview-api.ts b/web-client/scripts/preview-api.ts index 5294de2f..1485b170 100644 --- a/web-client/scripts/preview-api.ts +++ b/web-client/scripts/preview-api.ts @@ -2,6 +2,7 @@ import { createRequire } from 'node:module'; import { readFileSync, writeFileSync, existsSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import type { Plugin } from 'vite'; +import { createPreviewScenario, previewScenarios } from './preview-scenarios'; const require = createRequire(import.meta.url); export function previewApi(): Plugin { return { @@ -93,10 +94,19 @@ export function previewApi(): Plugin { } body = JSON.parse(text || '{}'); } + if (url.pathname === '/api/scenarios') { + if (req.method !== 'POST') { res.end(JSON.stringify(previewScenarios)); return; } + const scenario = await createPreviewScenario(engine, body.id); + state = scenario.state; + revision++; + messages = []; readAt = {}; + persist(); + res.end(JSON.stringify({ seat: scenario.seat })); return; + } if (url.pathname === '/api/reset' && req.method === 'POST') await reset(); if (url.pathname === '/api/settings' && req.method === 'POST') { if (body.seat !== 0 && body.seat !== 1) throw Error('Choose a player.'); - if (body.name !== 'skipRazeCity' || typeof body.value !== 'boolean') + if (!['skipRazeCity', 'keepGovernment'].includes(body.name) || typeof body.value !== 'boolean') throw Error('Invalid setting.'); state = engine.setPlayerSettings(state, body.seat, { [body.name]: body.value }); persist(); @@ -105,7 +115,10 @@ export function previewApi(): Plugin { } if (url.pathname === '/api/move' && req.method === 'POST') { if (body.revision !== revision) throw Error('The game changed. Please choose your action again.'); - if (!Number.isInteger(body.seat) || body.seat !== engine.currentPlayer(state)) + const move = typeof body.move === 'string' ? body.move : JSON.stringify(body.move); + const current = engine.currentPlayer(state); + const active = Array.isArray(current) ? current.includes(body.seat) : current === body.seat; + if (!Number.isInteger(body.seat) || (!active && !engine.canMoveOutOfTurn(state, move, body.seat))) throw Error('It is not your turn.'); state = engine.tryMove( state, diff --git a/web-client/scripts/preview-scenarios.ts b/web-client/scripts/preview-scenarios.ts new file mode 100644 index 00000000..86c29fef --- /dev/null +++ b/web-client/scripts/preview-scenarios.ts @@ -0,0 +1,40 @@ +import { readFileSync } from 'node:fs'; + +export const previewScenarios = [ + { 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.' }, + { id: 'objectives', label: 'Objectives', note: 'Objectives lets you queue beside each condition.' }, + { id: 'person', label: 'Great Person', note: 'Cards lets you take or pass conditionally; earlier players have priority.' }, + { id: 'government', label: 'Keep government preference', note: 'Research has Always keep current government. Changing governments is handled on your turn.' }, + { id: 'first', label: 'Choose first player', note: 'Use Choose first player beside your civilization while Rome finishes its government choice.' }, +]; + +export async function createPreviewScenario(engine: any, id: string) { + if (!previewScenarios.some(s => s.id === id)) throw Error('Unknown preview scenario'); + const names: Record = { + advance: 'status_phase/free_advance', raze: 'status_phase/raze_city_decline', + 'objectives-before': 'objective_cards/status_phase/standing_army', objectives: 'objective_cards/status_phase/standing_army', person: 'incidents/pirates_spawn', + government: 'status_phase/change_government', first: 'status_phase/change_government', + }; + const game = JSON.parse(readFileSync(new URL(`../../server/tests/test_games/${names[id]}.json`, import.meta.url), 'utf8')); + const fresh = JSON.parse(await engine.init(2, [], {}, 'early-preview', {})); + game.players = [...game.players.slice(0, 2), ...fresh.players.slice(2)]; + if (id === 'objectives' || id === 'objectives-before') { game.players[1].objective_cards = [13]; game.players[1].resources.wood = 7; } + if (id === 'person') { + game.incidents_left = [55]; + game.players[1].resources = { food: 2, culture_tokens: 4 }; + game.players[1].action_cards = [7, 9, 17]; + game.action_cards_left = game.action_cards_left?.filter((card: number) => ![7, 9, 17].includes(card)); + } + if (id === 'government' || id === 'first') { game.players[1].advances = [...game.players[0].advances]; game.players[0].resources.mood_tokens = 6; } + let state = JSON.stringify(game); + const apply = (action: unknown) => { state = engine.tryMove(state, JSON.stringify(action), engine.currentPlayer(state)); }; + if (id === 'advance' || id === 'objectives') apply({ Playing: 'EndTurn' }); + if (id === 'government' || id === 'first') apply({ Response: { SelectPositions: [] } }); + if (id === 'person') for (const response of [{ SelectAdvance: 'Storage' }, { SelectPositions: ['A2'] }, { SelectPositions: ['D1'] }, { Payment: [{ food: 1 }] }]) apply({ Response: response }); + const seat = id === 'objectives-before' ? 1 : 1 - engine.currentPlayer(state); + // Check the fixture can be rendered from both seats before replacing the preview. + for (const player of [0, 1]) engine.webView(engine.stripSecret(state, player), player); + return { state, seat }; +} diff --git a/web-client/src/ActionCardsDialog.svelte b/web-client/src/ActionCardsDialog.svelte index 14c856ee..95dc1a6d 100644 --- a/web-client/src/ActionCardsDialog.svelte +++ b/web-client/src/ActionCardsDialog.svelte @@ -1,6 +1,7 @@ + + + {#if saved}{:else}{/if} + + + diff --git a/web-client/src/EarlyChoices.svelte b/web-client/src/EarlyChoices.svelte new file mode 100644 index 00000000..2257af6a --- /dev/null +++ b/web-client/src/EarlyChoices.svelte @@ -0,0 +1,79 @@ + + +
+
+

{#if raze}Raze city{:else}{first ? 'Choose first player' : 'Choose ahead'}{/if}

+ +
+ {#each offers as offer (offer.key)} + {@const saved = offer.options.findIndex((o) => same(o.response, offer.selected))} + {@const value = selections[offer.key] ?? (saved >= 0 ? JSON.stringify(offer.selected) : '')} + {@const selected = offer.options.findIndex((o) => JSON.stringify(o.response) === value)} +
+ {#if !raze && !first}{/if} + {#if offer.key.endsWith('/advance')} +
+ + {#if saved >= 0}{/if} +
+ {#if saved >= 0}

Saved

{/if} + {:else if offer.key.endsWith('/raze')} +

Select a highlighted city on the map.

+ { controller.submit({QueueChoice:{key:offer.key,response:{SelectPositions:[]}}}); onclose(); }} + onraze={() => { controller.submit({QueueChoice:{key:offer.key,response:{SelectPositions:[$session.earlyRaze!.selected]}}}); onclose(); }} /> + {#if saved >= 0} +
+ Queued: {(offer.selected as {SelectPositions: string[]}).SelectPositions.length ? `raze ${(offer.selected as {SelectPositions: string[]}).SelectPositions[0]}` : 'keep all cities'} + +
+ {/if} + {:else} +
+ {#each offer.options as option} + + {/each} + {#if saved >= 0}{/if} +
+ {/if} + {#if !offer.key.endsWith('/advance') && selected >= 0 && offer.options[selected]?.description} +

+ {/if} +
+ {/each} +
+ + diff --git a/web-client/src/GreatPersonEffect.svelte b/web-client/src/GreatPersonEffect.svelte new file mode 100644 index 00000000..3ce82b2a --- /dev/null +++ b/web-client/src/GreatPersonEffect.svelte @@ -0,0 +1,10 @@ + +
+ {#if card.description.startsWith('You make place')}Active when taken{:else}Play {card.free ? 0 : 1} {/if} + +
diff --git a/web-client/src/RazeActions.svelte b/web-client/src/RazeActions.svelte new file mode 100644 index 00000000..45681f0e --- /dev/null +++ b/web-client/src/RazeActions.svelte @@ -0,0 +1,14 @@ + +
+ + +
+ diff --git a/web-client/src/ResearchTree.svelte b/web-client/src/ResearchTree.svelte index b95f5476..250e6ad0 100644 --- a/web-client/src/ResearchTree.svelte +++ b/web-client/src/ResearchTree.svelte @@ -57,7 +57,8 @@ } = $props(); const session = $derived(controller.session); const view = $derived(reference?.view ?? $session.view); - const choice = $derived(!reference && !$session.playback && researchDecision(view) ? view!.decision : null); + const early = $derived(!reference && !$session.playback ? view?.earlyChoices?.find((o) => o.key.endsWith('/advance')) : undefined); + const choice = $derived(early ? { name: 'Free advance', description: '', advanceMode: 'free', endOfAge: true } : !reference && !$session.playback && researchDecision(view) ? view!.decision : null); const freeResearch = $derived(!!choice && choice.advanceMode === 'free'); const borrowing = $derived(choice?.advanceMode === 'borrow'); let query = $state(''); @@ -266,12 +267,12 @@ {#if reference && player}· {player.civilization}{/if} {#if player}{/if} -

+ {#if !early}

{choice ? choice.description : 'Each advance scores ½ point. Branches unlock from their first advance.'}

- {#if choice}

Choose a highlighted advance.

{/if} + {#if choice}

Choose a highlighted advance.

{/if}{/if} {#if eventImminent}

{:else if lockedGovernment}{/if} + {#if group === currentGovernment && !reference && !$session.playback}{/if} {#each (view?.actionCards ?? []).filter(card => card.name === 'Synergies' && advances.some(a => a.group === group && cardHints(a).includes(card))) as card}

- {#if !advance.owned && (!choice || advance.action)}
- + {#if !early} 1}any mix{/if} {/each} {/if} - {/if}{#if researchAvailable(advance)} {#if warnsEvent}{:else}Available{/if} + >{:else if !early}Available{/if} {:else if !choice && parent && !parent.owned}
- {#if !reference && !$session.playback}
+ {#if !reference && !$session.playback}
+ {#if early?.selected} + + {/if} {#if !choice && !selected.owned && selected.payments.length > 1} ({ @@ -591,14 +595,14 @@ selectedAction && (!choice ? controller.submitResearch(selectedAction, buyFreeEducation) - : controller.submit(selectedAction))} + : (controller.submit(selectedAction), early && controller.patch({ mode: 'overview' })))} > {$session.pending ? 'Confirming…' : selected.owned ? 'Researched' - : `${borrowing ? 'Use' : choice?.advanceMode === 'paid' ? 'Choose' : 'Research'} ${selected.name}`} - {#if !selected.owned}{#if eventImminent}
{/if} - + >{/if} {:else}
ResearchedAvailable o.key === s.earlyRaze!.key) ? s.earlyRaze : undefined; + const mapChoices = earlyRaze ? earlyRaze.positions.map(position => ({position, name: position, description: '', value: position, mapTarget: undefined})) : mapDecisionOptions(s.view?.decision); this.tileTooltip.update(s); const decisionPositions = [...new Set(mapChoices.map((o) => o.position!))]; const pieceDecision = mapChoices.some((o) => o.mapTarget); @@ -1103,13 +1104,13 @@ export class World { : []; this.labelHost.classList.toggle('collecting', s.mode === 'collect'); this.labelHost.classList.toggle('choosing-happiness', s.mode === 'happiness'); - const decisionSelected = s.decisionSelection.flatMap((i) => mapChoices[i]?.position ?? []); + const decisionSelected = earlyRaze ? (earlyRaze.selected ? [earlyRaze.selected] : []) : s.decisionSelection.flatMap((i) => mapChoices[i]?.position ?? []); const interacting = s.mode === 'collect' || s.mode === 'happiness' || s.mode === 'settlers' || s.tilePanel || - mapChoices.length > 0 || + (mapChoices.length > 0 && !earlyRaze) || choosingCity || !!exploration || !!s.view?.decision?.tacticsSelection; @@ -2178,7 +2179,8 @@ export class World { if (interactionSignature !== this.interactionSignature) { this.interactionSignature = interactionSignature; this.updateViewport(); - this.centerInteraction(); + // Queued choices highlight the existing view without moving the player’s camera. + if (!earlyRaze) this.centerInteraction(); if (exploration) this.locateExploration(); } this.updateStructureMarkers(s, influence); diff --git a/web-client/src/controller.ts b/web-client/src/controller.ts index db7e9a63..83ddc3bd 100644 --- a/web-client/src/controller.ts +++ b/web-client/src/controller.ts @@ -87,6 +87,7 @@ export class Controller { replayAutoplay: true, availableOnly: false, skipRazeCity: false, + keepGovernment: false, }); readonly chat = new ChatController(); readonly audio = new GameAudio(); @@ -193,7 +194,7 @@ export class Controller { } setSettings(settings: Record | null) { this.playerSettings = settings; - this.patch({ skipRazeCity: settings?.skipRazeCity === true }); + this.patch({ skipRazeCity: settings?.skipRazeCity === true, keepGovernment: settings?.keepGovernment === true }); const request = this.keepCitiesRequest; this.keepCitiesRequest = null; const s = get(this.session); @@ -240,6 +241,11 @@ export class Controller { this.migratedSkipRaze = true; this.commands.updateSetting('skipRazeCity', true); } + setKeepGovernment(enabled: boolean) { + const s = get(this.session); + if (s.analysis || s.playback || s.pending || s.seat === undefined) return; + if (!this.commands.updateSetting('keepGovernment', enabled)) this.patch({error: 'Could not save the government setting. Please try again.'}); + } setSkipRazeCity(enabled: boolean) { const s = get(this.session); if (s.analysis || s.playback || s.pending || s.seat === undefined) return; @@ -948,7 +954,7 @@ export class Controller { if (get(this.session).seat !== undefined) this.playerSettings = null; this.migratedSkipRaze = false; this.keepCitiesRequest = null; - this.patch({ skipRazeCity: this.playerSettings?.skipRazeCity === true }); + this.patch({ skipRazeCity: this.playerSettings?.skipRazeCity === true, keepGovernment: this.playerSettings?.keepGovernment === true }); this.cardContinuation = null; this.endPlayback(); this.dismissEffects(true); @@ -1049,6 +1055,11 @@ export class Controller { this.inspectTile(position); return; } + if (s.earlyRaze && s.mode === 'overview' && s.view?.earlyChoices?.some(o => o.key === s.earlyRaze!.key)) { + if (!s.pending && s.earlyRaze.positions.includes(position)) + this.patch({earlyRaze: {...s.earlyRaze, selected: s.earlyRaze.selected === position ? null : position}}); + return; + } if (s.mode === 'port') { if (s.pending) return; const choice = s.portPlacement?.choices.find(c => c.position === position); @@ -1843,6 +1854,10 @@ export class Controller { s.playback || s.seat === undefined || (!(s.view?.activePlayers ?? [s.view?.activePlayer]).includes(s.seat) && + !( + typeof move === 'object' && 'QueueChoice' in move && + s.view?.earlyChoices?.some((c) => c.key === (move.QueueChoice as { key?: string })?.key) + ) && !( s.view?.civilizationDraft && typeof move === 'object' && diff --git a/web-client/src/decision-controls.test.ts b/web-client/src/decision-controls.test.ts index 2f80bc81..e6749606 100644 --- a/web-client/src/decision-controls.test.ts +++ b/web-client/src/decision-controls.test.ts @@ -150,7 +150,20 @@ test('free research exposes exactly the legal choices without paid actions or re assert.equal(next.players[seat].resources.food ?? 0, 0); assert.equal(next.players[seat].resources.gold ?? 0, 0); assert.ok(!researchDecision(view(state, 1 - seat))); - assert.ok(view(state, 1 - seat).advances.every((a) => !a.action)); + const waiting = view(state, 1 - seat); + const queuedAdvances = waiting.advances.filter((a) => a.action); + assert.ok(queuedAdvances.length > 0); + for (const advance of queuedAdvances) { + assert.ok('QueueChoice' in (advance.action as object)); + assert.equal(advance.costAmount, 0); + assert.deepEqual(advance.payments, []); + } + const queued = JSON.parse(engine.tryMove(state, JSON.stringify(queuedAdvances[0].action), 1 - seat)); + for (let player = 0; player < raw.players.length; player++) { + assert.deepEqual(queued.players[player].advances, raw.players[player].advances); + assert.deepEqual(queued.players[player].resources ?? {}, raw.players[player].resources ?? {}); + } + assert.equal(engine.currentPlayer(JSON.stringify(queued)), seat); assert.ok(!researchDecision(JSON.parse(engine.webView(engine.stripSecret(state))))); }); diff --git a/web-client/src/early-choices.test.ts b/web-client/src/early-choices.test.ts new file mode 100644 index 00000000..a5db6440 --- /dev/null +++ b/web-client/src/early-choices.test.ts @@ -0,0 +1,233 @@ +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)('../.engine/server.js'); +const npcs = JSON.parse(await engine.init(2, [], {}, 'early-choices', {})).players.slice(2); +function fixture(name: string) { + const g = JSON.parse(readFileSync(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8')); + g.players = [...g.players.slice(0, 2), ...structuredClone(npcs)]; + return JSON.stringify(g); +} +const apply = (raw: string, move: unknown, player = engine.currentPlayer(raw)) => engine.tryMove(raw, JSON.stringify(move), player); +const view = (raw: string, player: number) => JSON.parse(engine.webView(engine.stripSecret(raw, player), player)); +const queue = (raw: string, player: number, key: string, response: unknown) => apply(raw, { QueueChoice: { key, response } }, player); +const actions = (raw: string) => JSON.parse(raw).log.flatMap((a: any) => a.rounds.flatMap((r: any) => r.turns.flatMap((t: any) => t.actions ?? []))); +function research() { return apply(fixture('status_phase/free_advance'), { Playing: 'EndTurn' }); } + +test('early research is private, editable and persisted without spending or advancing play', () => { + const before = research(); + assert.equal(engine.currentPlayer(before), 1); + const offer = view(before, 0).earlyChoices[0]; + const selected = offer.options.find((o: any) => o.response.SelectAdvance === 'Philosophy'); + assert.ok(selected); + const command = JSON.stringify({ QueueChoice: { key: offer.key, response: selected.response } }); + assert.equal(engine.canMoveOutOfTurn(before, command, 0), true); + const queued = queue(before, 0, offer.key, selected.response); + assert.equal(engine.isLiveUpdate(queued), true); + assert.equal(engine.currentPlayer(queued), 1); + assert.deepEqual(JSON.parse(queued).players, JSON.parse(before).players); + assert.equal(actions(queued).length, actions(before).length); + assert.equal(JSON.parse(engine.stripSecret(queued, 1)).early_choices, undefined); + assert.equal(JSON.parse(engine.stripSecret(queued, undefined)).early_choices, undefined); + assert.deepEqual(view(queued, 0).earlyChoices[0].selected, selected.response); + const cancelled = queue(queued, 0, offer.key, null); + assert.equal(JSON.parse(cancelled).early_choices, undefined); + const edited = queue(queued, 0, offer.key, offer.options[0].response); + assert.equal(JSON.parse(edited).early_choices.length, 1); +}); + +test('queued research resolves in order as a normal journal response and replays', () => { + const before = research(); + const offer = view(before, 0).earlyChoices[0]; + const queued = queue(before, 0, offer.key, { SelectAdvance: 'Philosophy' }); + const after = apply(queued, { Response: { SelectAdvance: 'Storage' } }, 1); + assert.ok(JSON.parse(after).players[0].advances.includes('Philosophy')); + assert.ok(JSON.parse(after).players[1].advances.includes('Storage')); + assert.equal(JSON.parse(after).early_choices, undefined); + assert.equal(engine.isLiveUpdate(after), false); + const added = actions(after).slice(actions(before).length).map((a: any) => a.action); + assert.deepEqual(added.slice(0, 2), [{ Response: { SelectAdvance: 'Storage' } }, { Response: { SelectAdvance: 'Philosophy' } }]); + let replay = before; + for (const action of added) if (action !== 'StartTurn') replay = apply(replay, action); + assert.deepEqual(JSON.parse(replay).players, JSON.parse(after).players); +}); + +test('forged, stale, active-player and spectator queues are rejected', () => { + const raw = research(); + const offer = view(raw, 0).earlyChoices[0]; + for (const [player, key, response] of [ + [0, offer.key, { SelectAdvance: 'SteelWeapons' }], + [0, 'old-window', offer.options[0].response], + [1, offer.key, offer.options[0].response], + [99, offer.key, offer.options[0].response], + ] as const) assert.throws(() => queue(raw, player, key, response)); +}); + +test('a queued raze invalidated by a board change asks again instead of choosing another city', () => { + let raw = fixture('status_phase/raze_city'); + const offer = view(raw, 1).earlyChoices[0]; + const pick = offer.options.find((o: any) => o.response.SelectPositions.length); + assert.ok(pick); + raw = queue(raw, 1, offer.key, pick.response); + const changed = JSON.parse(raw); + const city = changed.players[1].cities.find((c: any) => c.position === pick.response.SelectPositions[0]); + city.city_pieces = { temple: 1 }; + raw = apply(JSON.stringify(changed), { Response: { SelectPositions: [] } }, 0); + assert.ok(JSON.parse(raw).players[1].cities.some((c: any) => c.position === city.position)); + assert.equal(JSON.parse(raw).early_choices, undefined); +}); + +function person() { + const g = JSON.parse(fixture('incidents/pirates_spawn')); + g.incidents_left = [55]; + g.players[1].resources = { food: 2, culture_tokens: 4 }; + let raw = JSON.stringify(g); + for (const response of [{ SelectAdvance: 'Storage' }, { SelectPositions: ['A2'] }, { SelectPositions: ['D1'] }, { Payment: [{ food: 1 }] }]) raw = apply(raw, { Response: response }); + return raw; +} + +test('Great Person preacceptance respects priority and waits through the recipient pirate payment', () => { + const raw = person(); + const offer = view(raw, 1).earlyChoices[0]; + assert.ok(offer); + const queued = queue(raw, 1, offer.key, { Payment: [{ culture_tokens: 2 }] }); + const passed = apply(queued, { Response: { Payment: [{}] } }, 0); + assert.equal(engine.currentPlayer(passed), 1); + assert.ok(JSON.parse(passed).events.at(-1).handler.request.Payment[0].name.includes('pirates')); + assert.ok(!(JSON.parse(passed).players[1].action_cards ?? []).includes(155)); + const after = apply(passed, { Response: { Payment: [{ food: 1 }] } }, 1); + assert.ok(JSON.parse(after).players[1].action_cards.includes(155)); + assert.equal(JSON.parse(after).players[1].resources.culture_tokens, 2); +}); + +test('Great Person claimed by earlier player expires conditional offers without charging others', () => { + const raw = person(); + const offer = view(raw, 1).earlyChoices[0]; + const queued = queue(raw, 1, offer.key, { Payment: [{ culture_tokens: 2 }] }); + let after = apply(queued, { Response: { Payment: [{ culture_tokens: 1 }] } }, 0); + after = apply(after, { Response: { Payment: [{ food: 1 }] } }, 1); + assert.equal(JSON.parse(after).players[1].resources.culture_tokens, 4); + assert.ok(JSON.parse(after).players[0].action_cards.includes(155)); + assert.equal(JSON.parse(after).early_choices, undefined); +}); + +test('early objective choices stay private and complete only when that player is reached', () => { + const g = JSON.parse(fixture('objective_cards/status_phase/standing_army')); + g.players[1].objective_cards = [13]; + g.players[1].resources.wood = 7; + let raw = apply(JSON.stringify(g), { Playing: 'EndTurn' }, 1); + const offer = view(raw, 1).earlyChoices.find((o: any) => o.title === 'Wood Supplies'); + assert.ok(offer, 'other player can queue a qualifying status objective'); + const pick = offer.options.find((o: any) => o.response.SelectHandCards.length); + for (const other of view(raw, 1).earlyChoices) { + raw = queue(raw, 1, other.key, other.key === offer.key ? pick.response : { SelectHandCards: [] }); + } + assert.ok(!JSON.parse(raw).players[1].completed_objectives?.length); + for (let i = 0; i < 3 && engine.currentPlayer(raw) === 0; i++) { + if (!JSON.parse(raw).events.at(-1)?.handler?.request.SelectHandCards) break; + raw = apply(raw, { Response: { SelectHandCards: [] } }, 0); + } + assert.ok(JSON.parse(raw).players[1].completed_objectives.some((o: any) => o.name === 'Wood Supplies')); +}); + +test('objectives can be queued before status, replace the other side, and expire when no longer met', () => { + const g = JSON.parse(fixture('objective_cards/status_phase/standing_army')); + g.players[1].objective_cards = [13]; + g.players[1].resources.wood = 7; + const before = JSON.stringify(g); + const offers = view(before, 1).earlyChoices; + const wood = offers.find((o: any) => o.title === 'Wood Supplies'); + assert.ok(wood, 'objective is available before ending the turn'); + const response = { SelectHandCards: [{ ObjectiveCard: 13 }] }; + const queued = queue(before, 1, wood.key, response); + assert.equal(JSON.parse(queued).early_choices.length, 1); + const other = offers.find((o: any) => o.key !== wood.key && o.options.some((v: any) => JSON.stringify(v.response) === JSON.stringify(response))); + if (other) { + const replaced = queue(queued, 1, other.key, response); + assert.equal(JSON.parse(replaced).early_choices.length, 1); + assert.equal(JSON.parse(replaced).early_choices[0].key, other.key); + } + const changed = JSON.parse(queued); + changed.players[1].resources.wood = 0; + const after = apply(JSON.stringify(changed), { Playing: 'EndTurn' }, 1); + assert.ok(!(JSON.parse(after).early_choices ?? []).some((c: any) => c.key === wood.key)); +}); + +test('a pre-status objective queue resolves only at that player’s objective check', () => { + const g = JSON.parse(fixture('objective_cards/status_phase/standing_army')); + g.players[1].objective_cards = [13]; + g.players[1].resources.wood = 7; + let raw = JSON.stringify(g); + for (const offer of view(raw, 1).earlyChoices) { + raw = queue(raw, 1, offer.key, offer.title === 'Wood Supplies' + ? { SelectHandCards: [{ ObjectiveCard: 13 }] } : { SelectHandCards: [] }); + } + raw = apply(raw, { Playing: 'EndTurn' }, 1); + assert.ok(!JSON.parse(raw).players[1].completed_objectives?.length); + for (let i = 0; i < 3 && engine.currentPlayer(raw) === 0; i++) { + if (!JSON.parse(raw).events.at(-1)?.handler?.request.SelectHandCards) break; + raw = apply(raw, { Response: { SelectHandCards: [] } }, 0); + } + assert.ok(JSON.parse(raw).players[1].completed_objectives.some((o: any) => o.name === 'Wood Supplies')); +}); + +function governmentQueueSetup() { + const g = JSON.parse(fixture('status_phase/change_government')); + g.players[1].advances = [...g.players[0].advances]; + g.players[0].resources.mood_tokens = 6; + return apply(JSON.stringify(g), {Response:{SelectPositions:[]}}); +} + +test('first player can be queued during government choices and resolves only for the actual chooser', () => { + const before = governmentQueueSetup(); + const offer = view(before, 1).earlyChoices.find((o: any) => o.key.endsWith(':first')); + assert.ok(offer); + let state = queue(before, 1, offer.key, {SelectPlayer:1}); + state = engine.setPlayerSettings(state, 1, {keepGovernment:true}); + state = apply(state, {Response:{Payment:[{}]}}); + assert.equal(JSON.parse(state).starting_player_index, 1); + assert.equal(JSON.parse(state).early_choices, undefined); +}); + +test('a changed first-player chooser does not consume another player’s queued selection', () => { + const before = governmentQueueSetup(); + const offer = view(before, 1).earlyChoices.find((o:any) => o.key.endsWith(':first')); + let state = queue(before,1,offer.key,{SelectPlayer:1}); + const g = JSON.parse(state); + g.players[1].resources.mood_tokens = 5; + state = engine.setPlayerSettings(JSON.stringify(g), 1, {keepGovernment:true}); + state = apply(state,{Response:{Payment:[{}]}}); + assert.equal(engine.currentPlayer(state),0); + assert.deepEqual(JSON.parse(state).events.at(-1).handler.request.SelectPlayer.choices, [0,1]); + assert.equal(JSON.parse(state).starting_player_index, 0); +}); + +test('first-player queue is visible only to the current eligible chooser, including ties', () => { + const g = JSON.parse(governmentQueueSetup()); + const hasOffer = () => view(JSON.stringify(g), 1).earlyChoices.some((o: any) => o.key.endsWith(':first')); + assert.equal(hasOffer(), true); // Greece: 14 tokens, Rome: 13. + g.players[1].resources.mood_tokens = 6; + assert.equal(hasOffer(), false); // Tie goes to Rome, first in turn order. + g.players[1].resources.mood_tokens = 5; + assert.equal(hasOffer(), false); +}); + +test('keep-government preference skips the optional payment without changing advances or resources', () => { + const before = governmentQueueSetup(); + const queued = engine.setPlayerSettings(before, 1, {keepGovernment:true}); + const after = apply(queued, {Response:{Payment:[{}]}}); + const p = JSON.parse(after).players[1]; + assert.deepEqual(p.advances, JSON.parse(before).players[1].advances); + assert.deepEqual(p.resources, JSON.parse(before).players[1].resources); + assert.ok(JSON.parse(after).events.at(-1).handler.request.SelectPlayer); + assert.ok(!view(before,1).earlyChoices.some((o:any) => o.key.endsWith('/government'))); +}); + +test('disabling keep-government restores the normal payment prompt', () => { + let state = engine.setPlayerSettings(governmentQueueSetup(),1,{keepGovernment:true}); + state = engine.setPlayerSettings(state,1,{keepGovernment:false}); + state = apply(state,{Response:{Payment:[{}]}}); + assert.equal(engine.currentPlayer(state),1); + assert.equal(JSON.parse(state).events.at(-1).handler.request.Payment[0].name,'Pay to change government'); +}); diff --git a/web-client/src/local-host.ts b/web-client/src/local-host.ts index 3455fe11..0e49d42d 100644 --- a/web-client/src/local-host.ts +++ b/web-client/src/local-host.ts @@ -1,6 +1,7 @@ const frame = document.querySelector('iframe')!; if (new URLSearchParams(location.search).has('built')) frame.src = '/built-viewer.html'; const seatSelect = document.querySelector('#seat')!; +seatSelect.value = sessionStorage.getItem('clash-preview-seat') ?? 'auto'; let revision = -1; let seat: number | undefined; let ready = false; @@ -31,6 +32,7 @@ try { 'availableOnly', 'replayAutoplay', 'skipRazeCity', + 'keepGovernment', ]) if (typeof saved[key] === 'boolean') preferences[key] = saved[key]; if (['2d', 'strategy'].includes(saved.mapView)) preferences.mapView = 'strategy'; @@ -171,11 +173,16 @@ addEventListener('message', async (event) => { `Player ${payload.index + 1} · ${payload.index === 0 ? 'Leif' : 'Aurelia'}`; }); seatSelect.onchange = () => { + sessionStorage.setItem('clash-preview-seat', seatSelect.value); lastMessages = ''; void refresh(true); }; document.querySelector('#reset')!.addEventListener('click', async () => { await post('/api/reset', {}); + sessionStorage.removeItem('clash-preview-scenario'); + scenarioSelect.value = ''; + scenarioNote.style.display = 'none'; + restartScenario.disabled = true; lastMessages = ''; showError(''); await refresh(true); @@ -187,3 +194,33 @@ document.querySelector('#theme')!.addEventListener('click', () => { setInterval(() => { if (ready) void refresh(); }, 2000); + +const scenarioSelect = document.querySelector('#scenario')!; +const restartScenario = document.querySelector('#restart-scenario')!; +const scenarioNote = document.querySelector('#scenario-note')!; +let scenarios: {id: string; label: string; note: string}[] = []; +fetch('/api/scenarios').then(r => r.json()).then(data => { + scenarios = data; + for (const item of scenarios) scenarioSelect.add(new Option(item.label, item.id)); + const remembered = sessionStorage.getItem('clash-preview-scenario'); + const scenario = scenarios.find(s => s.id === remembered); + if (scenario) { scenarioSelect.value = scenario.id; restartScenario.disabled = false; scenarioNote.textContent = scenario.note; scenarioNote.style.display = 'block'; } +}); +async function loadScenario() { + if (!scenarioSelect.value) return; + try { + restartScenario.disabled = true; + showError(''); + const result = await post('/api/scenarios', {id: scenarioSelect.value}); + seatSelect.value = String(result.seat); + sessionStorage.setItem('clash-preview-seat', seatSelect.value); + sessionStorage.setItem('clash-preview-scenario', scenarioSelect.value); + lastMessages = ''; + scenarioNote.textContent = scenarios.find(s => s.id === scenarioSelect.value)?.note ?? ''; + scenarioNote.style.display = 'block'; + frame.src = frame.src; + } catch (error) { showError(String(error)); } + finally { restartScenario.disabled = false; } +} +scenarioSelect.onchange = () => { void loadScenario(); }; +restartScenario.onclick = () => { void loadScenario(); }; diff --git a/web-client/src/research.css b/web-client/src/research.css index 60c0762e..5b9ef62f 100644 --- a/web-client/src/research.css +++ b/web-client/src/research.css @@ -645,3 +645,19 @@ .score-dialog .civilization-advances { margin: 20px 0; } + +.research-payment.early-payment { + display: flex; + align-items: stretch; + gap: 8px; +} +.early-payment .clear-choice { + padding: 10px 16px; + border: 1px solid var(--line); + border-radius: 4px; + background: var(--paper); +} +.early-payment .primary { flex: 1; width: auto; } + + +.keep-government { display:flex; gap:8px; align-items:center; font-size:12px; margin:0 0 12px; color:var(--muted); cursor:pointer; } diff --git a/web-client/src/style.css b/web-client/src/style.css index ea6c66d0..0da0040e 100644 --- a/web-client/src/style.css +++ b/web-client/src/style.css @@ -6317,3 +6317,54 @@ small { white-space: nowrap; } } + +.board-toolbar .board-actions button.early-available { + background: var(--paper2); + box-shadow: inset 0 -2px var(--gold, #b59255); + color: var(--ink); +} + +@media (min-width: 761px) and (min-height: 501px) { + .play-layout .action-panel.floating-panel.early-choices { + top: var(--action-bar-bottom, 154px); + max-height: calc(100% - var(--action-bar-bottom, 154px) - 20px); + } +} + +/* Both immediate and queued razing use the same desktop map prompt. */ +@media (min-width: 761px) and (min-height: 501px) { + .game-shell .play-layout .action-panel.floating-panel.raze-prompt { + left: auto; + right: 20px; + top: var(--action-bar-bottom, 154px); + bottom: auto; + width: 354px; + max-height: calc(100% - var(--action-bar-bottom, 154px) - 20px); + padding: 16px; + gap: 8px; + } + .game-shell .raze-prompt h2 { font-size: 24px; margin: 0; } +} + +.objective-queue-action { display: flex; justify-content: flex-end; margin: 8px 0 12px; } +.objective-queue-action button { display: flex; gap: 6px; align-items: center; padding: 8px 12px; border: 1px solid var(--line); border-radius: 4px; } + +.header-actions .cards-button.queue-available > svg, +.header-actions .objectives-button.queue-available > svg { + color: #b87523; +} +.header-actions .cards-button.queue-saved > svg, +.header-actions .objectives-button.queue-saved > svg { + color: var(--green); +} + +@media (min-width: 761px) and (min-height: 501px) { + .header-actions .text-button { + padding-block: 10px; + margin-block: -10px; + border-radius: 6px; + } +} + +.queue-first-player { display: flex; align-items: center; gap: 6px; padding: 7px 10px; border-radius: 5px; background: var(--paper); color: var(--ink); font-size: 11px; } +.queue-first-player.saved { color: var(--green); } diff --git a/web-client/src/types.ts b/web-client/src/types.ts index 1920ab26..cc1c59fe 100644 --- a/web-client/src/types.ts +++ b/web-client/src/types.ts @@ -18,7 +18,7 @@ export interface City { } export interface Player { id: number; - settings?: { skipRazeCity?: boolean }; + settings?: { skipRazeCity?: boolean; keepGovernment?: boolean }; name?: string; civilization: string; resources?: Pile; @@ -279,6 +279,7 @@ export interface ActiveEffect { rules: string[]; } export interface View { + earlyChoices?: { key: string; title: string; options: { label: string; description: string; response: unknown }[]; selected: unknown | null }[]; activeEffects?: ActiveEffect[]; cardCatalog?: Pick[]; influenceContext?: InfluenceContext | null; @@ -540,6 +541,7 @@ export interface EventInfo { targets: ('all' | 'active' | 'selected')[]; } export interface Session { + earlyRaze?: { key: string; positions: string[]; selected: string | null }; eventNotices?: import('./event-notices').EventNotice[]; portPlacement?: { city: string; payment: Pile; choices: { position: string; action: Move }[] }; landingTargets?: string[]; @@ -636,6 +638,7 @@ export interface Session { replayAutoplay: boolean; availableOnly: boolean; skipRazeCity: boolean; + keepGovernment: boolean; } export interface MapPick { kind: 'tile' | 'city' | 'unit' | 'units' | 'decision';