diff --git a/server/src/content/objectives/combat_objectives.rs b/server/src/content/objectives/combat_objectives.rs index aa52eb77..b031ac2a 100644 --- a/server/src/content/objectives/combat_objectives.rs +++ b/server/src/content/objectives/combat_objectives.rs @@ -318,7 +318,7 @@ pub(crate) fn resistance() -> Objective { let name = "Resistance"; Objective::builder( name, - "You won a battle against Barbarians in a city and killed at least 2 of their units.", + "You won a battle as defender and killed at least 2 enemy units.", ) .add_simple_persistent_event_listener( |event| &mut event.combat_end, @@ -326,8 +326,7 @@ pub(crate) fn resistance() -> Objective { |game, p, s| { let player = p.index; if s.is_winner(player) - && !s.opponent_is_human(player, game) - && s.battleground.is_city() + && s.defender.player == player && s.opponent(player).losses.amount() >= 2 { objective_is_ready(game.player_mut(player), name); @@ -449,3 +448,7 @@ pub(crate) fn sea_cleansing() -> Objective { ) .build() } + +#[cfg(test)] +#[path = "resistance_tests.rs"] +mod resistance_tests; diff --git a/server/src/content/objectives/non_combat.rs b/server/src/content/objectives/non_combat.rs index 6e38933b..c028ebcb 100644 --- a/server/src/content/objectives/non_combat.rs +++ b/server/src/content/objectives/non_combat.rs @@ -43,7 +43,11 @@ pub(crate) fn city_founder() -> Objective { |event| &mut event.found_city, 0, |game, player, p| { - if game.map.revealed_distance(capital_city_position(game, player.get(game)), *p).is_some_and(|distance| distance >= 5) { + if game + .map + .revealed_distance(capital_city_position(game, player.get(game)), *p) + .is_some_and(|distance| distance >= 5) + { objective_is_ready(player.get_mut(game), name); } }, @@ -72,32 +76,46 @@ pub(crate) fn magnificent_culture() -> Objective { let name = "Magnificent Culture"; Objective::builder( name, - "You just built a wonder OR \ - you built the only Wonder built during the last round.", + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.", ) .status_phase_check(|game, player| { - last_round(game).iter().any(|p| { - p.actions.iter().any(|a| { - a.items.iter().any(|i| { - matches!(&i.entry, ActionLogEntry::HandCard { - card: HandCard::Wonder(_), - from: HandCardLocation::Hand(p) , - to: HandCardLocation::PlayToKeep, - } if *p == player.index) - }) - }) - }) + let builders = wonder_builders(last_round(game).into_iter().flat_map(|turn| &turn.actions)); + !builders.is_empty() && builders.iter().all(|p| *p == player.index) }) .add_simple_persistent_event_listener( |event| &mut event.play_wonder_card, 0, |game, player, _| { - objective_is_ready(player.get_mut(game), name); + let builders = wonder_builders( + crate::log::linear_action_entries(game).into_iter(), + ); + if builders == [player.index] { + objective_is_ready(player.get_mut(game), name); + } }, ) .build() } +// Construction history remains valid even after a Wonder is captured or destroyed. +fn wonder_builders<'a>(actions: impl Iterator) -> Vec { + actions + .flat_map(|action| &action.items) + .filter_map(|item| match &item.entry { + ActionLogEntry::HandCard { + card: HandCard::Wonder(_), + from: HandCardLocation::Hand(player), + to: HandCardLocation::PlayToKeep, + } => Some(*player), + _ => None, + }) + .collect() +} + +#[cfg(test)] +#[path = "wonder_objective_tests.rs"] +mod wonder_objective_tests; + pub(crate) fn last_player_round(game: &Game, player: usize) -> Vec<&ActionLogAction> { last_round(game) .iter() diff --git a/server/src/content/objectives/resistance_tests.rs b/server/src/content/objectives/resistance_tests.rs new file mode 100644 index 00000000..846f0515 --- /dev/null +++ b/server/src/content/objectives/resistance_tests.rs @@ -0,0 +1,128 @@ +use crate::action::Action; +use crate::cache::Cache; +use crate::combat_listeners::{CombatResult, on_end_combat}; +use crate::combat_stats::{Battleground, CombatPlayerStats, CombatStats}; +use crate::content::persistent_events::{ + EventResponse, PersistentEventRequest, PersistentEventType, +}; +use crate::game::{Game, GameContext}; +use crate::game_data::GameData; +use crate::log::{ActionLogAction, current_turn_log_mut}; +use crate::playing_actions::PlayingAction; +use crate::position::Position; +use crate::unit::Units; + +fn qualifies( + defending: bool, + result: CombatResult, + losses: u8, + battleground: Battleground, + barbarians: bool, +) -> bool { + let mut data: serde_json::Value = serde_json::from_str(include_str!( + "../../../tests/test_games/tactics_cards/heavy_resistance.json" + )) + .unwrap(); + for p in data["players"].as_array_mut().unwrap() { + p["objective_cards"] = serde_json::json!([]); + p["action_cards"] = serde_json::json!([]); + p["advances"] = serde_json::json!(["Farming", "Mining", "Tactics"]); + } + data["players"][0]["objective_cards"] = serde_json::json!([28]); + if barbarians { + data["players"][1]["civilization"] = serde_json::json!("Barbarians"); + } + let data: GameData = serde_json::from_value(data).unwrap(); + let cache = Cache::new(&data.options); + let mut game = Game::from_data(data, cache, GameContext::Play); + game.log_index = 1; + current_turn_log_mut(&mut game) + .actions + .push(ActionLogAction::new( + Action::Playing(PlayingAction::EndTurn), + 0, + None, + 0, + )); + let mut stats = CombatStats::new( + battleground, + false, + CombatPlayerStats::new( + usize::from(defending), + Units { + infantry: 2, + ..Units::empty() + }, + Position::from_offset("C2"), + ), + CombatPlayerStats::new( + usize::from(!defending), + Units { + infantry: 3, + ..Units::empty() + }, + Position::from_offset("C1"), + ), + Some(result), + None, + ); + if defending { + stats.attacker.losses.infantry = losses; + } else { + stats.defender.losses.infantry = losses; + } + on_end_combat(&mut game, stats); + // Barbarian rewards resolve before combat objectives are checked. + while let Some(handler) = game.current_event_handler() { + let PersistentEventRequest::ResourceReward(request) = &handler.request else { + break; + }; + let response = Action::Response(EventResponse::ResourceReward( + request.reward.payment_options.default.clone(), + )); + let player = game.active_player(); + game = crate::game_api::execute(game, response, player); + } + game.events.iter().any(|event| matches!(&event.event_type, PersistentEventType::SelectObjectives(info) if info.shown_objective.as_deref() == Some("Resistance"))) +} + +#[test] +fn defiance_accepts_human_and_barbarian_attackers() { + for barbarians in [false, true] { + assert!(qualifies( + true, + CombatResult::DefenderWins, + 2, + Battleground::Land, + barbarians + )); + assert!(qualifies( + true, + CombatResult::DefenderWins, + 2, + Battleground::City, + barbarians + )); + assert!(!qualifies( + true, + CombatResult::DefenderWins, + 1, + Battleground::City, + barbarians + )); + assert!(!qualifies( + false, + CombatResult::AttackerWins, + 2, + Battleground::City, + barbarians + )); + assert!(!qualifies( + true, + CombatResult::AttackerWins, + 2, + Battleground::City, + barbarians + )); + } +} diff --git a/server/src/content/objectives/wonder_objective_tests.rs b/server/src/content/objectives/wonder_objective_tests.rs new file mode 100644 index 00000000..70761e6b --- /dev/null +++ b/server/src/content/objectives/wonder_objective_tests.rs @@ -0,0 +1,110 @@ +use super::*; +use crate::action::Action; +use crate::cache::Cache; +use crate::events::EventOrigin; +use crate::game::GameContext; +use crate::game_data::GameData; +use crate::log::{ActionLogItem, ActionLogRound, current_turn_log_mut}; +use crate::playing_actions::PlayingAction; +use crate::wonder::Wonder; + +fn game() -> Game { + let data: GameData = serde_json::from_str(include_str!( + "../../../tests/test_games/tactics_cards/heavy_resistance.json" + )) + .unwrap(); + let cache = Cache::new(&data.options); + let mut game = Game::from_data(data, cache, GameContext::Play); + game.log.last_mut().unwrap().rounds = vec![ActionLogRound { + round: 3, + turns: vec![ActionLogTurn { + turn_type: TurnType::Player(0), + actions: vec![], + }], + }]; + game +} + +fn build(game: &mut Game, player: usize) { + let mut action = ActionLogAction::new(Action::Playing(PlayingAction::EndTurn), player, None, 0); + action.items.push(ActionLogItem::new( + player, + ActionLogEntry::HandCard { + card: HandCard::Wonder(Wonder::Pyramids), + from: HandCardLocation::Hand(player), + to: HandCardLocation::PlayToKeep, + }, + EventOrigin::Ability("Build Wonder".into()), + vec![], + )); + current_turn_log_mut(game).actions.push(action); + game.log_index += 1; +} + +#[test] +fn only_builder_in_last_round_qualifies_even_with_multiple_wonders() { + let mut game = game(); + let objective = magnificent_culture(); + let check = objective.status_phase_check.unwrap(); + assert!(!check(&game, game.player(0))); + build(&mut game, 0); + assert!(check(&game, game.player(0))); + assert!(!check(&game, game.player(1))); + build(&mut game, 0); + assert!(check(&game, game.player(0))); + build(&mut game, 1); + assert!(!check(&game, game.player(0))); + assert!(!check(&game, game.player(1))); +} + +#[test] +fn first_construction_uses_history_not_current_ownership() { + let mut game = game(); + build(&mut game, 0); + let builders = |g: &Game| { + wonder_builders( + g.log + .iter() + .flat_map(|a| &a.rounds) + .flat_map(|r| &r.turns) + .flat_map(|t| &t.actions), + ) + }; + assert_eq!(builders(&game), [0]); + // No Wonder remains on the board; its construction still counts. + assert!(game.players.iter().all(|p| p.wonders_built.is_empty())); + build(&mut game, 1); + assert_eq!(builders(&game), [0, 1]); +} + +#[test] +fn construction_event_offers_only_the_first_wonder() { + use crate::content::persistent_events::{EventResponse, PersistentEventType}; + use crate::resource_pile::ResourcePile; + for earlier_builder in [None, Some(0), Some(1)] { + let data: GameData = serde_json::from_str(include_str!( + "../../../tests/test_games/wonders/pyramids.json" + )) + .unwrap(); + let cache = Cache::new(&data.options); + let mut game = Game::from_data(data, cache, GameContext::Play); + if let Some(player) = earlier_builder { + build(&mut game, player); + } + let game = crate::game_api::execute( + game, + Action::Playing(PlayingAction::WonderCard(Wonder::Pyramids)), + 0, + ); + let game = crate::game_api::execute( + game, + Action::Response(EventResponse::Payment(vec![ResourcePile::new( + 2, 3, 6, 0, 1, 0, 5, + )])), + 0, + ); + let offered = game.events.iter().any(|event| matches!(&event.event_type, + PersistentEventType::SelectObjectives(info) if info.shown_objective.as_deref() == Some("Magnificent Culture"))); + assert_eq!(offered, earlier_builder.is_none()); + } +} diff --git a/web-client/src/localization/da.json b/web-client/src/localization/da.json index 35698ea4..e8314626 100644 --- a/web-client/src/localization/da.json +++ b/web-client/src/localization/da.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Straks efter at have bygget spillets første vidunder, eller i statusfasen hvis du var den eneste spiller, der byggede vidundere i sidste runde.", + "You won a battle as defender and killed at least 2 enemy units.": "Du vandt et slag som forsvarer og dræbte mindst 2 fjendtlige enheder.", "# Arguments": "# Argumenter", "# Errors": "# Fejl", "# Panics": "# Panikker", diff --git a/web-client/src/localization/de.json b/web-client/src/localization/de.json index 94f482ec..df7d1efb 100644 --- a/web-client/src/localization/de.json +++ b/web-client/src/localization/de.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Sofort nach dem Bau des ersten Weltwunders im Spiel oder in der Statusphase, wenn nur du in der letzten Runde Weltwunder gebaut hast.", + "You won a battle as defender and killed at least 2 enemy units.": "Du hast als Verteidiger eine Schlacht gewonnen und mindestens 2 feindliche Einheiten vernichtet.", "# Arguments": "# Argumente", "# Errors": "# Fehler", "# Panics": "# Paniken", diff --git a/web-client/src/localization/el.json b/web-client/src/localization/el.json index 905b3396..c70a6c2c 100644 --- a/web-client/src/localization/el.json +++ b/web-client/src/localization/el.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Αμέσως μετά την κατασκευή του πρώτου Θαύματος στο παιχνίδι, ή στη Φάση Κατάστασης αν ήσουν ο μόνος παίκτης που κατασκεύασε Θαύματα στον τελευταίο γύρο.", + "You won a battle as defender and killed at least 2 enemy units.": "Κέρδισες μάχη ως αμυνόμενος και εξόντωσες τουλάχιστον 2 εχθρικές μονάδες.", "# Arguments": "# Ορίσματα", "# Errors": "# Σφάλματα", "# Panics": "# Πανικοί", diff --git a/web-client/src/localization/en.json b/web-client/src/localization/en.json index f11e3857..a13e2fc5 100644 --- a/web-client/src/localization/en.json +++ b/web-client/src/localization/en.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.", + "You won a battle as defender and killed at least 2 enemy units.": "You won a battle as defender and killed at least 2 enemy units.", "_blank": "_blank", "_tokens": "_tokens", "- all options are": "- all options are", diff --git a/web-client/src/localization/fa.json b/web-client/src/localization/fa.json index d9f562af..d7271b56 100644 --- a/web-client/src/localization/fa.json +++ b/web-client/src/localization/fa.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "بلافاصله پس از ساخت نخستین شگفتی بازی، یا در مرحله وضعیت اگر تنها بازیکنی بودید که در دور گذشته شگفتی ساخته است.", + "You won a battle as defender and killed at least 2 enemy units.": "در یک نبرد به‌عنوان مدافع پیروز شدید و دست‌کم ۲ واحد دشمن را از بین بردید.", "# Arguments": "# Arguments", "# Errors": "# Errors", "# Panics": "# Panics", diff --git a/web-client/src/localization/fr.json b/web-client/src/localization/fr.json index e2b4e166..78bab9ba 100644 --- a/web-client/src/localization/fr.json +++ b/web-client/src/localization/fr.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Immédiatement après avoir construit la première Merveille de la partie, ou en phase de statut si vous êtes le seul joueur à avoir construit des Merveilles lors de la dernière manche.", + "You won a battle as defender and killed at least 2 enemy units.": "Vous avez remporté une bataille en tant que défenseur et éliminé au moins 2 unités ennemies.", "# Arguments": "# Arguments", "# Errors": "# Erreurs", "# Panics": "# Paniques", diff --git a/web-client/src/localization/hi.json b/web-client/src/localization/hi.json index f1ed8051..6ec4dddf 100644 --- a/web-client/src/localization/hi.json +++ b/web-client/src/localization/hi.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "खेल का पहला अजूबा बनाने के तुरंत बाद, या स्थिति चरण में यदि पिछले दौर में केवल आपने अजूबे बनाए थे।", + "You won a battle as defender and killed at least 2 enemy units.": "आपने रक्षक के रूप में लड़ाई जीती और कम से कम 2 शत्रु इकाइयाँ नष्ट कीं।", "# Arguments": "# तर्क", "# Errors": "# त्रुटियाँ", "# Panics": "# घबराहटें", diff --git a/web-client/src/localization/it.json b/web-client/src/localization/it.json index 54b87ef7..d37695e1 100644 --- a/web-client/src/localization/it.json +++ b/web-client/src/localization/it.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Subito dopo aver costruito la prima Meraviglia della partita, oppure nella fase di stato se sei stato l'unico giocatore a costruire Meraviglie nell'ultimo round.", + "You won a battle as defender and killed at least 2 enemy units.": "Hai vinto una battaglia come difensore ed eliminato almeno 2 unità nemiche.", "# Arguments": "# Argomenti", "# Errors": "# Errori", "# Panics": "# Panici", diff --git a/web-client/src/localization/ko.json b/web-client/src/localization/ko.json index 0dd42aa2..c26b4241 100644 --- a/web-client/src/localization/ko.json +++ b/web-client/src/localization/ko.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "게임의 첫 불가사의를 건설한 직후, 또는 지난 라운드에 불가사의를 건설한 유일한 플레이어라면 상태 단계에 달성합니다.", + "You won a battle as defender and killed at least 2 enemy units.": "방어자로서 전투에서 승리하고 적 유닛을 최소 2개 제거했습니다.", "# Arguments": "# 인수", "# Errors": "# 오류", "# Panics": "# 패닉", diff --git a/web-client/src/localization/nl.json b/web-client/src/localization/nl.json index 66332dc1..24ed641f 100644 --- a/web-client/src/localization/nl.json +++ b/web-client/src/localization/nl.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Direct na het bouwen van het eerste wereldwonder in het spel, of in de statusfase als jij de enige speler was die in de laatste ronde wereldwonderen bouwde.", + "You won a battle as defender and killed at least 2 enemy units.": "Je won een gevecht als verdediger en doodde minstens 2 vijandelijke eenheden.", "# Arguments": "# Argumenten", "# Errors": "# Fouten", "# Panics": "# Panieks", diff --git a/web-client/src/localization/pl.json b/web-client/src/localization/pl.json index 9f01b6ce..57636354 100644 --- a/web-client/src/localization/pl.json +++ b/web-client/src/localization/pl.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Natychmiast po zbudowaniu pierwszego cudu w grze lub w fazie statusu, jeśli tylko ty zbudowałeś cuda w ostatniej rundzie.", + "You won a battle as defender and killed at least 2 enemy units.": "Wygrałeś bitwę jako obrońca i zniszczyłeś co najmniej 2 wrogie jednostki.", "# Arguments": "# Argumenty", "# Errors": "# Błędy", "# Panics": "# Paniki", diff --git a/web-client/src/localization/pt-BR.json b/web-client/src/localization/pt-BR.json index e94f7501..01a8d77e 100644 --- a/web-client/src/localization/pt-BR.json +++ b/web-client/src/localization/pt-BR.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Imediatamente após construir a primeira Maravilha da partida, ou na fase de status se você foi o único jogador a construir Maravilhas na última rodada.", + "You won a battle as defender and killed at least 2 enemy units.": "Você venceu uma batalha como defensor e eliminou pelo menos 2 unidades inimigas.", "# Arguments": "# Argumentos", "# Errors": "# Erros", "# Panics": "# Pânicos", diff --git a/web-client/src/localization/ro.json b/web-client/src/localization/ro.json index ebfa2a8f..33a7a7de 100644 --- a/web-client/src/localization/ro.json +++ b/web-client/src/localization/ro.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Imediat după construirea primei Minuni din joc sau în faza de statut dacă ai fost singurul jucător care a construit Minuni în ultima rundă.", + "You won a battle as defender and killed at least 2 enemy units.": "Ai câștigat o bătălie ca apărător și ai eliminat cel puțin 2 unități inamice.", "# Arguments": "# Argumente", "# Errors": "# Erori", "# Panics": "# Panici", diff --git a/web-client/src/localization/ru.json b/web-client/src/localization/ru.json index 5d54b44a..310c0dd0 100644 --- a/web-client/src/localization/ru.json +++ b/web-client/src/localization/ru.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Сразу после постройки первого чуда в игре или в фазе статуса, если только вы строили чудеса в последнем раунде.", + "You won a battle as defender and killed at least 2 enemy units.": "Вы выиграли битву, в качестве защитника, и уничтожили не менее 2 вражеских отрядов.", "# Arguments": "# Аргументы", "# Errors": "# Ошибки", "# Panics": "# Паники", diff --git a/web-client/src/localization/vi.json b/web-client/src/localization/vi.json index 6747bacf..612a3961 100644 --- a/web-client/src/localization/vi.json +++ b/web-client/src/localization/vi.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "Ngay sau khi xây Kỳ quan đầu tiên của ván chơi, hoặc trong giai đoạn trạng thái nếu bạn là người duy nhất xây Kỳ quan trong vòng vừa qua.", + "You won a battle as defender and killed at least 2 enemy units.": "Bạn thắng trận với vai trò phòng thủ và tiêu diệt ít nhất 2 đơn vị địch.", "# Arguments": "# Đối số", "# Errors": "# Lỗi", "# Panics": "# Hoảng loạn", diff --git a/web-client/src/localization/zh-CN.json b/web-client/src/localization/zh-CN.json index 3fd86937..8fa8874b 100644 --- a/web-client/src/localization/zh-CN.json +++ b/web-client/src/localization/zh-CN.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "建造本局首座奇迹后立即完成;或在状态阶段完成,条件是上一轮只有你建造过奇迹。", + "You won a battle as defender and killed at least 2 enemy units.": "你作为防守方在战斗中获胜,并消灭了至少2个敌方单位。", "_blank": "_blank", "_tokens": "_tokens", "- all options are": "- 所有选项均为", diff --git a/web-client/src/localization/zh-TW.json b/web-client/src/localization/zh-TW.json index a0039f14..470f49d6 100644 --- a/web-client/src/localization/zh-TW.json +++ b/web-client/src/localization/zh-TW.json @@ -1,4 +1,6 @@ { + "Immediately after constructing the first Wonder in the game, or during the Status Phase if you were the only player to construct Wonders in the last round.": "建造本局首座奇觀後立即完成;或在狀態階段完成,條件是上一輪只有你建造過奇觀。", + "You won a battle as defender and killed at least 2 enemy units.": "你作為防守方在戰鬥中獲勝,並消滅了至少2個敵方單位。", "# Arguments": "# 參數", "# Errors": "# 錯誤", "# Panics": "# 恐慌",