diff --git a/docs/monumental-game-length.md b/docs/monumental-game-length.md new file mode 100644 index 00000000..4e29c13c --- /dev/null +++ b/docs/monumental-game-length.md @@ -0,0 +1,99 @@ +# Monumental game lengths — viewer 0.1.203 / engine 0.4.137 + +The five creation choices are approved for publication with the matching engine. +`web-client/bgs-length-option.json` is the publisher input; the original proposal +is retained as a matching reference. Existing saved games are not migrated. + +## Selection and compatibility + +A single `options.length` enum selects exactly one mode. Arrays, unknown enum names +and objects combining modes are rejected by serde, including the WASM option parser. +Civilization selection, Builder and balance-patch options remain independent. +There is no ambiguous `Short` alias. Missing length still means serialized `Standard` (displayed as **Normal**, 6 ages); +`Epic` still means 8 ages in ongoing games, archives and replays. + +- `Shorter`: four ages and two initial settlers, including civilization-draft setup. + Nonfinal status phases give one free advance to every player in turn order, then + a second full pass. The second advance comes from supply, not the event tracker: + ordinary prerequisites, bonuses and advance listeners run, but no event marker + is consumed by that advance. Any nested choice retains its ordinary rules. +- `RollToEnd`: seven-age track. Roll before the first player's turn-start abilities + in each eligible round. The printed thresholds supplied by the user are: + + | Round | End on | + | --- | --- | + | VI.2 | 6 | + | VI.3 | 5–6 | + | VII.1 | 4–6 | + | VII.2 | 3–6 | + | VII.3 | 2–6 | + + The existing RNG/dice path has two faces for each number 1–6, and is therefore + uniform. It records the roll and uses the normal information-reveal undo barrier. + A successful roll enters final status immediately, without a player turn. +- `WonderfulEnding`: construction (not acquisition or capture) in those same five + rounds sets a persistent flag. Every remaining player finishes that round before + final status. Undoing a reversible construction also undoes the flag. + +Every final status phase checks objectives only: no free advances, cards, razing, +government changes or first-player selection. Variable modes without a trigger +finish normally at the end of VII. Existing no-city and withdrawal endings remain. + +## State and UI + +Optional `variable_end` records the triggered ending and survives saves and replay. +It is absent in all old/default games. `SecondFreeAdvance` is a distinct persistent +status phase, reusing the normal free-advance request/benefit handler. First-pass +preselections remain compatible; the second pass uses ordinary live choices. + +The viewer uses the saved length for the age track. The separate Game length +collapsible is removed. Tap/click any age (or use Tab and Enter/Space) to open +anchored rule details; Escape restores focus, and outside click dismisses them. +Hover titles and expanded/current-step semantics expose the same affordance. +The current mode's rules and all five mode names/age counts remain discoverable +there, including Shorter, Normal and legacy Epic. Normal is only a display name: +the serialized enum and creation option's value remain `Standard`. + +Roll to End marks VI and VII with dice; Wonderful Ending marks them with a wonder. +VI.1 is explicitly ineligible in the details and its current-age icon is muted. +Details give all five eligible rounds, exact dice thresholds, immediate versus +end-of-round timing, objectives-only final status and the VII fallback. +The round caption shows the applicable dice threshold in Roll to End. Wonderful +Ending shows **Wonder to end** only during VI.2–VII.3; a recorded construction +trigger changes this to **Ends this round**. Both captions open the same details. +Mobile retains the age track on a compact row; details wrap within the viewport +and render above map controls. All 17 catalogs contain the active captions and +rule/log strings (native-language editorial review remains useful). Second-pass +research does not display a spurious event-trigger warning. +The legacy Macroquad client continues to show the current age and round and uses +the same engine rules; its rule-help/localization UI is not expanded here. + +## Local verification + +- Rust 1.94.1 workspace tests, formatting check and Clippy completed. Clippy still + reports the repository's existing warning backlog. +- Eleven focused native tests cover the printed track, option shapes, both advance + passes, incident-marker boundaries, normal bonuses and nested wonder-card choice + resumption across save/load, final status, construction versus acquisition, + remaining-player handoffs/drops, and round-start undo barriers (including a + first-player chooser selecting themselves). +- Frontend type checking, 1,028 tests, catalog parity/source checks and production + build completed against a locally rebuilt wasm-bindgen 0.2.105 bridge. +- Browser smoke checks (`node web-client/scripts/game-length-smoke.mjs`, after + building and starting the local preview at http://localhost:8671/) cover + 1,400px and 390px EN/FR layouts, all five modes, actual age/phase-caption taps, + keyboard activation, Escape/focus restoration, outside dismissal, exact dice + thresholds, VI.1 inactivity, all five wonder-window rounds, triggered ending + labels, popover bounds/layering, no horizontal overflow and no page errors. + Screenshots are saved to `/tmp/clash-age-{roll,wonder}-{en,fr}-{1400,390}.png`. + +One intermediate randomized native run failed in the unrelated Tributes / +Acamapichtli action validator; subsequent full runs passed. The failing randomized +state was retained at `/tmp/clash-length-random-action-failure.json`, not added to +tracked fixtures. This is not represented as a warning-free or exhaustive rules audit. + +Release verification also checks the approved BGS creation choices against WASM, +including the missing-length Standard default, and runs the mode tests against +the packed 0.4.137 engine. Calendar privacy/history/undo and Voting/Sparta payment +regressions pass against that same package. The release workspace test run passed +(including random actions); the earlier randomized failure above did not recur. diff --git a/docs/monumental-length-option.proposal.json b/docs/monumental-length-option.proposal.json new file mode 100644 index 00000000..b2d9c22d --- /dev/null +++ b/docs/monumental-length-option.proposal.json @@ -0,0 +1,13 @@ +{ + "label": "Game length", + "type": "select", + "name": "length", + "default": "Standard", + "items": [ + { "name": "Standard", "label": "Normal — 6 ages" }, + { "name": "Shorter", "label": "Shorter — 4 ages, 2 settlers, two free advances" }, + { "name": "RollToEnd", "label": "Roll to End, up to 7 ages" }, + { "name": "WonderfulEnding", "label": "Wonderful Ending, up to 7 ages" }, + { "name": "Epic", "label": "Epic — 8 ages" } + ] +} diff --git a/server/src/early_choices.rs b/server/src/early_choices.rs index 38f1aba4..7aa6b8ac 100644 --- a/server/src/early_choices.rs +++ b/server/src/early_choices.rs @@ -122,7 +122,7 @@ fn advance_key(game: &Game) -> String { } fn advance_offer(game: &Game, player: usize) -> Option { - if game.age >= game.options.length.ages() { + if game.variable_end.is_some() || game.age >= game.options.length.ages() { return None; } let status = game diff --git a/server/src/game.rs b/server/src/game.rs index d1bcf838..c05cad0c 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -64,6 +64,9 @@ pub enum GameLength { #[default] Standard, Epic, + Shorter, + RollToEnd, + WonderfulEnding, } impl GameLength { @@ -72,6 +75,8 @@ impl GameLength { match self { Self::Standard => crate::consts::AGES, Self::Epic => 8, + Self::Shorter => 4, + Self::RollToEnd | Self::WonderfulEnding => 7, } } @@ -81,6 +86,25 @@ impl GameLength { } } +/// The printed seven-age track's final five rounds. +#[must_use] +pub fn variable_end_threshold(age: u32, round: u32) -> Option { + match (age, round) { + (6, 2) => Some(6), + (6, 3) => Some(5), + (7, 1) => Some(4), + (7, 2) => Some(3), + (7, 3) => Some(2), + _ => None, + } +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)] +pub enum VariableEnd { + RollToEnd, + WonderfulEnding, +} + #[derive(Serialize, Deserialize, PartialEq, Clone, Default)] pub struct GameOptions { // Read old saves only. Cleared on load; unrestricted undo is no longer a rule. @@ -162,6 +186,8 @@ pub struct Game { pub undo_limit: usize, pub actions_left: u32, pub successful_cultural_influence: bool, + /// Set by a variable ending; `WonderfulEnding` waits until this round completes. + pub variable_end: Option, pub round: u32, // starts at 1 pub age: u32, // starts at 1 pub messages: Vec, @@ -414,7 +440,11 @@ impl Game { pub(crate) fn start_turn(&mut self) { let player = self.current_player_index; add_turn_log(self, TurnType::Player(player)); + self.start_turn_after_log(); + } + fn start_turn_after_log(&mut self) { + let player = self.current_player_index; self.actions_left = ACTIONS; let lost_action = self .permanent_effects @@ -456,7 +486,8 @@ impl Game { pub fn increment_player_index(&mut self) { // Barbarians and Pirates have the highest player indices self.current_player_index += 1; - self.current_player_index %= self.human_players_count(); + // Seat indices remain stable when a player drops. + self.current_player_index %= self.players.iter().filter(|p| p.is_human()).count(); } #[must_use] @@ -537,6 +568,10 @@ impl Game { } fn next_round(&mut self) { + if self.variable_end == Some(VariableEnd::WonderfulEnding) { + enter_status_phase(self); + return; + } self.round += 1; self.skip_dropped_players(); if self.round > 3 { @@ -544,6 +579,30 @@ impl Game { return; } add_round_log(self, self.round); + if self.options.length == GameLength::RollToEnd + && let Some(threshold) = variable_end_threshold(self.age, self.round) + { + // Establish the log before rolling, but do not run any turn-start abilities. + add_turn_log(self, TurnType::Player(self.current_player_index)); + add_start_turn_action_if_needed(self, self.current_player_index); + let roll = self.next_dice_roll().value; + self.log( + self.current_player_index, + &EventOrigin::Ability("Roll to End".into()), + &format!("Roll to End: {roll} (end on {threshold}–6)"), + ); + if roll >= threshold { + self.variable_end = Some(VariableEnd::RollToEnd); + enter_status_phase(self); + } else { + self.start_turn_after_log(); + } + // Final-status / turn-start logging can replace the current turn. + // Keep the reveal barrier in that new log too (including when the + // first-player chooser is also the next active player). + self.lock_undo(); + return; + } self.start_turn(); } @@ -611,6 +670,10 @@ impl Game { true } + /// Remove a player while keeping surviving seat indices and round order stable. + /// + /// # Panics + /// Panics if the saved human-seat layout is inconsistent with its active players. pub fn drop_player(&mut self, player_index: usize) { if self.civilization_draft.is_some() { crate::game_setup::drop_draft_player(self, player_index); @@ -626,12 +689,22 @@ impl Game { "{} has left the game", self.player_name(player_index) )); + let dropped_first = self.starting_player_index == player_index; + if dropped_first { + let seats = self.players.iter().filter(|p| p.is_human()).count(); + self.starting_player_index = (1..seats) + .map(|offset| (player_index + offset) % seats) + .find(|p| !self.dropped_players.contains(p)) + .expect("an active player remains"); + } if self.current_player_index != player_index { return; } self.skip_dropped_players(); - if self.current_player_index == self.starting_player_index { + if !dropped_first && self.current_player_index == self.starting_player_index { self.next_round(); + } else if self.events.is_empty() { + self.start_turn(); } } diff --git a/server/src/game_data.rs b/server/src/game_data.rs index 9664c9b6..2aa147b1 100644 --- a/server/src/game_data.rs +++ b/server/src/game_data.rs @@ -82,6 +82,8 @@ pub struct GameData { #[serde(default)] #[serde(skip_serializing_if = "std::ops::Not::not")] successful_cultural_influence: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + variable_end: Option, round: u32, age: u32, messages: Vec, @@ -156,6 +158,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { calendar_incident_undo: None, log_index: data.log_index, undo_limit: data.undo_limit, + variable_end: data.variable_end, round: data.round, age: data.age, messages: data.messages, @@ -218,6 +221,7 @@ pub fn data(game: Game) -> GameData { undo_limit: game.undo_limit, actions_left: game.actions_left, successful_cultural_influence: game.successful_cultural_influence, + variable_end: game.variable_end.clone(), round: game.round, age: game.age, messages: game.messages, @@ -262,6 +266,7 @@ pub fn cloned_data(game: &Game) -> GameData { undo_limit: game.undo_limit, actions_left: game.actions_left, successful_cultural_influence: game.successful_cultural_influence, + variable_end: game.variable_end.clone(), round: game.round, age: game.age, messages: game.messages.clone(), diff --git a/server/src/game_length_tests.rs b/server/src/game_length_tests.rs new file mode 100644 index 00000000..10f4da00 --- /dev/null +++ b/server/src/game_length_tests.rs @@ -0,0 +1,366 @@ +use crate::action::Action; +use crate::advance::Advance; +use crate::content::persistent_events::EventResponse; +use crate::events::{EventOrigin, EventPlayer}; +use crate::game::{ + Game, GameContext, GameLength, GameOptions, GameState, VariableEnd, variable_end_threshold, +}; +use crate::game_setup::{GameSetupBuilder, setup_game}; +use crate::status_phase::{StatusPhaseState, enter_status_phase, get_status_phase}; +use crate::unit::UnitType; +use crate::wonder::{Wonder, construct_wonder, gain_wonder}; + +fn setup(length: GameLength) -> Game { + let mut game = setup_game( + &GameSetupBuilder::new(2) + .seed("official-length-tests".into()) + .assigned_civilizations(vec!["Rome".into(), "Greece".into()]) + .options(GameOptions { + length, + ..GameOptions::default() + }) + .build(), + ); + for p in &mut game.players { + p.objective_cards.clear(); + } + game.starting_player_index = 0; + game.current_player_index = 0; + game +} + +fn answer(game: Game, advance: Advance) -> Game { + let player = game.active_player(); + crate::game_api::execute( + game, + Action::Response(EventResponse::SelectAdvance(advance)), + player, + ) +} + +#[test] +fn printed_track_and_legacy_options() { + for age in 0..=9 { + for round in 0..=4 { + let expected = match (age, round) { + (6, 2) => Some(6), + (6, 3) => Some(5), + (7, 1) => Some(4), + (7, 2) => Some(3), + (7, 3) => Some(2), + _ => None, + }; + assert_eq!(variable_end_threshold(age, round), expected); + } + } + for (name, ages) in [ + ("Standard", 6), + ("Epic", 8), + ("Shorter", 4), + ("RollToEnd", 7), + ("WonderfulEnding", 7), + ] { + let options: GameOptions = serde_json::from_value( + serde_json::json!({"length":name,"variant":"Builder","civilization":"DraftThree"}), + ) + .expect("valid test options"); + assert_eq!(options.length.ages(), ages); + assert_eq!( + serde_json::to_value(options).expect("valid test options")["variant"], + "Builder" + ); + } + for length in [ + serde_json::json!(["Shorter", "RollToEnd"]), + serde_json::json!("Short"), + serde_json::json!({"Shorter":true,"WonderfulEnding":true}), + ] { + assert!( + serde_json::from_value::(serde_json::json!({"length":length})).is_err() + ); + } + assert_eq!( + serde_json::from_str::("{}") + .expect("valid test options") + .length + .ages(), + 6 + ); +} + +#[test] +fn shorter_setup_and_two_complete_passes() { + let mut game = setup(GameLength::Shorter); + for p in game.players.iter().filter(|p| p.is_human()) { + assert_eq!( + p.units + .iter() + .filter(|u| u.unit_type == UnitType::Settler) + .count(), + 2 + ); + } + game.starting_player_index = 1; + enter_status_phase(&mut game); + for (player, advance, phase) in [ + (1, Advance::Storage, StatusPhaseState::FreeAdvance), + (0, Advance::Storage, StatusPhaseState::FreeAdvance), + (1, Advance::Irrigation, StatusPhaseState::SecondFreeAdvance), + (0, Advance::Irrigation, StatusPhaseState::SecondFreeAdvance), + ] { + assert_eq!(game.active_player(), player); + assert_eq!(get_status_phase(&game), Some(&phase)); + if phase == StatusPhaseState::SecondFreeAdvance { + game.player_mut(player).incident_tokens = 1; + } + let mood = game.player(player).resources.mood_tokens; + let before = game.player(player).incident_tokens; + game = answer(game, advance); + assert!(game.player(player).has_advance(advance)); + if advance == Advance::Irrigation { + assert_eq!(game.player(player).resources.mood_tokens, mood + 1); + } + assert_eq!( + game.player(player).incident_tokens, + before - u8::from(phase == StatusPhaseState::FreeAdvance) + ); + } + assert_ne!( + get_status_phase(&game), + Some(&StatusPhaseState::SecondFreeAdvance) + ); +} + +#[test] +fn final_status_never_awards_advances() { + for (length, age) in [ + (GameLength::Shorter, 4), + (GameLength::Standard, 6), + (GameLength::Epic, 8), + (GameLength::RollToEnd, 7), + (GameLength::WonderfulEnding, 7), + ] { + let mut game = setup(length); + game.age = age; + let advances = game.player(0).advances; + enter_status_phase(&mut game); + assert!(matches!(game.state, GameState::Finished)); + assert_eq!(game.player(0).advances, advances); + assert!(game.events.is_empty()); + } +} + +#[test] +fn every_roll_boundary_precedes_turn_start_and_cannot_be_undone() { + for (age, round, threshold) in [(6, 2, 6), (6, 3, 5), (7, 1, 4), (7, 2, 3), (7, 3, 2)] { + for roll in 1..=6 { + let mut game = setup(GameLength::RollToEnd); + game.age = age; + game.round = round - 1; + game.current_player_index = 1; + game.dice_roll_outcomes = vec![(roll - 1) * 2]; + // A turn-start penalty must remain untouched when the roll ends play. + game.permanent_effects + .push(crate::content::effects::PermanentEffect::RevolutionLoseAction(0)); + game = crate::game_api::execute( + game, + Action::Playing(crate::playing_actions::PlayingAction::EndTurn), + 1, + ); + assert_eq!(game.dice_roll_log.last(), Some(&((roll - 1) * 2))); + assert_eq!(matches!(game.state, GameState::Finished), roll >= threshold); + assert_eq!(game.variable_end.is_some(), roll >= threshold); + assert!(!game.can_undo()); + if roll >= threshold { + assert!(!game.permanent_effects.is_empty()); + } + let restored = + Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play); + assert_eq!(restored.variable_end, game.variable_end); + assert_eq!(restored.dice_roll_log, game.dice_roll_log); + assert!(!restored.can_undo()); + } + } +} + +#[test] +fn rolls_only_at_eligible_round_start_not_each_player() { + let mut game = setup(GameLength::RollToEnd); + game.age = 6; + game.dice_roll_outcomes = vec![0]; + game.next_turn(); + assert_eq!(game.dice_roll_outcomes.len(), 1); + game.next_turn(); + assert!(game.dice_roll_outcomes.is_empty()); + game.dice_roll_outcomes.push(10); + game.next_turn(); + assert_eq!(game.dice_roll_outcomes.len(), 1); + assert!(!matches!(game.state, GameState::Finished)); +} + +#[test] +fn wonderful_ending_construction_only_and_finishes_whole_round() { + for (age, round, eligible) in [ + (6, 1, false), + (6, 2, true), + (6, 3, true), + (7, 1, true), + (7, 2, true), + (7, 3, true), + ] { + for builder in 0..2 { + let mut game = setup(GameLength::WonderfulEnding); + game.age = age; + game.round = round; + game.current_player_index = builder; + crate::log::add_start_turn_action_if_needed(&mut game, builder); + let player = EventPlayer::new(builder, EventOrigin::Wonder(Wonder::Colosseum)); + let city = game.player(builder).cities[0].position; + construct_wonder(&mut game, &player, Wonder::Colosseum, city); + assert_eq!(game.variable_end.is_some(), eligible); + assert!(!matches!(game.state, GameState::Finished)); + if builder == 0 { + game.next_turn(); + assert_eq!(game.current_player_index, 1); + assert!(!matches!(game.state, GameState::Finished)); + } + game.next_turn(); + assert_eq!(matches!(game.state, GameState::Finished), eligible); + } + } + let mut game = setup(GameLength::WonderfulEnding); + game.age = 7; + game.round = 2; + crate::log::add_start_turn_action_if_needed(&mut game, 0); + let city = game.player(0).cities[0].position; + gain_wonder( + &mut game, + &EventPlayer::new(0, EventOrigin::Wonder(Wonder::Colosseum)), + Wonder::Colosseum, + city, + ); + assert_eq!(game.variable_end, None); + game.variable_end = Some(VariableEnd::WonderfulEnding); + let restored = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play); + assert_eq!(restored.variable_end, game.variable_end); +} + +#[test] +fn first_pass_still_triggers_an_incident() { + let mut game = setup(GameLength::Shorter); + game.player_mut(0).incident_tokens = 1; + enter_status_phase(&mut game); + let incidents = game.incidents_left.len(); + game = answer(game, Advance::Storage); + assert_eq!(game.player(0).incident_tokens, 3); + assert!(game.incidents_left.len() < incidents); +} + +#[test] +fn second_pass_preserves_initializers_and_save_load() { + let mut game = setup(GameLength::Shorter); + enter_status_phase(&mut game); + game = answer(game, Advance::Storage); + game = answer(game, Advance::Storage); + assert_eq!( + get_status_phase(&game), + Some(&StatusPhaseState::SecondFreeAdvance) + ); + game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play); + game.player_mut(0).incident_tokens = 1; + let cards = game.player(0).action_cards.len(); + let objectives = game.player(0).objective_cards.len(); + let culture = game.player(0).resources.culture_tokens; + game = answer(game, Advance::Writing); + assert_eq!(game.player(0).action_cards.len(), cards + 1); + assert_eq!(game.player(0).objective_cards.len(), objectives + 1); + assert_eq!(game.player(0).resources.culture_tokens, culture + 1); + assert_eq!(game.player(0).incident_tokens, 1); + assert_eq!(game.active_player(), 1); + assert_eq!( + get_status_phase(&game), + Some(&StatusPhaseState::SecondFreeAdvance) + ); +} + +#[test] +fn remaining_seats_finish_wonderful_round_after_a_drop() { + for dropped in 0..3 { + let mut game = setup_game( + &GameSetupBuilder::new(3) + .seed("drop-length".into()) + .options(GameOptions { + length: GameLength::WonderfulEnding, + ..GameOptions::default() + }) + .build(), + ); + for player in &mut game.players { + player.objective_cards.clear(); + } + game.starting_player_index = 0; + game.current_player_index = 0; + game.age = 6; + game.round = 2; + game.variable_end = Some(VariableEnd::WonderfulEnding); + game.drop_player(dropped); + assert!(!matches!(game.state, GameState::Finished)); + // The current round still gives each surviving seat its turn. + game.next_turn(); + assert!(!matches!(game.state, GameState::Finished)); + game.next_turn(); + assert!(matches!(game.state, GameState::Finished)); + } +} + +#[test] +fn first_player_choosing_self_cannot_undo_round_start_roll() { + for roll in [0, 10] { + let mut game = setup(GameLength::RollToEnd); + game.age = 6; + game.round = 4; + game.dice_roll_outcomes = vec![roll]; + crate::status_phase::status_phase_response( + &mut game, + StatusPhaseState::DetermineFirstPlayer(0), + ); + game = crate::game_api::execute(game, Action::Response(EventResponse::SelectPlayer(0)), 0); + assert_eq!(game.age, 7); + assert_eq!(game.round, 1); + assert_eq!(game.dice_roll_log.last(), Some(&roll)); + assert!(!game.can_undo()); + assert_eq!(matches!(game.state, GameState::Finished), roll == 10); + } +} + +#[test] +fn second_pass_resumes_after_normal_nested_wonder_choice() { + let mut game = setup(GameLength::Shorter); + enter_status_phase(&mut game); + game = answer(game, Advance::Storage); + game = answer(game, Advance::Storage); + game.player_mut(0).incident_tokens = 1; + game.permanent_effects + .push(crate::content::effects::PermanentEffect::PublicWonderCard( + Wonder::Colosseum, + )); + game = answer(game, Advance::Engineering); + assert_eq!(game.active_player(), 0); + assert_eq!( + get_status_phase(&game), + Some(&StatusPhaseState::SecondFreeAdvance) + ); + assert!(matches!( + game.events.last().map(|event| &event.event_type), + Some(crate::content::persistent_events::PersistentEventType::DrawWonderCard(_)) + )); + game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play); + game = crate::game_api::execute(game, Action::Response(EventResponse::Bool(true)), 0); + assert!(game.player(0).wonder_cards.contains(&Wonder::Colosseum)); + assert_eq!(game.player(0).incident_tokens, 1); + assert_eq!(game.active_player(), 1); + assert_eq!( + get_status_phase(&game), + Some(&StatusPhaseState::SecondFreeAdvance) + ); +} diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs index 2c279408..d6123da1 100644 --- a/server/src/game_setup.rs +++ b/server/src/game_setup.rs @@ -220,6 +220,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game { undo_limit: 0, actions_left: ACTIONS, successful_cultural_influence: false, + variable_end: None, round: 1, age: 0, messages: vec![], @@ -297,6 +298,9 @@ fn execute_setup_round(player_amount: usize, game: &mut Game, map_setup: Option< gain_city(game, player, City::new(player_index, position)); set_city_mood(game, position, &origin, MoodState::Happy); gain_unit(game, player, position, UnitType::Settler); + if game.options.length == crate::game::GameLength::Shorter { + gain_unit(game, player, position, UnitType::Settler); + } } } } diff --git a/server/src/lib.rs b/server/src/lib.rs index 57860359..5779be35 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -83,3 +83,6 @@ pub mod utils; pub mod victory_points; pub mod web_view; pub mod wonder; + +#[cfg(test)] +mod game_length_tests; diff --git a/server/src/status_phase.rs b/server/src/status_phase.rs index 7b77cd59..61a5bc46 100644 --- a/server/src/status_phase.rs +++ b/server/src/status_phase.rs @@ -35,6 +35,7 @@ pub enum StatusPhaseStateType { pub enum StatusPhaseState { CompleteObjectives, FreeAdvance, + SecondFreeAdvance, DrawCards, RazeSize1City, ChangeGovernmentType(bool), @@ -116,7 +117,8 @@ fn play_status_phase(game: &mut Game, mut phase: StatusPhaseState, response: boo phase = match phase { CompleteObjectives => { - if game.age >= game.options.length.ages() + if game.variable_end.is_some() + || game.age >= game.options.length.ages() || game .players .iter() @@ -128,7 +130,10 @@ fn play_status_phase(game: &mut Game, mut phase: StatusPhaseState, response: boo } FreeAdvance } - FreeAdvance => DrawCards, + FreeAdvance if game.options.length == crate::game::GameLength::Shorter => { + SecondFreeAdvance + } + FreeAdvance | SecondFreeAdvance => DrawCards, DrawCards => RazeSize1City, RazeSize1City => ChangeGovernmentType(false), ChangeGovernmentType(_) => DetermineFirstPlayer(player_that_chooses_next_first_player( @@ -182,13 +187,13 @@ pub(crate) fn free_advance() -> Ability { .collect_vec(); Some(AdvanceRequest::new(choices)) }, - |game, c, _| { + |game, c, phase| { gain_advance_without_payment( game, c.choice, &c.player(), ResourcePile::empty(), - true, + *phase != StatusPhaseState::SecondFreeAdvance, ); }, ) @@ -523,7 +528,9 @@ pub(crate) fn player_that_chooses_next_first_player(players: &[&Player]) -> usiz pub fn status_phase_type(p: &StatusPhaseState) -> StatusPhaseStateType { match p { StatusPhaseState::CompleteObjectives => StatusPhaseStateType::CompleteObjectives, - StatusPhaseState::FreeAdvance => StatusPhaseStateType::FreeAdvance, + StatusPhaseState::FreeAdvance | StatusPhaseState::SecondFreeAdvance => { + StatusPhaseStateType::FreeAdvance + } StatusPhaseState::DrawCards => StatusPhaseStateType::DrawCards, StatusPhaseState::RazeSize1City => StatusPhaseStateType::RazeSize1City, StatusPhaseState::ChangeGovernmentType(_) => StatusPhaseStateType::ChangeGovernmentType, diff --git a/server/src/web_view/decisions.rs b/server/src/web_view/decisions.rs index 691712cf..3c724dbf 100644 --- a/server/src/web_view/decisions.rs +++ b/server/src/web_view/decisions.rs @@ -111,7 +111,12 @@ pub(super) fn advance_mode(game: &Game, handler: &PersistentEventHandler) -> &'s // costs resources (e.g. Synergies). The Library only borrows an effect. Regular // purchases, the status-phase advance, Dogma and leader research use a marker. pub(super) fn advance_uses_event_marker(game: &Game, handler: &PersistentEventHandler) -> bool { - !matches!(handler.origin, EventOrigin::CivilCard(_)) + !matches!( + game.events.last().map(|event| &event.event_type), + Some(PersistentEventType::StatusPhase( + crate::status_phase::StatusPhaseState::SecondFreeAdvance + )) + ) && !matches!(handler.origin, EventOrigin::CivilCard(_)) && !matches!(&handler.origin, EventOrigin::Ability(name) if name == "Teach us") && advance_mode(game, handler) != "borrow" } diff --git a/server/src/web_view/turn.rs b/server/src/web_view/turn.rs index 4a7fc4f5..fc144fac 100644 --- a/server/src/web_view/turn.rs +++ b/server/src/web_view/turn.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; // This is a forecast from the visible board, not a simulated turn. In particular, // do not trigger rewards, reveal secrets, or consume randomness while viewing it. pub(super) fn trade_warning(game: &Game, seat: usize) -> Option { - if game.round == 3 && game.age >= game.options.length.ages() { + if game.variable_end.is_some() || (game.round == 3 && game.age >= game.options.length.ages()) { return None; // No next turn after the final age. } let player = game.player(seat); diff --git a/server/src/wonder.rs b/server/src/wonder.rs index 5f9193cf..3518162c 100644 --- a/server/src/wonder.rs +++ b/server/src/wonder.rs @@ -505,6 +505,16 @@ pub(crate) fn construct_wonder( wonder: Wonder, city_position: Position, ) { + if game.options.length == crate::game::GameLength::WonderfulEnding + && crate::game::variable_end_threshold(game.age, game.round).is_some() + && game.variable_end.is_none() + { + game.variable_end = Some(crate::game::VariableEnd::WonderfulEnding); + player.log( + game, + "Wonderful Ending: finish this round, then complete objectives", + ); + } player.get_mut(game).wonders_built.push(wonder); activate_city(city_position, game, &EventOrigin::Wonder(wonder)); log_card_transfer( diff --git a/web-client/bgs-length-option.json b/web-client/bgs-length-option.json index 9ca6ffa0..b2d9c22d 100644 --- a/web-client/bgs-length-option.json +++ b/web-client/bgs-length-option.json @@ -4,7 +4,10 @@ "name": "length", "default": "Standard", "items": [ - { "name": "Standard", "label": "Standard — 6 ages" }, + { "name": "Standard", "label": "Normal — 6 ages" }, + { "name": "Shorter", "label": "Shorter — 4 ages, 2 settlers, two free advances" }, + { "name": "RollToEnd", "label": "Roll to End, up to 7 ages" }, + { "name": "WonderfulEnding", "label": "Wonderful Ending, up to 7 ages" }, { "name": "Epic", "label": "Epic — 8 ages" } ] } diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md index 251fd941..89076c96 100644 --- a/web-client/docs/viewer-publishing.md +++ b/web-client/docs/viewer-publishing.md @@ -953,3 +953,14 @@ Existing game history is not replayed or repaired. Calendar now persists owner-only known-top state at the first legal turn boundary. Reopening a known card, Keep and Cancel are local: no backend move, history entry or clock credit. Replacement cards require an explicit new inspection; stale-safe paid burial records the existing actions. Historical views omit private knowledge, and reload/reconstruction preserve knowledge and undo floors. Voting’s activation fee remains separate from Rituals’ city happiness conversions. Sparta can replace Draft tokens but cannot convert a recruited leader’s own mood fee. Both fees retain general Colosseum conversions. Publish the matching viewer and engine together; no production game repair or historical rewrite is needed. + +# Viewer 0.1.203 / engine 0.4.137 + +Publish the matching engine, viewer and game-length creation options together. +Shorter adds four ages, two starting settlers and two free-advance passes; +Roll to End and Wonderful Ending use the official seven-age track and their +respective dice/construction ending windows. Normal retains serialized Standard +and the six-age default; legacy Epic remains eight ages. The accessible AgeTrack +provides localized mode rules and ending captions on desktop and mobile. +No existing games are migrated or replayed. See +[implementation and verification](../../docs/monumental-game-length.md). diff --git a/web-client/package-lock.json b/web-client/package-lock.json index ee4615b1..162285ff 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.202", + "version": "0.1.203", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.202", + "version": "0.1.203", "dependencies": { "@boardgamers/protocol": "0.9.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index 93021191..7f30c36c 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.202", + "version": "0.1.203", "private": true, "type": "module", "scripts": { diff --git a/web-client/scripts/game-length-smoke.mjs b/web-client/scripts/game-length-smoke.mjs new file mode 100644 index 00000000..ea281849 --- /dev/null +++ b/web-client/scripts/game-length-smoke.mjs @@ -0,0 +1,156 @@ +// Local built viewer: npm run build; preview must be serving on localhost:8671. +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { readFile } from 'node:fs/promises'; +import { chromium } from 'playwright'; +const engine = createRequire(import.meta.url)('../.engine/server.js'); +const browser = await chromium.launch({ + headless: true, + args: ['--use-gl=angle', '--use-angle=swiftshader'], +}); +try { + for (const locale of ['en', 'fr']) { + const catalog = JSON.parse( + await readFile(new URL(`../src/localization/${locale}.json`, import.meta.url), 'utf8'), + ); + for (const width of [1400, 390]) { + const page = await browser.newPage({ viewport: { width, height: 900 }, hasTouch: true }); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await page.goto(`http://localhost:8671/?locale=${locale}`); + await page.waitForSelector('.age-track'); + await page.waitForSelector(`[data-clash-locale="${locale}"]`); + async function emit(mode, age = 1, round = 1, triggered = false) { + const game = JSON.parse(await engine.init(2, [], { length: mode }, 'age-track-smoke', {})); + Object.assign(game, { age, round }); + if (triggered) game.variable_end = 'WonderfulEnding'; + const state = engine.stripSecret(JSON.stringify(game), game.current_player_index); + await page.evaluate((state) => host.emit('state', state), state); + await page.waitForTimeout(100); + } + for (const [mode, count, name] of [ + ['Shorter', 4, 'Shorter'], + ['Standard', 6, 'Normal'], + ['RollToEnd', 7, 'Roll to End'], + ['WonderfulEnding', 7, 'Wonderful Ending'], + ['Epic', 8, 'Epic'], + ]) { + await emit(mode, 1, 1); + assert.equal(await page.locator('.age-step').count(), count); + await page.locator('.age-step').last().tap(); + const details = page.locator('.age-length-details'); + await details.waitFor(); + assert.ok((await details.innerText()).includes(catalog[name])); + assert.equal(await details.locator('footer').count(), 0); + assert.ok( + (await details.locator('strong').innerText()).includes( + `${catalog['Age']} ${['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII'][count - 1]}`, + ), + ); + assert.doesNotMatch(await details.innerText(), /VI\.[123]|VII\.[123]/); + const box = await details.boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= width, `popover fits ${width}`); + await page.keyboard.press('Escape'); + assert.equal(await details.count(), 0); + assert.equal( + await page + .locator('.age-step') + .last() + .evaluate((node) => document.activeElement === node), + true, + ); + } + await emit('RollToEnd', 6, 1); + assert.equal(await page.locator('.age-phase').count(), 0); + assert.equal(await page.locator('.age-step.current .inactive').count(), 1); + for (const [age, round, threshold] of [ + [6, 2, '6'], + [6, 3, '5–6'], + [7, 1, '4–6'], + [7, 2, '3–6'], + [7, 3, '2–6'], + ]) { + await emit('RollToEnd', age, round); + assert.equal(await page.locator('.age-phase').innerText(), threshold); + } + await page.locator('.age-step').nth(5).focus(); + await page.keyboard.press('Enter'); + const rows = page.locator('.age-end-thresholds tbody tr'); + assert.equal(await rows.count(), 5); + assert.deepEqual( + await rows.evaluateAll((nodes) => + nodes.map((node) => [...node.cells].map((cell) => cell.textContent)), + ), + [ + ['VI', '2', '6'], + ['VI', '3', '5–6'], + ['VII', '1', '4–6'], + ['VII', '2', '3–6'], + ['VII', '3', '2–6'], + ], + ); + assert.equal(await page.locator('.age-end-thresholds tr.current[aria-current="step"]').count(), 1); + assert.deepEqual(await page.locator('.age-end-thresholds tr.current td').allTextContents(), [ + 'VII', + '3', + '2–6', + ]); + await page.screenshot({ path: `/tmp/clash-age-roll-${locale}-${width}.png` }); + await page.locator('.age-details-close').click(); + for (const [age, round] of [ + [5, 3], + [6, 1], + ]) { + await emit('WonderfulEnding', age, round); + assert.equal(await page.locator('.age-phase').count(), 0); + } + for (const [age, round] of [ + [6, 2], + [6, 3], + [7, 1], + [7, 2], + [7, 3], + ]) { + await emit('WonderfulEnding', age, round); + assert.equal(await page.locator('.age-phase').innerText(), catalog['Wonder to end']); + } + await emit('WonderfulEnding', 6, 2); + await page.locator('.age-phase').tap(); + assert.ok( + (await page.locator('.age-length-details').innerText()).includes( + catalog[ + 'Starting from age 6, round 2, building a wonder ends the game after that round. Then complete objectives.' + ], + ), + ); + assert.equal(await page.locator('.age-length-details p').count(), 1); + assert.equal(await page.locator('.age-length-details table, .age-length-details footer').count(), 0); + assert.ok( + await page.locator('.age-length-details').evaluate((node) => { + const box = node.getBoundingClientRect(); + return node.contains(document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2)); + }), + 'details must render above the map action toolbar', + ); + await page.screenshot({ path: `/tmp/clash-age-wonder-${locale}-${width}.png` }); + await page.locator('.brand').click(); // Outside click dismisses the anchored details. + assert.equal(await page.locator('.age-length-details').count(), 0); + await emit('WonderfulEnding', 6, 2, true); + assert.equal(await page.locator('.age-phase').innerText(), catalog['Ends this round']); + await page.locator('.age-phase').tap(); + assert.ok( + (await page.locator('.age-length-details').innerText()).includes( + catalog['Wonderful Ending: finish this round, then complete objectives'], + ), + ); + await page.keyboard.press('Escape'); + assert.equal(await page.locator('.length-rule').count(), 0); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + assert.deepEqual(errors, []); + console.log(`Age-track tap/keyboard/round-window checks passed: ${locale}, ${width}px`); + await page.close(); + } + } +} finally { + await browser.close(); +} diff --git a/web-client/src/AgeTrack.svelte b/web-client/src/AgeTrack.svelte new file mode 100644 index 00000000..e3d35683 --- /dev/null +++ b/web-client/src/AgeTrack.svelte @@ -0,0 +1,126 @@ + + + { + if (event.key === 'Escape' && selected !== null) { + event.stopPropagation(); + close(); + } + }} + onclick={(event) => { + if (selected !== null && !root?.contains(event.target as Node)) selected = null; + }} +/> +
+
+ {#each Array.from({ length: ageCount(game) }, (_, i) => i + 1) as step} + + {/each} +
+ + {round > 3 ? t('End of age') : `${t('Round')} ${round}/3`}{#if roundHint} + · {roundHint}{/if} + {#if mode === 'WonderfulEnding' && (threshold !== null || triggered)} + + {:else if mode === 'RollToEnd' && threshold !== null} + + {/if} + + {#if selected !== null} +
+ + {t(lengthName(game))} · {t('Age')} {ageLabel(selected)} +

{t(lengthRule(game))}

+ {#if mode === 'RollToEnd'} + + + + {#each [[6, 2, 6], [6, 3, 5], [7, 1, 4], [7, 2, 3], [7, 3, 2]] as [endAge, endRound, endThreshold]} + + + + {/each} + +
{t('Age')}{t('Round')}{t('End on')}
{ageLabel(endAge)}{endRound}{endThreshold === 6 ? '6' : `${endThreshold}–6`}
+ {/if} + {#if triggered}

+ {t('Wonderful Ending: finish this round, then complete objectives')} +

{/if} +
+ {/if} +
diff --git a/web-client/src/App.svelte b/web-client/src/App.svelte index 0ff9267f..8d361f98 100644 --- a/web-client/src/App.svelte +++ b/web-client/src/App.svelte @@ -125,7 +125,8 @@ import CollectionIndicators from './CollectionIndicators.svelte'; import { movementBonus } from './movement-bonus'; import { sinceLastTurn } from './playback'; - import { ageCount, ageLabel } from './game-length'; + import { ageLabel } from './game-length'; + import AgeTrack from './AgeTrack.svelte'; import { roundProgress, personalRoundLabel } from './round-progress'; let { controller, concurrentPreview }: { controller: Controller; concurrentPreview?: { pending: boolean; waiting: boolean; seat: number; other: string; label?: string; pendingPlayer?: number; queued: number; ended: boolean; onUndo: () => void; onWait: () => void } } = $props(); const session = $derived(controller.session); @@ -832,31 +833,12 @@ >

-
- {#each Array.from({ length: ageCount($session.game) }, (_, i) => i + 1) as age} - - {ageLabel(age)} - - {/each} - {($session.playback?.frame?.round ?? $session.game?.round ?? 1) > 3 - ? 'End of age' - : `Round ${$session.playback?.frame?.round ?? $session.game?.round ?? 1}/3`}{#if roundHint} - · {roundHint}{/if} -
+