diff --git a/server/src/cache.rs b/server/src/cache.rs index 87288da3..5c3a1ca7 100644 --- a/server/src/cache.rs +++ b/server/src/cache.rs @@ -104,14 +104,14 @@ impl Cache { .map(|action_card| (action_card.id, action_card)) .collect(), - all_objective_cards: objective_cards::get_all_uncached(), - objective_cards_by_id: objective_cards::get_all_uncached() + all_objective_cards: objective_cards::get_all_uncached(options), + objective_cards_by_id: objective_cards::get_all_uncached(options) .into_iter() .map(|objective_card| (objective_card.id, objective_card)) .collect(), - all_objectives: objectives::get_all_uncached(), - objectives_by_name: objectives::get_all_uncached() + all_objectives: objectives::get_all_uncached(options), + objectives_by_name: objectives::get_all_uncached(options) .into_iter() .map(|objective| (objective.name.clone(), objective)) .collect(), diff --git a/server/src/combat_stats.rs b/server/src/combat_stats.rs index b2b23ce3..ad76df3f 100644 --- a/server/src/combat_stats.rs +++ b/server/src/combat_stats.rs @@ -248,10 +248,16 @@ pub(crate) fn new_combat_stats( let a = game.player(attacker); let d = game.player(defender); let attacker_position = a.get_unit(attackers[0]).position; + // A converted Persian unit fights the remaining army in the space where it + // was converted; it has not moved into that space from a neighboring tile. + let converted_army = battleground == Battleground::Land + && attackers.len() == 1 + && a.has_special_advance(crate::special_advance::SpecialAdvance::Zoroastrianism); assert!( defender_position != attacker_position - || (battleground == Battleground::Sea && d.civilization.is_pirates()), - "Only pirate ships sharing your sea space can be attacked without entering it" + || (battleground == Battleground::Sea && d.civilization.is_pirates()) + || converted_army, + "Combat in a shared space requires pirate ships or a converted army unit" ); CombatStats::new( diff --git a/server/src/content/objective_cards.rs b/server/src/content/objective_cards.rs index b6195c0d..311cffc9 100644 --- a/server/src/content/objective_cards.rs +++ b/server/src/content/objective_cards.rs @@ -23,13 +23,14 @@ use crate::content::objectives::unit_objectives::{ colony, horse_power, ivory_tower, large_army, large_fleet, migration, military_might, outpost, sea_blockade, shipping_routes, standing_army, threat, trade_power, versatility, }; +use crate::game::{GameOptions, GameVariant}; use crate::objective_card::ObjectiveCard; use itertools::Itertools; use std::vec; #[must_use] -pub(crate) fn get_all_uncached() -> Vec { - let all = vec![ +pub(crate) fn get_all_uncached(options: &GameOptions) -> Vec { + let mut all = vec![ ObjectiveCard::new(1, large_civ(), draft()), ObjectiveCard::new(2, science_lead(), conqueror()), ObjectiveCard::new(3, coastal_lead(), warmonger()), @@ -69,6 +70,12 @@ pub(crate) fn get_all_uncached() -> Vec { ObjectiveCard::new(37, migration(), trample()), ObjectiveCard::new(38, high_culture(), sea_cleansing()), ]; + if options.variant == GameVariant::Builder { + for card in &mut all { + card.objectives.retain(|o| !o.requires_player_combat); + } + all.retain(|card| !card.objectives.is_empty()); + } assert_eq!( all.iter().unique_by(|i| i.id).count(), all.len(), diff --git a/server/src/content/objectives.rs b/server/src/content/objectives.rs index cdcf3be4..f30ca213 100644 --- a/server/src/content/objectives.rs +++ b/server/src/content/objectives.rs @@ -6,14 +6,15 @@ pub(crate) mod resource_objectives; pub(crate) mod unit_objectives; use crate::content::objective_cards; +use crate::game::GameOptions; use crate::objective_card::Objective; use itertools::Itertools; #[must_use] -pub(crate) fn get_all_uncached() -> Vec { - let mut all = objective_cards::get_all_uncached() +pub(crate) fn get_all_uncached(options: &GameOptions) -> Vec { + let mut all = objective_cards::get_all_uncached(options) .into_iter() - .flat_map(|card| card.objectives.map(|o| (o.name.clone(), o))) + .flat_map(|card| card.objectives.into_iter().map(|o| (o.name.clone(), o))) .collect_vec(); all.sort_by_key(|(name, _)| name.clone()); all.dedup_by_key(|(name, _)| name.clone()); diff --git a/server/src/content/objectives/combat_objectives.rs b/server/src/content/objectives/combat_objectives.rs index 8b5cf98a..79cea07f 100644 --- a/server/src/content/objectives/combat_objectives.rs +++ b/server/src/content/objectives/combat_objectives.rs @@ -16,6 +16,7 @@ pub(crate) fn conqueror() -> Objective { name, "Immediately after capturing another player's city defended by at least 1 army unit or a Fortress.", ) + .requires_player_combat() .add_simple_persistent_event_listener( |event| &mut event.combat_end, 1, @@ -120,6 +121,7 @@ pub(crate) fn defiance() -> Objective { name, "You won a battle against a human player despite having fewer units than them.", ) + .requires_player_combat() .add_simple_persistent_event_listener( |event| &mut event.combat_end, 5, @@ -146,6 +148,7 @@ pub(crate) fn naval_assault() -> Objective { name, "Immediately after capturing another player's city with your army disembarking from a ship.", ) + .requires_player_combat() .add_simple_persistent_event_listener( |event| &mut event.combat_end, 6, @@ -236,6 +239,7 @@ pub(crate) fn scavenger() -> Objective { name, "You killed a settler or ship that could have been used for Trade Routes.", ) + .requires_player_combat() .add_simple_persistent_event_listener( |event| &mut event.combat_end, 9, @@ -354,6 +358,7 @@ pub(crate) fn great_commander() -> Objective { pub(crate) fn brutus() -> Objective { let name = "Brutus"; Objective::builder(name, "You killed a leader and 2 army units in a battle.") + .requires_player_combat() .add_simple_persistent_event_listener( |event| &mut event.combat_end, 14, diff --git a/server/src/cultural_influence.rs b/server/src/cultural_influence.rs index 636dc65d..c51d0855 100644 --- a/server/src/cultural_influence.rs +++ b/server/src/cultural_influence.rs @@ -792,6 +792,9 @@ pub(crate) fn unit_influence_cost( { return Err("No matching unit available".into()); } + if !game.can_attack_player(player, owner.index) && owner.get_units(unit.position).len() > 1 { + return Err("Builder: this conversion would start a battle with another player".into()); + } let dummy_city = City::new(target.player, unit.position); let (start, boost) = affordable_start_position( game, diff --git a/server/src/game.rs b/server/src/game.rs index 31472ede..ce783a82 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -93,6 +93,22 @@ pub struct GameOptions { pub patch: PatchOption, #[serde(default, skip_serializing_if = "GameLength::is_default")] pub length: GameLength, + #[serde(default, skip_serializing_if = "GameVariant::is_default")] + pub variant: GameVariant, +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Default)] +pub enum GameVariant { + #[default] + Standard, + Builder, +} + +impl GameVariant { + #[must_use] + pub fn is_default(&self) -> bool { + self == &Self::Standard + } } impl GameOptions { @@ -354,6 +370,13 @@ impl Game { }) } + #[must_use] + pub fn can_attack_player(&self, attacker: usize, defender: usize) -> bool { + self.options.variant != GameVariant::Builder + || !self.player(attacker).is_human() + || !self.player(defender).is_human() + } + pub fn add_info_log_item(&mut self, info: &str) { current_action_log_mut(self).log.push(info.to_string()); } diff --git a/server/src/movement.rs b/server/src/movement.rs index 1279f6c0..584e5de4 100644 --- a/server/src/movement.rs +++ b/server/src/movement.rs @@ -698,7 +698,11 @@ fn is_move_restricted( return Err("battle movement restriction".to_string()); } let dest = route.destination; - let attack = game.enemy_player(player.index, dest).is_some(); + let enemy = game.enemy_player(player.index, dest); + if enemy.is_some_and(|defender| !game.can_attack_player(player.index, defender)) { + return Err("Builder: you cannot attack another player's units or cities".into()); + } + let attack = enemy.is_some(); if attack && game.map.is_land(dest) && stack_size == 0 { return Err("no army units to attack".to_string()); } diff --git a/server/src/objective_card.rs b/server/src/objective_card.rs index 65c0c41f..60e86616 100644 --- a/server/src/objective_card.rs +++ b/server/src/objective_card.rs @@ -50,6 +50,7 @@ pub enum ObjectiveType { pub struct Objective { pub name: String, pub description: String, + pub(crate) requires_player_combat: bool, pub(crate) listeners: AbilityListeners, pub(crate) status_phase_check: Option, pub(crate) progress: Option, @@ -83,7 +84,7 @@ impl Objective { #[derive(Clone)] pub struct ObjectiveCard { pub id: u8, - pub objectives: [Objective; 2], + pub objectives: Vec, } impl ObjectiveCard { @@ -91,7 +92,7 @@ impl ObjectiveCard { pub fn new(id: u8, first: Objective, second: Objective) -> Self { Self { id, - objectives: [first, second], + objectives: vec![first, second], } } @@ -102,13 +103,14 @@ impl ObjectiveCard { #[must_use] pub fn name(&self) -> String { - format!("{}/{}", self.objectives[0].name, self.objectives[1].name) + self.objectives.iter().map(|o| &o.name).join("/") } } pub struct ObjectiveBuilder { name: String, description: String, + requires_player_combat: bool, status_phase_check: Option, progress: Option, status_phase_update: Option, @@ -122,6 +124,7 @@ impl ObjectiveBuilder { Self { name: name.to_string(), description: description.to_string(), + requires_player_combat: false, status_phase_check: None, progress: None, status_phase_update: None, @@ -130,6 +133,12 @@ impl ObjectiveBuilder { } } + #[must_use] + pub(crate) fn requires_player_combat(mut self) -> Self { + self.requires_player_combat = true; + self + } + #[must_use] pub(crate) fn status_phase_check(mut self, f: F) -> Self where @@ -183,6 +192,7 @@ impl ObjectiveBuilder { Objective { name: self.name, description: self.description, + requires_player_combat: self.requires_player_combat, listeners: self.builder.build(), status_phase_check: self.status_phase_check, progress: self.progress, diff --git a/server/src/recruit.rs b/server/src/recruit.rs index 37e7b7b8..fae0312f 100644 --- a/server/src/recruit.rs +++ b/server/src/recruit.rs @@ -328,6 +328,14 @@ fn recruit_cost_options( if units.ships > 0 && city.pieces.port.is_none() { return Err("Mising building: port".to_string()); } + if units.ships > 0 + && city + .port_position + .and_then(|port| game.enemy_player(player.index, port)) + .is_some_and(|defender| !game.can_attack_player(player.index, defender)) + { + return Err("Builder: you cannot recruit ships into another player's fleet".into()); + } for (t, a) in units.clone() { let avail = player.unit_limit().get_amount(&t); diff --git a/server/tests/builder_tests.rs b/server/tests/builder_tests.rs new file mode 100644 index 00000000..d6512c72 --- /dev/null +++ b/server/tests/builder_tests.rs @@ -0,0 +1,256 @@ +use common::{JsonTest, influence_action, move_action}; +use server::action::{Action, try_execute_action}; +use server::cache::Cache; +use server::game::{CivSetupOption, Game, GameContext, GameLength, GameOptions, GameVariant}; +use server::game_api; +use server::movement::possible_move_routes; +use server::player::CostTrigger; +use server::playing_actions::PlayingAction; +use server::position::Position; +use server::recruit::{Recruit, recruit_cost_without_replaced}; +use server::resource_pile::ResourcePile; +use server::unit::{Unit, UnitType, Units}; + +mod common; + +fn builder(mut game: Game) -> Game { + game.options.variant = GameVariant::Builder; + let cache = Cache::new(&game.options); + Game::from_data(game.cloned_data(), cache, GameContext::Play) +} + +fn can_move_to(game: &Game, units: &[u32], destination: Position) -> bool { + let player = game.player(0); + possible_move_routes( + player, + game, + units, + player.get_unit(units[0]).position, + None, + ) + .unwrap_or_default() + .iter() + .any(|route| route.destination == destination) +} + +#[test] +fn builder_blocks_land_sea_and_disembarking_attacks_in_previews_and_execution() { + for (folder, fixture, units, destination) in [ + ( + "combat", + "remove_casualties_attacker", + vec![0, 1, 2, 3], + "C1", + ), + ("combat", "ship_combat", vec![7, 8], "D2"), + ( + "movement", + "ship_disembark_capture_empty_city", + vec![1, 2], + "B2", + ), + ] { + let game = JsonTest::new(folder).load_game(fixture); + let destination = Position::from_offset(destination); + assert!(can_move_to(&game, &units, destination), "{fixture}"); + let game = builder(game); + assert!(!can_move_to(&game, &units, destination), "{fixture}"); + let error = try_execute_action(game, move_action(units, destination), 0) + .err() + .expect("Builder must reject the submitted attack"); + assert!(error.contains("Builder"), "{fixture}: {error}"); + } +} + +#[test] +fn builder_also_protects_undefended_settlers() { + let mut game = JsonTest::new("combat").load_game("remove_casualties_attacker"); + let destination = Position::from_offset("C1"); + game.players[1].cities.clear(); + game.players[1].units = vec![Unit::new(1, destination, UnitType::Settler, 0)]; + assert!(can_move_to(&game, &[0, 1, 2, 3], destination)); + assert!(!can_move_to(&builder(game), &[0, 1, 2, 3], destination)); +} + +#[test] +fn builder_keeps_attacks_against_barbarians_and_pirates() { + for (fixture, civilization, units, destination) in [ + ( + "remove_casualties_attacker", + "Barbarians", + vec![0, 1, 2, 3], + "C1", + ), + ("ship_combat", "Pirates", vec![7, 8], "D2"), + ] { + let mut game = JsonTest::new("combat").load_game(fixture); + game.players[1].civilization = game.cache.get_civilization(civilization); + let game = builder(game); + let destination = Position::from_offset(destination); + assert!(can_move_to(&game, &units, destination), "{civilization}"); + assert!(try_execute_action(game, move_action(units, destination), 0).is_ok()); + } +} + +#[test] +fn builder_preserves_barbarian_attacks_on_players() { + let game = JsonTest::new("incidents").load_game("barbarians_attack"); + let action = Action::Response( + server::content::persistent_events::EventResponse::SelectAdvance( + server::advance::Advance::Storage, + ), + ); + let standard = try_execute_action(game.clone(), action.clone(), 0).unwrap(); + let mut peaceful = try_execute_action(builder(game), action, 0).unwrap(); + peaceful.options.variant = GameVariant::Standard; + assert_eq!(common::to_json(&standard), common::to_json(&peaceful)); +} + +#[test] +fn builder_blocks_recruiting_into_player_fleets_but_keeps_pirate_battles_and_land_recruitment() { + let game = builder(JsonTest::new("combat").load_game("recruit_combat")); + let city = Position::from_offset("C2"); + let units = Units::new(0, 0, 4, 0, 0, None); + let action = Action::Playing(PlayingAction::Recruit(Recruit::new( + &units, + city, + ResourcePile::wood(5) + ResourcePile::gold(3), + ))); + assert!(try_execute_action(game.clone(), action.clone(), 0).is_ok()); + let mut game = game; + let pirates = game + .players + .iter() + .position(|p| p.civilization.is_pirates()) + .unwrap(); + game.players[pirates].civilization = game.cache.get_civilization("Rome"); + assert!( + recruit_cost_without_replaced( + &game, + game.player(0), + &units, + city, + CostTrigger::WithModifiers + ) + .err() + .unwrap() + .contains("Builder") + ); + assert!( + try_execute_action(game.clone(), action, 0) + .err() + .unwrap() + .contains("Builder") + ); + assert!( + recruit_cost_without_replaced( + &game, + game.player(0), + &Units::new(0, 1, 0, 0, 0, None), + city, + CostTrigger::WithModifiers, + ) + .is_ok() + ); +} + +#[test] +fn builder_preserves_cultural_influence() { + let game = builder(JsonTest::new("base").load_game("cultural_influence")); + assert!(try_execute_action(game, influence_action(), 1).is_ok()); +} + +#[test] +fn builder_removes_only_objectives_requiring_player_combat() { + let standard = Cache::new(&GameOptions::default()); + let options = GameOptions { + variant: GameVariant::Builder, + ..GameOptions::default() + }; + let builder = Cache::new(&options); + let removed = [ + "Conqueror", + "Defiance", + "Naval Assault", + "Scavenger", + "Brutus", + ]; + assert_eq!( + builder.get_objective_cards().len(), + standard.get_objective_cards().len() + ); + for card in standard.get_objective_cards() { + let filtered = builder.get_objective_card(card.id); + let expected: Vec<_> = card + .objectives + .iter() + .filter(|o| !removed.contains(&o.name.as_str())) + .map(|o| &o.name) + .collect(); + assert_eq!( + filtered + .objectives + .iter() + .map(|o| &o.name) + .collect::>(), + expected + ); + assert!(!filtered.name().is_empty()); + } + for name in removed { + assert!(standard.get_objectives().iter().any(|o| o.name == name)); + assert!(!builder.get_objectives().iter().any(|o| o.name == name)); + } + assert_eq!(builder.get_objective_card(10).name(), "Optimized Storage"); + for name in [ + "Barbarian Conquest", + "Resistance", + "Sea Cleansing", + "General", + "Warmonger", + "Legendary Battle", + "Threat", + "Sea Blockade", + "Consulate", + ] { + assert!(builder.get_objectives().iter().any(|o| o.name == name)); + } +} + +#[test] +fn builder_combines_with_epic_and_civilization_draft_and_survives_save_load() { + let default: GameOptions = serde_json::from_str("{}").unwrap(); + assert!(default.variant == GameVariant::Standard); + assert_eq!( + serde_json::to_value(default).unwrap(), + serde_json::json!({}) + ); + let options = GameOptions { + variant: GameVariant::Builder, + length: GameLength::Epic, + civilization: CivSetupOption::DraftThree, + ..GameOptions::default() + }; + let mut game = game_api::init(4, "builder-draft".into(), options); + let offers = game.civilization_draft.as_ref().unwrap().offers.clone(); + for (seat, choices) in offers.into_iter().enumerate() { + game = + try_execute_action(game, Action::ChooseCivilization(choices[0].clone()), seat).unwrap(); + } + let data = game.cloned_data(); + let cache = Cache::new(&data.options); + let game = Game::from_data(data, cache, GameContext::Play); + assert!(game.options.variant == GameVariant::Builder); + assert_eq!(game.options.length.ages(), 10); + assert!(game.civilization_draft.is_none()); + assert!(!game.map.tiles.is_empty()); + assert_eq!(game.cache.get_objective_card(20).name(), "Science Focus"); + for attacker in 0..4 { + for defender in 0..4 { + assert!(!game.can_attack_player(attacker, defender)); + } + assert!(game.can_attack_player(attacker, 4)); + assert!(game.can_attack_player(4, attacker)); + assert!(game.can_attack_player(attacker, 5)); + } +} diff --git a/web-client/bgs-variant-option.json b/web-client/bgs-variant-option.json new file mode 100644 index 00000000..702afc3a --- /dev/null +++ b/web-client/bgs-variant-option.json @@ -0,0 +1,10 @@ +{ + "label": "Variant", + "type": "select", + "name": "variant", + "default": "Standard", + "items": [ + { "name": "Standard", "label": "Standard" }, + { "name": "Builder", "label": "Builder — no military attacks between players" } + ] +} diff --git a/web-client/scripts/publish.mjs b/web-client/scripts/publish.mjs index 94f6c78d..c8e72ef8 100644 --- a/web-client/scripts/publish.mjs +++ b/web-client/scripts/publish.mjs @@ -30,10 +30,14 @@ const civilizationOption = JSON.parse( await fs.readFile(path.join(root, 'bgs-civilization-option.json'), 'utf8'), ); const lengthOption = JSON.parse(await fs.readFile(path.join(root, 'bgs-length-option.json'), 'utf8')); +const variantOption = JSON.parse(await fs.readFile(path.join(root, 'bgs-variant-option.json'), 'utf8')); const options = [ - ...(previous.options ?? []).filter((option) => !['undo', 'civilization', 'length'].includes(option.name)), + ...(previous.options ?? []).filter( + (option) => !['undo', 'civilization', 'length', 'variant'].includes(option.name), + ), civilizationOption, lengthOption, + variantOption, ]; const declaredPreferences = JSON.parse(await fs.readFile(path.join(root, 'bgs-preferences.json'), 'utf8')); const replacedPreferences = new Set([ diff --git a/web-client/src/App.svelte b/web-client/src/App.svelte index 224e0cb8..b7f82d18 100644 --- a/web-client/src/App.svelte +++ b/web-client/src/App.svelte @@ -515,7 +515,7 @@ onclick={() => controller.commands.openBoardgame()} aria-label="About Clash of Cultures" >Clash of Cultures{#if $session.view?.civilizationDraft}Civilization draft{:else}Age {ageLabel( + >{#if $session.game?.options?.variant === 'Builder'}Builder · {/if}{#if $session.view?.civilizationDraft}Civilization draft{:else}Age {ageLabel( $session.playback?.frame?.age ?? $session.game?.age ?? 1, )} · {($session.playback?.frame?.round ?? $session.game?.round ?? 1) > 3 ? 'End of age' @@ -1309,7 +1309,12 @@ >

How to play

-

Score the most points over six ages.

+

Score the most points over {ageCount($session.game)} ages.

+ {#if $session.game?.options?.variant === 'Builder'} +

Builder: You cannot attack another player's units or cities. Barbarians + and pirates remain, and Cultural Influence is allowed. Objectives requiring battles + against other players are removed; their cards keep any remaining objective.

+ {/if}
@@ -1319,7 +1324,7 @@ wonders, events and captured leaders.

- The game ends after Age VI’s objective checks. It also ends at an earlier age’s objective checks + The game ends after Age {ageLabel(ageCount($session.game))}’s objective checks. It also ends at an earlier age’s objective checks if any player has no cities. Compare total scores in either case; there is no fixed score target.

diff --git a/web-client/src/builder.test.ts b/web-client/src/builder.test.ts new file mode 100644 index 00000000..aa93c9f1 --- /dev/null +++ b/web-client/src/builder.test.ts @@ -0,0 +1,96 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; + +const engine = createRequire(import.meta.url)('../.engine/server.js'); +const serialize = (game: unknown) => JSON.stringify(game); +const view = (game: unknown, seat: number | undefined = 0) => + JSON.parse(engine.webView(engine.stripSecret(serialize(game), seat), seat)); +const move = (game: unknown, action: unknown, seat = 0) => + JSON.parse(engine.tryMove(serialize(game), serialize(action), seat)); + +async function fixture(name: string) { + const game = JSON.parse( + readFileSync(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'), + ); + const npcs = JSON.parse(await engine.init(2, [], {}, 'builder-fixtures', {})).players.slice(2); + game.players.push(...npcs); + return game; +} + +test('Builder keeps peaceful halves of objective cards in the private hand', async () => { + const game = JSON.parse(await engine.init(2, [], { variant: 'Builder' }, 'builder-objectives', {})); + game.players[0].objective_cards = [10, 20, 24, 38]; + assert.deepEqual( + view(game).objectiveCards.map((card: any) => card.objectives.map((o: any) => o.name)), + [ + ['Optimized Storage'], + ['Science Focus'], + ['Government', 'Barbarian Conquest'], + ['High Culture', 'Sea Cleansing'], + ], + ); + game.players[1].objective_cards = []; + assert.deepEqual(view(game, 1).objectiveCards, []); + const publicGame = engine.stripSecret(serialize(game), undefined); + assert.deepEqual(JSON.parse(engine.webView(publicGame, undefined)).objectiveCards, []); + assert.equal(JSON.parse(publicGame).options.variant, 'Builder'); + game.options.variant = 'Standard'; + assert.equal(view(game).objectiveCards[0].objectives[1].name, 'Naval Assault'); +}); + +test('Builder does not offer hostile map destinations and rejects a stale attack action', async () => { + const game = await fixture('combat/remove_casualties_attacker'); + const query = () => + JSON.parse( + engine.webQuery( + engine.stripSecret(serialize(game), 0), + 0, + serialize({ kind: 'movement', units: [0, 1, 2, 3] }), + ), + ); + const attack = query().destinations.find((d: any) => d.position === 'C1'); + assert.ok(attack?.attack); + game.options = { variant: 'Builder' }; + assert.ok(!query().destinations.some((d: any) => d.position === 'C1')); + assert.throws(() => move(game, attack.action), /Builder/); +}); + +test('Builder allows Persian conversion but excludes targets that would start a player battle', async () => { + const game = await fixture('base/cultural_influence_instant'); + game.current_player_index = 0; + const player = game.players[0]; + player.civilization = 'Persia'; + player.advances = [...new Set([...player.advances, 'Myths', 'Priesthood'])]; + player.resources.culture_tokens = 7; + player.units = []; + game.players[1].units = [ + { id: 0, position: 'B3', unit_type: 'Infantry' }, + { id: 1, position: 'B3', unit_type: 'Infantry' }, + ]; + game.players[1].next_unit_id = 2; + game.dice_roll_outcomes = [10]; + const conversion = (state: unknown) => + view(state).influence.find((i: any) => i.variant === 'Zoroastrianism'); + const attack = conversion(game); + assert.ok(attack); + assert.doesNotThrow(() => move(game, attack.action), 'Standard permits the conversion battle'); + game.options = { variant: 'Builder' }; + assert.equal(conversion(game), undefined); + assert.throws(() => move(game, attack.action), /Builder.*battle/); + + const barbarians = structuredClone(game); + barbarians.players[2].units = barbarians.players[1].units; + barbarians.players[2].next_unit_id = 2; + barbarians.players[1].units = []; + assert.ok(conversion(barbarians), 'conversion may still provoke a barbarian battle'); + assert.doesNotThrow(() => move(barbarians, conversion(barbarians).action)); + + game.players[1].units.pop(); + const peaceful = conversion(game); + assert.ok(peaceful, 'converting a lone unit does not start a battle'); + const after = move(game, peaceful.action); + assert.ok(after.players[0].units.some((u: any) => u.position === 'B3' && u.unit_type === 'Infantry')); + assert.equal((after.players[1].units ?? []).length, 0); +}); diff --git a/web-client/src/types.ts b/web-client/src/types.ts index 52a56dd5..96024238 100644 --- a/web-client/src/types.ts +++ b/web-client/src/types.ts @@ -64,7 +64,7 @@ export interface Playback { animate: boolean; } export interface Game { - options?: { length?: 'Standard' | 'Epic' }; + options?: { length?: 'Standard' | 'Epic'; variant?: 'Standard' | 'Builder' }; permanent_effects?: unknown[]; board_history?: { id: string; frames: BoardFrame[] }; state: unknown;