1pub mod activation_table;
2mod alt_costs;
3mod card_assembly;
4pub mod card_changed_words;
5pub mod card_clone_states;
6pub mod card_collection;
7pub mod card_collection_view;
8pub mod card_copy_service;
9pub mod card_damage_history;
10pub mod card_damage_map;
11pub mod card_factory;
12pub mod card_factory_util;
13pub mod card_lists;
14pub mod card_play_option;
15pub mod card_predicates;
16pub mod card_property;
17pub mod card_state;
18pub mod card_trait_changes;
19pub mod card_util;
20pub mod card_zone_table;
21pub mod counter_enum_type;
22pub mod counter_keyword_type;
23pub mod counter_type;
24pub mod damage_history;
25pub mod filter_constants;
26mod keyword_gen;
27pub mod perpetual;
28pub mod svar_cache;
29pub mod token;
30pub mod token_create_table;
31pub mod trait_card_trait_changes;
32pub mod valid_filter;
33use crate::card::activation_table::ActivationTable;
34use crate::core::HasSVars;
35pub use counter_type::CounterType;
36
37use crate::keyword::keyword_instance::Keyword as Kw;
39
40pub const KEYWORD_PLOTTED_PREFIX: &str = "Plotted:";
47
48pub const KEYWORD_WARP_EXILED: &str = "WarpExiled";
51
52use std::collections::{BTreeMap, HashMap, HashSet};
53
54use forge_carddb::CardRules;
55use forge_foundation::{CardTypeLine, ColorSet, CoreType, ManaCost, ZoneType};
56use serde::{Deserialize, Serialize};
57
58use crate::ability::activated::{parse_activated_ability, ActivatedAbility};
59use crate::card::perpetual::perpetual_record::PerpetualRecord;
60use crate::card::svar_cache::{ParsedSVar, ParsedSVarCache};
61use crate::cost::{parse_cost, Cost};
62use crate::game::GameState;
63use crate::ids::{CardId, PlayerId};
64use crate::parsing::{keys, parse_or_warn, Params, ParsedParams};
65use crate::replacement::{parse_replacement_effect, ReplacementEffect};
66use crate::spellability::{SpellAbility, TargetRestrictions};
67use crate::staticability::{parse_static_ability, StaticAbility};
68use crate::trigger::Trigger;
69
70fn colorless_color_set() -> ColorSet {
72 ColorSet::COLORLESS
73}
74
75fn parse_literal_target_count(expr: &str) -> Option<i32> {
76 if let Ok(n) = expr.trim().parse::<i32>() {
77 return Some(n);
78 }
79 expr.trim().strip_prefix('+')?.parse::<i32>().ok()
80}
81
82pub fn make_plotted_keyword(turn: u32) -> String {
83 format!("{KEYWORD_PLOTTED_PREFIX}{turn}")
84}
85
86pub fn parse_plotted_turn(kw: &str) -> Option<u32> {
88 kw.strip_prefix(KEYWORD_PLOTTED_PREFIX)
89 .and_then(|s| s.parse().ok())
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct CardOtherPart {
97 pub name: String,
98 #[serde(default)]
99 pub oracle_text: String,
100 #[serde(default)]
105 pub is_modal: bool,
106 pub type_line: CardTypeLine,
107 pub mana_cost: ManaCost,
108 pub color: ColorSet,
109 pub base_power: Option<i32>,
110 pub base_toughness: Option<i32>,
111 pub keywords: crate::keyword::keyword_collection::KeywordCollection,
112 pub abilities: Vec<String>,
113 pub triggers: Vec<Trigger>,
114 pub static_abilities: Vec<crate::staticability::StaticAbility>,
115 pub replacement_effects: Vec<crate::replacement::ReplacementEffect>,
116 pub svars: BTreeMap<String, String>,
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize, Default)]
120pub struct CardActionSpellSpec {
121 pub ability_index: usize,
122 pub has_valid_tgts: bool,
123 pub cost_contains_x: bool,
124 #[serde(default)]
125 pub target_chain: Vec<CardActionTargetSpec>,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct CardActionTargetSpec {
130 pub target_restrictions: TargetRestrictions,
131 pub min_targets: Option<i32>,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum_macros::EnumString)]
144#[strum(ascii_case_insensitive)]
145pub enum LoseControlCondition {
146 #[strum(serialize = "EOT", serialize = "UntilEOT", serialize = "EndOfTurn")]
148 EndOfTurn,
149 #[strum(serialize = "Untap", serialize = "UntilUntap", serialize = "NextUntap")]
151 NextUntap,
152 EndOfCombat,
154 LeavesPlay,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct AnimateState {
161 pub original_type_line: CardTypeLine,
162 pub original_base_power: Option<i32>,
163 pub original_base_toughness: Option<i32>,
164 pub original_color: ColorSet,
165 #[serde(default)]
169 pub original_keywords: Option<crate::keyword::keyword_collection::KeywordCollection>,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct CloneState {
175 #[serde(default)]
176 pub expires_at_cleanup: bool,
177 pub original_card_name: String,
178 #[serde(default)]
179 pub original_oracle_text: String,
180 pub original_type_line: CardTypeLine,
181 pub original_mana_cost: ManaCost,
182 pub original_color: ColorSet,
183 pub original_base_power: Option<i32>,
184 pub original_base_toughness: Option<i32>,
185 pub original_keywords: crate::keyword::keyword_collection::KeywordCollection,
186 pub original_abilities: Vec<String>,
187 pub original_activated_abilities: Vec<ActivatedAbility>,
188 pub original_triggers: Vec<Trigger>,
189 pub original_svars: BTreeMap<String, String>,
190 pub original_static_abilities: Vec<StaticAbility>,
191 pub original_replacement_effects: Vec<ReplacementEffect>,
192 #[serde(default)]
198 pub original_base_ability_count: usize,
199 #[serde(default)]
201 pub original_base_trigger_count: usize,
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct Card {
208 pub id: CardId,
209 pub card_name: String,
212 pub full_name: String,
216 #[serde(default)]
217 pub oracle_text: String,
218
219 pub owner: PlayerId,
221 pub controller: PlayerId,
222
223 pub zone: ZoneType,
225
226 pub type_line: CardTypeLine,
228
229 pub mana_cost: ManaCost,
231
232 pub color: ColorSet,
234
235 #[serde(default = "colorless_color_set")]
240 pub color_identity: ColorSet,
241
242 pub base_power: Option<i32>,
244 pub base_toughness: Option<i32>,
245 pub initial_loyalty: Option<String>,
247 pub power_modifier: i32,
250 pub toughness_modifier: i32,
251 pub perpetual_power_modifier: i32,
254 pub perpetual_toughness_modifier: i32,
255 #[serde(default)]
257 pub perpetual: Vec<PerpetualRecord>,
258 pub static_set_power: Option<i32>,
262 pub static_set_toughness: Option<i32>,
263 pub static_power_modifier: i32,
266 pub static_toughness_modifier: i32,
267
268 pub tapped: bool,
270 #[serde(skip)]
274 pub last_mana_produced: Option<Vec<u16>>,
275 pub flipped: bool,
276 pub face_down: bool,
277 pub has_morph: bool,
279 pub discarded: bool,
281 pub unearthed: bool,
283 pub class_level: i32,
285 pub paired_with: Option<CardId>,
287 pub manifested: bool,
289 pub cloaked: bool,
291 pub foretold: bool,
293 pub melded_with: Vec<CardId>,
296 pub foretold_cost_by_effect: bool,
298 pub is_bestowed: bool,
300 pub summoning_sick: bool,
301 #[serde(default)]
302 pub came_under_control_since_last_upkeep: bool,
303 pub exerted: bool,
304 pub damage: i32,
305 pub cast_from: Option<ZoneType>,
311
312 pub counters: BTreeMap<CounterType, i32>,
314
315 pub keywords: crate::keyword::keyword_collection::KeywordCollection,
318 pub granted_keywords: crate::keyword::keyword_collection::KeywordCollection,
321 #[serde(default)]
324 pub granted_svars: BTreeMap<String, String>,
325 pub static_added_subtypes: Vec<String>,
331 #[serde(skip)]
332 pub static_type_line_base: Option<CardTypeLine>,
333 #[serde(skip)]
334 pub changed_type_line_base: Option<CardTypeLine>,
335 #[serde(skip)]
336 pub changed_base_power: Option<Option<i32>>,
337 #[serde(skip)]
338 pub changed_base_toughness: Option<Option<i32>>,
339 pub pump_keywords: crate::keyword::keyword_collection::KeywordCollection,
342 pub pump_trigger_count: usize,
345
346 pub abilities: Vec<String>,
348 #[serde(default)]
350 pub action_spell_specs: Vec<CardActionSpellSpec>,
351 #[serde(default)]
353 pub action_spell_cost: Option<Cost>,
354 #[serde(default)]
356 pub ai_phyrexian_payment: Option<String>,
357 #[serde(default)]
359 pub spree_min_mode_cost: Option<i32>,
360
361 pub activated_abilities: Vec<ActivatedAbility>,
363 pub base_ability_count: usize,
366 pub base_trigger_count: usize,
369 pub changed_card_traits:
372 std::collections::BTreeMap<(i64, i64), card_trait_changes::CardTraitChanges>,
373 pub changed_card_traits_by_text:
376 std::collections::BTreeMap<(i64, i64), card_trait_changes::CardTraitChanges>,
377
378 pub static_abilities: Vec<StaticAbility>,
381
382 pub has_deathtouch_damage: bool,
384 pub cant_attack_static: bool,
387 pub cant_block_static: bool,
390
391 #[serde(default)]
393 pub turn_in_zone: u32,
394 pub entered_battlefield_this_turn: bool,
395 pub attacked_this_turn: bool,
396 pub started_turn_tapped: bool,
399
400 pub triggers: Vec<Trigger>,
402 pub svars: BTreeMap<String, String>,
404 #[serde(skip, default)]
405 pub parsed_svar_cache: ParsedSVarCache,
406
407 pub is_commander: bool,
410 pub move_to_command_zone: bool,
413 pub commander_cast_count: u32,
415
416 pub is_token: bool,
418
419 pub cast_with_flashback: bool,
422 pub cast_with_harmonize: bool,
425
426 pub replacement_effects: Vec<ReplacementEffect>,
429
430 pub attached_to: Option<CardId>,
434 pub attached_to_player: Option<PlayerId>,
435 pub attached_this_turn: bool,
438 pub attachments: Vec<CardId>,
440
441 pub remembered_cards: Vec<CardId>,
444 pub remembered_players: Vec<PlayerId>,
446 pub imprinted_cards: Vec<CardId>,
448 pub gain_control_targets: Vec<CardId>,
450 pub until_leaves_battlefield: Vec<CardId>,
452 pub exiled_cards: Vec<CardId>,
454 pub paid_cost_exiled_cards: Vec<CardId>,
457 pub haunted_by: Vec<CardId>,
459 pub haunting: Option<CardId>,
461 pub chosen_map: HashMap<PlayerId, Vec<CardId>>,
463 pub remembered_cmc: Vec<i32>,
465 #[serde(default)]
466 pub stored_rolls: Vec<i32>,
467 pub effect_source: Option<CardId>,
469 #[serde(default)]
470 pub clone_origin: Option<CardId>,
471 #[serde(default)]
472 pub copied_permanent: Option<CardId>,
473 #[serde(skip, default)]
477 pub cast_sa: Option<Box<SpellAbility>>,
478 #[serde(default)]
482 pub chosen_charm_modes: HashMap<String, i32>,
483 #[serde(skip, default)]
489 pub remembered_lki_cards: Vec<Card>,
490 #[serde(default)]
494 pub lose_control_condition: Option<LoseControlCondition>,
495 pub temp_effect_until_eot: bool,
497 pub temp_effect_host: Option<CardId>,
500 pub forget_on_moved_origin: Option<ZoneType>,
502 pub exile_when_no_remembered: bool,
504 pub exiled_by: Option<CardId>,
508
509 pub original_controller_eot: Option<PlayerId>,
511
512 pub is_transformed: bool,
515 pub other_part: Option<CardOtherPart>,
517
518 pub set_code: Option<String>,
520
521 pub card_number: Option<String>,
525
526 #[serde(default)]
527 pub paper_foil: bool,
528 #[serde(default)]
529 pub cosmetics: Option<forge_foundation::sealed_product::card_cosmetics::CardCosmetics>,
530
531 pub phased_out: bool,
533
534 pub regeneration_shields: i32,
537
538 pub kicked: bool,
542 pub monstrous: bool,
545
546 pub chosen_colors: Vec<String>,
548 pub chosen_cards: Vec<CardId>,
550
551 pub animate_state: Option<AnimateState>,
553 pub clone_state: Option<CloneState>,
555
556 pub chosen_type: Option<String>,
559 pub chosen_type2: Option<String>,
561 pub noted_types: Vec<String>,
563 pub named_cards: Vec<String>,
565 pub chosen_number: Option<i32>,
567 pub chosen_number_controller: Option<PlayerId>,
568 pub chosen_number_revealed: bool,
569 pub chosen_mode: Option<String>,
570 pub chosen_player: Option<PlayerId>,
572 pub chosen_player_controller: Option<PlayerId>,
574 pub chosen_type_controller: Option<PlayerId>,
576 pub chosen_player_revealed: bool,
578 pub chosen_type_revealed: bool,
580 pub promised_gift: Option<PlayerId>,
582 pub attraction_lights: Vec<u32>,
584 pub sector: Option<String>,
586 pub chosen_sector: Option<String>,
588 pub sprocket: i32,
590 pub chosen_even_odd: Option<String>,
592 pub detained: bool,
594 pub attacking_player: Option<PlayerId>,
596 pub goaded_by: Option<PlayerId>,
598 pub damage_prevention: i32,
600 pub assigned_damage: i32,
602 pub must_block: bool,
604 pub encoded_cards: Vec<CardId>,
606 pub damage_sources_this_turn: Vec<CardId>,
609 pub total_damage_done_this_turn: i32,
613 pub lki_power: Option<i32>,
617 pub lki_toughness: Option<i32>,
620 pub lki_counters: Option<std::collections::BTreeMap<CounterType, i32>>,
623 #[serde(skip)]
626 pub damage_history: damage_history::DamageHistory,
627 pub must_block_cards: Vec<CardId>,
629 pub etb_counters_p1p1: i32,
631 pub colors_spent_to_cast: u16,
634 pub paying_mana_to_cast: Vec<u16>,
637 pub chosen_modes: Option<Vec<usize>>,
640 pub strive_extra_targets: u32,
642 pub became_target_this_turn: bool,
644 pub temp_controllers: Vec<PlayerId>,
646 pub may_look_at: Vec<PlayerId>,
648 pub may_play: Vec<PlayerId>,
650 pub can_block_additional: i32,
652 pub can_block_any: bool,
654 pub cant_have_keywords: HashSet<String>,
656 pub intensity: i32,
658 pub surveilled: bool,
660 pub milled: bool,
662 pub visited_this_turn: bool,
664 pub times_crewed_this_turn: u32,
666 pub is_crewed: bool,
668 pub ignore_legend_rule_flag: bool,
670 pub ability_activated_this_turn: u32,
672 pub ability_resolved_this_turn: u32,
674 #[serde(skip)]
676 pub number_turn_activations: ActivationTable,
677 #[serde(skip)]
679 pub number_game_activations: ActivationTable,
680 #[serde(skip)]
682 pub number_ability_resolved: ActivationTable,
683 pub planeswalker_abilities_activated: u32,
685 pub planeswalker_activation_limit_used: bool,
687 pub chosen_modes_turn: Option<u32>,
689 pub enlisted_this_combat: bool,
691 pub activations_this_game: std::collections::BTreeMap<usize, u32>,
693 pub is_renowned: bool,
696 pub zone_timestamp: u64,
700
701 #[serde(skip)]
704 trait_base_activated_abilities: Option<Vec<ActivatedAbility>>,
705 #[serde(skip)]
706 trait_base_triggers: Option<Vec<Trigger>>,
707 #[serde(skip)]
708 trait_base_replacement_effects: Option<Vec<ReplacementEffect>>,
709 #[serde(skip)]
710 trait_base_static_abilities: Option<Vec<StaticAbility>>,
711 #[serde(skip)]
712 trait_base_keywords: Option<crate::keyword::keyword_collection::KeywordCollection>,
713}
714
715pub type CardInstance = Card;
717
718impl Card {
719 pub fn new(
720 id: CardId,
721 card_name: String,
722 owner: PlayerId,
723 type_line: CardTypeLine,
724 mana_cost: ManaCost,
725 color: ColorSet,
726 base_power: Option<i32>,
727 base_toughness: Option<i32>,
728 keywords: Vec<String>,
729 abilities: Vec<String>,
730 ) -> Self {
731 let activated_abilities: Vec<ActivatedAbility> = abilities
733 .iter()
734 .enumerate()
735 .filter_map(|(i, raw)| {
736 parse_or_warn(parse_activated_ability(raw, i), "ActivatedAbility", raw)
737 })
738 .collect();
739
740 let replacement_effects: Vec<ReplacementEffect> = abilities
743 .iter()
744 .filter_map(|raw| {
745 parse_or_warn(parse_replacement_effect(raw), "ReplacementEffect", raw)
746 })
747 .collect();
748
749 let static_abilities: Vec<StaticAbility> = abilities
752 .iter()
753 .filter_map(|raw| parse_or_warn(parse_static_ability(raw), "StaticAbility", raw))
754 .collect();
755
756 let full_name = card_name.clone();
757 let color_identity = color;
758 let mut card = Card {
759 id,
760 card_name,
761 full_name,
762 oracle_text: String::new(),
763 owner,
764 controller: owner,
765 zone: ZoneType::None,
766 type_line,
767 mana_cost,
768 color,
769 color_identity,
770 base_power,
771 base_toughness,
772 initial_loyalty: None,
773 power_modifier: 0,
774 toughness_modifier: 0,
775 perpetual_power_modifier: 0,
776 perpetual_toughness_modifier: 0,
777 perpetual: Vec::new(),
778 static_set_power: None,
779 static_set_toughness: None,
780 static_power_modifier: 0,
781 static_toughness_modifier: 0,
782 tapped: false,
783 last_mana_produced: None,
784 flipped: false,
785 face_down: false,
786 has_morph: false,
787 discarded: false,
788 unearthed: false,
789 class_level: 1,
790 paired_with: None,
791 manifested: false,
792 cloaked: false,
793 foretold: false,
794 foretold_cost_by_effect: false,
795 melded_with: Vec::new(),
796 is_bestowed: false,
797 summoning_sick: true,
798 came_under_control_since_last_upkeep: false,
799 exerted: false,
800 damage: 0,
801 cast_from: None,
802 counters: BTreeMap::new(),
803 keywords: crate::keyword::keyword_collection::KeywordCollection::from_strings(
804 &keywords,
805 ),
806 granted_keywords: crate::keyword::keyword_collection::KeywordCollection::new(),
807 granted_svars: BTreeMap::new(),
808 static_added_subtypes: Vec::new(),
809 static_type_line_base: None,
810 changed_type_line_base: None,
811 changed_base_power: None,
812 changed_base_toughness: None,
813 pump_keywords: crate::keyword::keyword_collection::KeywordCollection::new(),
814 pump_trigger_count: 0,
815 abilities,
816 action_spell_specs: Vec::new(),
817 action_spell_cost: None,
818 ai_phyrexian_payment: None,
819 spree_min_mode_cost: None,
820 activated_abilities,
821 base_ability_count: 0,
822 base_trigger_count: 0,
823 changed_card_traits: std::collections::BTreeMap::new(),
824 changed_card_traits_by_text: std::collections::BTreeMap::new(),
825 static_abilities,
826 has_deathtouch_damage: false,
827 cant_attack_static: false,
828 cant_block_static: false,
829 turn_in_zone: 0,
830 entered_battlefield_this_turn: false,
831 attacked_this_turn: false,
832 started_turn_tapped: false,
833 triggers: Vec::new(),
834 svars: BTreeMap::new(),
835 parsed_svar_cache: ParsedSVarCache::default(),
836 is_commander: false,
837 move_to_command_zone: false,
838 commander_cast_count: 0,
839 is_token: false,
840 cast_with_flashback: false,
841 cast_with_harmonize: false,
842 replacement_effects,
843 attached_to: None,
844 attached_to_player: None,
845 attached_this_turn: false,
846 attachments: Vec::new(),
847 remembered_cards: Vec::new(),
848 remembered_players: Vec::new(),
849 imprinted_cards: Vec::new(),
850 gain_control_targets: Vec::new(),
851 until_leaves_battlefield: Vec::new(),
852 exiled_cards: Vec::new(),
853 paid_cost_exiled_cards: Vec::new(),
854 haunted_by: Vec::new(),
855 haunting: None,
856 chosen_map: HashMap::new(),
857 remembered_cmc: Vec::new(),
858 stored_rolls: Vec::new(),
859 effect_source: None,
860 clone_origin: None,
861 copied_permanent: None,
862 cast_sa: None,
863 chosen_charm_modes: HashMap::new(),
864 remembered_lki_cards: Vec::new(),
865 lose_control_condition: None,
866 temp_effect_until_eot: false,
867 temp_effect_host: None,
868 forget_on_moved_origin: None,
869 exile_when_no_remembered: false,
870 exiled_by: None,
871 original_controller_eot: None,
872 is_transformed: false,
873 other_part: None,
874 set_code: None,
875 card_number: None,
876 paper_foil: false,
877 cosmetics: None,
878 phased_out: false,
879 regeneration_shields: 0,
880 kicked: false,
881 monstrous: false,
882 chosen_colors: Vec::new(),
883 chosen_cards: Vec::new(),
884 animate_state: None,
885 clone_state: None,
886 chosen_type: None,
887 chosen_type2: None,
888 noted_types: Vec::new(),
889 named_cards: Vec::new(),
890 chosen_number: None,
891 chosen_number_controller: None,
892 chosen_number_revealed: false,
893 chosen_mode: None,
894 chosen_player: None,
895 chosen_player_controller: None,
896 chosen_type_controller: None,
897 chosen_player_revealed: false,
898 chosen_type_revealed: false,
899 promised_gift: None,
900 attraction_lights: Vec::new(),
901 sector: None,
902 chosen_sector: None,
903 sprocket: 0,
904 chosen_even_odd: None,
905 detained: false,
906 attacking_player: None,
907 goaded_by: None,
908 damage_prevention: 0,
909 assigned_damage: 0,
910 must_block: false,
911 encoded_cards: Vec::new(),
912 damage_sources_this_turn: Vec::new(),
913 total_damage_done_this_turn: 0,
914 lki_power: None,
915 lki_toughness: None,
916 lki_counters: None,
917 damage_history: damage_history::DamageHistory::default(),
918 must_block_cards: Vec::new(),
919 etb_counters_p1p1: 0,
920 colors_spent_to_cast: 0,
921 paying_mana_to_cast: Vec::new(),
922 chosen_modes: None,
923 strive_extra_targets: 0,
924 became_target_this_turn: false,
925 temp_controllers: Vec::new(),
926 may_look_at: Vec::new(),
927 may_play: Vec::new(),
928 can_block_additional: 0,
929 can_block_any: false,
930 cant_have_keywords: HashSet::new(),
931 intensity: 0,
932 surveilled: false,
933 milled: false,
934 visited_this_turn: false,
935 times_crewed_this_turn: 0,
936 is_crewed: false,
937 ignore_legend_rule_flag: false,
938 ability_activated_this_turn: 0,
939 ability_resolved_this_turn: 0,
940 number_turn_activations: ActivationTable::default(),
941 number_game_activations: ActivationTable::default(),
942 number_ability_resolved: ActivationTable::default(),
943 planeswalker_abilities_activated: 0,
944 planeswalker_activation_limit_used: false,
945 chosen_modes_turn: None,
946 enlisted_this_combat: false,
947 activations_this_game: std::collections::BTreeMap::new(),
948 is_renowned: false,
949 zone_timestamp: 0,
950 trait_base_activated_abilities: None,
951 trait_base_triggers: None,
952 trait_base_replacement_effects: None,
953 trait_base_static_abilities: None,
954 trait_base_keywords: None,
955 };
956
957 card.generate_basic_land_mana_abilities();
959 card.generate_keyword_abilities();
960 card.generate_keyword_triggers();
961 crate::card::card_state::update_types(&mut card);
962 crate::card::card_state::update_keywords_cache(&mut card);
963 crate::card::card_state::calculate_perpetual_adjusted_mana_cost(&mut card);
964 card.refresh_action_specs();
965 card.base_ability_count = card.activated_abilities.len();
967 card.base_trigger_count = card.triggers.len();
968 card
969 }
970
971 pub fn clone_for_parity_snapshot(&self) -> Self {
972 let mut out = self.clone();
973 out.abilities.clear();
974 out.activated_abilities.clear();
975 out.triggers.clear();
976 for static_ability in &mut out.static_abilities {
977 *static_ability.base = crate::card_trait_base::CardTraitBase::default();
978 }
979 out.replacement_effects.clear();
980 out.cast_sa = None;
981 out.trait_base_activated_abilities = None;
982 out.trait_base_triggers = None;
983 out.trait_base_replacement_effects = None;
984 out.trait_base_static_abilities = None;
985 out.trait_base_keywords = None;
986 out
987 }
988
989 pub fn from_rules(rules: &CardRules, owner: PlayerId) -> Self {
1003 card_factory::build_from_rules(rules, owner)
1004 }
1005
1006 pub fn power(&self) -> i32 {
1014 let base = self
1015 .static_set_power
1016 .unwrap_or(self.base_power.unwrap_or(0));
1017 base + self.static_power_modifier
1018 + self.power_modifier
1019 + self.perpetual_power_modifier
1020 + self.counter_count(&CounterType::P1P1)
1021 - self.counter_count(&CounterType::M1M1)
1022 }
1023
1024 pub fn toughness(&self) -> i32 {
1026 let base = self
1027 .static_set_toughness
1028 .unwrap_or(self.base_toughness.unwrap_or(0));
1029 base + self.static_toughness_modifier
1030 + self.toughness_modifier
1031 + self.perpetual_toughness_modifier
1032 + self.counter_count(&CounterType::P1P1)
1033 - self.counter_count(&CounterType::M1M1)
1034 }
1035
1036 pub fn lethal_damage(&self) -> bool {
1037 self.damage >= self.toughness()
1038 }
1039
1040 pub fn can_be_dealt_damage(&self) -> bool {
1041 self.zone == ZoneType::Battlefield
1042 && (self.is_creature()
1043 || self.type_line.is_planeswalker()
1044 || self.type_line.core_types.contains(&CoreType::Battle))
1045 }
1046
1047 pub fn is_creature(&self) -> bool {
1048 !self.is_bestowed && self.type_line.is_creature()
1049 }
1050
1051 pub fn is_land(&self) -> bool {
1052 self.type_line.is_land()
1053 }
1054
1055 pub fn is_permanent(&self) -> bool {
1056 self.type_line.is_permanent()
1057 }
1058
1059 pub fn update_types(&mut self) {
1061 crate::card::card_state::update_types(self);
1062 }
1063
1064 pub fn update_types_for_view(&mut self) {
1065 crate::card::card_state::update_types_for_view(self);
1066 }
1067
1068 pub fn add_type(&mut self, ty: &str) {
1069 crate::card::card_state::add_type(self, ty);
1070 self.update_types();
1071 self.update_types_for_view();
1072 }
1073
1074 pub fn remove_type(&mut self, ty: &str) {
1075 crate::card::card_state::remove_type(self, ty);
1076 self.update_types();
1077 self.update_types_for_view();
1078 }
1079
1080 pub fn remove_card_types(&mut self) {
1081 crate::card::card_state::remove_card_types(self);
1082 self.update_types();
1083 self.update_types_for_view();
1084 }
1085
1086 pub fn set_type(&mut self, type_line: &str) {
1087 crate::card::card_state::set_type(self, type_line);
1088 self.update_types();
1089 self.update_types_for_view();
1090 }
1091
1092 pub fn set_type_line(&mut self, type_line: CardTypeLine) {
1093 self.type_line = type_line;
1094 self.update_types();
1095 self.update_types_for_view();
1096 }
1097
1098 pub fn add_color(&mut self, color: ColorSet) {
1099 crate::card::card_state::add_color(self, color);
1100 }
1101
1102 pub fn has_intrinsic_keyword(&self, keyword: &str) -> bool {
1103 crate::card::card_state::has_intrinsic_keyword(self, keyword)
1104 }
1105
1106 pub fn add_intrinsic_keyword(&mut self, keyword: &str) -> bool {
1107 let changed = crate::card::card_state::add_intrinsic_keyword(self, keyword);
1108 if changed {
1109 crate::card::card_state::update_keywords_cache(self);
1110 }
1111 changed
1112 }
1113
1114 pub fn add_intrinsic_keywords<'a>(
1115 &mut self,
1116 keywords: impl IntoIterator<Item = &'a str>,
1117 ) -> bool {
1118 let changed = crate::card::card_state::add_intrinsic_keywords(self, keywords);
1119 if changed {
1120 crate::card::card_state::update_keywords_cache(self);
1121 }
1122 changed
1123 }
1124
1125 pub fn remove_intrinsic_keyword(&mut self, keyword: &str) -> bool {
1126 let changed = crate::card::card_state::remove_intrinsic_keyword(self, keyword);
1127 if changed {
1128 crate::card::card_state::update_keywords_cache(self);
1129 }
1130 changed
1131 }
1132
1133 pub fn has_spell_ability(&self, sa: &SpellAbility) -> bool {
1134 crate::card::card_state::has_spell_ability(self, sa)
1135 }
1136
1137 pub fn add_spell_ability(&mut self, sa: &SpellAbility) -> bool {
1138 let added = crate::card::card_state::add_spell_ability(self, sa);
1139 self.refresh_action_specs();
1140 added
1141 }
1142
1143 pub fn has_trigger(&self, trigger_id: u32) -> bool {
1144 crate::card::card_state::has_trigger(self, trigger_id)
1145 }
1146
1147 pub fn add_trigger(&mut self, trig: Trigger) -> bool {
1148 crate::card::card_state::add_trigger(self, trig)
1149 }
1150
1151 pub fn clear_pump_triggers(&mut self) {
1152 let count = self.pump_trigger_count;
1153 if count == 0 {
1154 return;
1155 }
1156 let new_len = self
1157 .triggers
1158 .len()
1159 .saturating_sub(count)
1160 .max(self.base_trigger_count);
1161 self.triggers.truncate(new_len);
1162 self.pump_trigger_count = 0;
1163 }
1164
1165 pub fn copiable_triggers(&self) -> Vec<Trigger> {
1166 self.trait_base_triggers
1167 .clone()
1168 .unwrap_or_else(|| self.triggers.clone())
1169 }
1170
1171 pub fn copiable_replacement_effects(&self) -> Vec<ReplacementEffect> {
1172 self.trait_base_replacement_effects
1173 .clone()
1174 .unwrap_or_else(|| self.replacement_effects.clone())
1175 }
1176
1177 pub fn add_static_ability(&mut self, st_ab: StaticAbility) -> bool {
1178 crate::card::card_state::add_static_ability(self, st_ab)
1179 }
1180
1181 pub fn remove_static_ability(&mut self, mode: crate::staticability::StaticMode) -> bool {
1182 crate::card::card_state::remove_static_ability(self, mode)
1183 }
1184
1185 pub fn add_replacement_effect(&mut self, re: ReplacementEffect) -> bool {
1186 crate::card::card_state::add_replacement_effect(self, re)
1187 }
1188
1189 pub fn has_replacement_effect(&self) -> bool {
1190 crate::card::card_state::has_replacement_effect(self)
1191 }
1192
1193 pub fn has_s_var(&self, key: &str) -> bool {
1194 crate::card::card_state::has_s_var(self, key)
1195 }
1196
1197 pub fn get_s_var(&self, key: &str) -> Option<&str> {
1198 self.svars
1199 .get(key)
1200 .or_else(|| self.granted_svars.get(key))
1201 .map(String::as_str)
1202 }
1203
1204 pub fn parsed_s_var(&mut self, key: &str) -> Option<ParsedSVar> {
1205 let raw = self.get_s_var(key)?.to_string();
1206 Some(self.parsed_svar_cache.get_or_parse(key, &raw).clone())
1207 }
1208
1209 pub fn remove_s_var(&mut self, key: &str) {
1210 crate::card::card_state::remove_s_var(self, key);
1211 self.parsed_svar_cache.remove(key);
1212 self.refresh_action_specs_after_svar_change();
1213 }
1214
1215 pub fn set_s_var(&mut self, key: impl Into<String>, value: impl Into<String>) {
1216 let key = key.into();
1217 self.parsed_svar_cache.remove(&key);
1218 self.svars.insert(key, value.into());
1219 self.refresh_action_specs_after_svar_change();
1220 }
1221
1222 pub fn set_s_var_if_absent(&mut self, key: impl Into<String>, value: impl Into<String>) {
1223 let key = key.into();
1224 if self.svars.contains_key(&key) {
1225 return;
1226 }
1227 self.svars.insert(key, value.into());
1228 self.refresh_action_specs_after_svar_change();
1229 }
1230
1231 pub fn set_svars_map(&mut self, svars: BTreeMap<String, String>) {
1232 self.svars = svars;
1233 self.parsed_svar_cache.clear();
1234 self.refresh_action_specs();
1235 }
1236
1237 pub fn copy_from_card_state(&mut self, source: &Card) {
1238 crate::card::card_state::copy_from(source, self);
1239 }
1240
1241 pub fn copy_from(&mut self, source: &Card) {
1242 self.copy_from_card_state(source);
1243 }
1244
1245 pub fn add_abilities_from(&mut self, source: &Card) {
1246 crate::card::card_state::add_abilities_from(source, self);
1247 }
1248
1249 pub fn has_property(&self, property: &str) -> bool {
1250 crate::card::card_state::has_property(self, property)
1251 }
1252
1253 pub fn reset_original_host(&mut self) {
1254 crate::card::card_state::reset_original_host(self);
1255 }
1256
1257 pub fn update_changed_text(&mut self) {
1258 crate::card::card_state::update_changed_text(self);
1259 }
1260
1261 pub fn update_keywords_cache(&mut self) {
1262 crate::card::card_state::update_keywords_cache(self);
1263 }
1264
1265 pub fn change_text_intrinsic(&mut self) {
1266 crate::card::card_state::change_text_intrinsic(self);
1267 }
1268
1269 pub fn has_chapter(&self) -> bool {
1270 crate::card::card_state::has_chapter(self)
1271 }
1272
1273 pub fn get_final_chapter_nr(&self) -> i32 {
1274 crate::card::card_state::get_final_chapter_nr(self)
1275 }
1276
1277 pub fn sunburst_count(&self) -> i32 {
1281 use forge_foundation::mana::ManaAtom;
1282 let mut count = 0;
1283 for &bit in &[
1284 ManaAtom::WHITE,
1285 ManaAtom::BLUE,
1286 ManaAtom::BLACK,
1287 ManaAtom::RED,
1288 ManaAtom::GREEN,
1289 ] {
1290 if (self.colors_spent_to_cast & bit) != 0 {
1291 count += 1;
1292 }
1293 }
1294 count
1295 }
1296
1297 pub fn has_keyword(&self, kw: &str) -> bool {
1298 crate::card::card_state::has_keyword(self, kw)
1299 }
1300
1301 pub fn has_keyword_enum(&self, kw: Kw) -> bool {
1306 if self
1307 .cant_have_keywords
1308 .contains(&kw.display_name().to_ascii_lowercase())
1309 {
1310 return false;
1311 }
1312 self.keywords.contains_keyword(kw)
1313 || self.granted_keywords.contains_keyword(kw)
1314 || self.pump_keywords.contains_keyword(kw)
1315 }
1316
1317 pub fn has_haste(&self) -> bool {
1318 self.has_keyword_enum(crate::keyword::keyword_instance::Keyword::Haste)
1319 }
1320
1321 pub fn has_flying(&self) -> bool {
1322 self.has_keyword_enum(crate::keyword::keyword_instance::Keyword::Flying)
1323 }
1324
1325 pub fn has_reach(&self) -> bool {
1326 self.has_keyword_enum(Kw::Reach)
1327 }
1328
1329 pub fn has_first_strike(&self) -> bool {
1330 self.has_keyword_enum(Kw::FirstStrike)
1331 }
1332
1333 pub fn has_double_strike(&self) -> bool {
1334 self.has_keyword_enum(Kw::DoubleStrike)
1335 }
1336
1337 pub fn has_trample(&self) -> bool {
1338 self.has_keyword_enum(Kw::Trample)
1339 }
1340
1341 pub fn has_deathtouch(&self) -> bool {
1342 self.has_keyword_enum(Kw::Deathtouch)
1343 }
1344
1345 pub fn has_lifelink(&self) -> bool {
1346 self.has_keyword_enum(Kw::Lifelink)
1347 }
1348
1349 pub fn has_vigilance(&self) -> bool {
1350 self.has_keyword_enum(Kw::Vigilance)
1351 }
1352
1353 pub fn has_defender(&self) -> bool {
1354 self.has_keyword_enum(Kw::Defender)
1355 }
1356
1357 pub fn has_hexproof(&self) -> bool {
1358 self.has_keyword_enum(Kw::Hexproof)
1359 }
1360
1361 pub fn has_shroud(&self) -> bool {
1362 self.has_keyword_enum(Kw::Shroud)
1363 }
1364
1365 pub fn has_menace(&self) -> bool {
1366 self.has_keyword_enum(Kw::Menace)
1367 }
1368
1369 pub fn has_fear(&self) -> bool {
1370 self.has_keyword_enum(Kw::Fear)
1371 }
1372
1373 pub fn has_intimidate(&self) -> bool {
1374 self.has_keyword_enum(Kw::Intimidate)
1375 }
1376
1377 pub fn has_shadow(&self) -> bool {
1378 self.has_keyword_enum(Kw::Shadow)
1379 }
1380
1381 pub fn has_skulk(&self) -> bool {
1382 self.has_keyword_enum(Kw::Skulk)
1383 }
1384
1385 pub fn has_horsemanship(&self) -> bool {
1386 self.has_keyword_enum(Kw::Horsemanship)
1387 }
1388
1389 pub fn has_indestructible(&self) -> bool {
1390 self.has_keyword_enum(Kw::Indestructible)
1391 }
1392
1393 pub fn has_infect(&self) -> bool {
1394 self.has_keyword_enum(Kw::Infect)
1395 }
1396
1397 pub fn has_wither(&self) -> bool {
1398 self.has_keyword_enum(Kw::Wither)
1399 }
1400
1401 pub fn has_prowess(&self) -> bool {
1402 self.has_keyword_enum(Kw::Prowess)
1403 }
1404
1405 pub fn has_rebound(&self) -> bool {
1406 self.has_keyword_enum(Kw::Rebound)
1407 }
1408
1409 pub fn has_hexproof_from(&self, color: &str) -> bool {
1411 let target = format!("Hexproof from {color}");
1412 self.keywords.contains_string_ignore_case(&target)
1413 || self.granted_keywords.contains_string_ignore_case(&target)
1414 }
1415
1416 pub fn get_toxic_count(&self) -> Option<i32> {
1418 self.get_keyword_cost("Toxic").and_then(|s| s.parse().ok())
1419 }
1420
1421 pub fn has_storm(&self) -> bool {
1423 self.has_keyword_enum(Kw::Storm)
1424 }
1425
1426 pub fn has_cascade(&self) -> bool {
1427 self.has_keyword_enum(Kw::Cascade)
1428 }
1429
1430 pub fn mana_value(&self) -> i32 {
1432 self.mana_cost.cmc()
1433 }
1434
1435 pub fn has_protection_from(&self, quality: &str) -> bool {
1437 let target = format!("Protection from {quality}");
1438 self.keywords.contains_string_ignore_case(&target)
1439 || self.granted_keywords.contains_string_ignore_case(&target)
1440 }
1441
1442 pub fn get_protections(&self) -> Vec<String> {
1444 let mut prots = Vec::new();
1445 for kw in self
1446 .keywords
1447 .iter_strings()
1448 .chain(self.granted_keywords.iter_strings())
1449 {
1450 if let Some(from) = kw.strip_prefix("Protection from ") {
1451 prots.push(from.to_lowercase());
1452 }
1453 }
1454 prots
1455 }
1456
1457 pub fn is_protected_from(&self, source: &Card) -> bool {
1461 for prot in self.get_protections() {
1462 match prot.as_str() {
1463 "white" => {
1464 if source.color.has_white() {
1465 return true;
1466 }
1467 }
1468 "blue" => {
1469 if source.color.has_blue() {
1470 return true;
1471 }
1472 }
1473 "black" => {
1474 if source.color.has_black() {
1475 return true;
1476 }
1477 }
1478 "red" => {
1479 if source.color.has_red() {
1480 return true;
1481 }
1482 }
1483 "green" => {
1484 if source.color.has_green() {
1485 return true;
1486 }
1487 }
1488 "colorless" => {
1489 if source.color.is_colorless() {
1490 return true;
1491 }
1492 }
1493 "artifacts" => {
1494 if source.type_line.is_artifact() {
1495 return true;
1496 }
1497 }
1498 "creatures" => {
1499 if source.type_line.is_creature() {
1500 return true;
1501 }
1502 }
1503 "enchantments" => {
1504 if source.type_line.is_enchantment() {
1505 return true;
1506 }
1507 }
1508 _ => {}
1509 }
1510 }
1511 false
1512 }
1513
1514 pub fn can_attack(&self) -> bool {
1515 self.is_creature()
1516 && !self.tapped
1517 && !self.has_defender()
1518 && !self.cant_attack_static
1519 && !self.detained
1520 && (self.has_haste() || !self.summoning_sick)
1521 && self.zone == ZoneType::Battlefield
1522 }
1523
1524 pub fn can_block(&self) -> bool {
1525 self.is_creature()
1526 && !self.tapped
1527 && !self.cant_block_static
1528 && !self.detained
1529 && self.zone == ZoneType::Battlefield
1530 }
1531
1532 pub fn can_be_controlled_by(&self, player: PlayerId) -> bool {
1535 if player == self.controller {
1536 return true;
1537 }
1538 !self.has_keyword("Other players can't gain control of CARDNAME.")
1539 }
1540
1541 pub fn counter_count(&self, ct: &CounterType) -> i32 {
1542 *self.counters.get(ct).unwrap_or(&0)
1543 }
1544
1545 pub fn add_counter(&mut self, ct: &CounterType, count: i32) {
1546 let entry = self.counters.entry(ct.clone()).or_insert(0);
1547 *entry += count;
1548 }
1549
1550 pub fn remove_counter(&mut self, ct: &CounterType, count: i32) {
1551 let entry = self.counters.entry(ct.clone()).or_insert(0);
1552 *entry = (*entry - count).max(0);
1553 }
1554
1555 pub fn enter_battlefield(&mut self) {
1557 self.tapped = false;
1558 self.damage = 0;
1559 self.summoning_sick = true;
1560 self.came_under_control_since_last_upkeep = true;
1561 self.has_deathtouch_damage = false;
1562 self.entered_battlefield_this_turn = true;
1563 self.attacked_this_turn = false;
1564 self.damage_sources_this_turn.clear();
1565 }
1566
1567 pub fn clear_global_turn_state(&mut self) {
1569 self.entered_battlefield_this_turn = false;
1570 self.attacked_this_turn = false;
1571 self.attached_this_turn = false;
1572 self.has_deathtouch_damage = false;
1573 self.damage_sources_this_turn.clear();
1574 self.total_damage_done_this_turn = 0;
1575 }
1576
1577 pub fn new_turn(&mut self) {
1579 self.clear_global_turn_state();
1580 if self.zone == ZoneType::Battlefield {
1581 if let Ok(filter) = std::env::var("FORGE_CARD_TRACE") {
1582 if !filter.is_empty()
1583 && self.card_name.eq_ignore_ascii_case(&filter)
1584 && self.summoning_sick
1585 {
1586 eprintln!(
1587 "[card-trace] new_turn clears sickness on {}#{:?} (controller={:?})",
1588 self.card_name, self.id, self.controller,
1589 );
1590 }
1591 }
1592 self.summoning_sick = false;
1593 }
1594 }
1595
1596 pub fn add_remembered_card(&mut self, card_id: CardId) {
1598 if !self.remembered_cards.contains(&card_id) {
1599 self.remembered_cards.push(card_id);
1600 }
1601 }
1602
1603 pub fn add_remembered_cmc(&mut self, cmc: i32) {
1605 self.remembered_cmc.push(cmc);
1606 }
1607
1608 pub fn add_remembered_player(&mut self, player: PlayerId) {
1609 if !self.remembered_players.contains(&player) {
1610 self.remembered_players.push(player);
1611 }
1612 }
1613
1614 pub fn add_remembered_players<I>(&mut self, players: I)
1615 where
1616 I: IntoIterator<Item = PlayerId>,
1617 {
1618 for p in players {
1619 self.add_remembered_player(p);
1620 }
1621 }
1622
1623 pub fn has_remembered(&self) -> bool {
1624 !self.remembered_cards.is_empty()
1625 || !self.remembered_players.is_empty()
1626 || !self.remembered_cmc.is_empty()
1627 }
1628
1629 pub fn add_remembered(&mut self, card_id: CardId) {
1630 self.add_remembered_card(card_id);
1631 }
1632
1633 pub fn remove_remembered(&mut self, card_id: CardId) {
1634 self.remembered_cards.retain(|&c| c != card_id);
1635 }
1636
1637 pub fn clear_remembered(&mut self) {
1638 self.remembered_cards.clear();
1639 self.remembered_players.clear();
1640 self.remembered_cmc.clear();
1641 }
1642
1643 pub fn update_remembered(&mut self) {
1644 let mut seen = HashSet::new();
1645 self.remembered_cards.retain(|c| seen.insert(*c));
1646 }
1647
1648 pub fn has_imprinted_card(&self) -> bool {
1649 !self.imprinted_cards.is_empty()
1650 }
1651
1652 pub fn add_imprinted_card(&mut self, card_id: CardId) {
1653 if !self.imprinted_cards.contains(&card_id) {
1654 self.imprinted_cards.push(card_id);
1655 }
1656 }
1657
1658 pub fn add_imprinted_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1659 for c in cards {
1660 self.add_imprinted_card(c);
1661 }
1662 }
1663
1664 pub fn remove_imprinted_card(&mut self, card_id: CardId) {
1665 self.imprinted_cards.retain(|&c| c != card_id);
1666 }
1667
1668 pub fn remove_imprinted_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1669 for c in cards {
1670 self.remove_imprinted_card(c);
1671 }
1672 }
1673
1674 pub fn clear_imprinted_cards(&mut self) {
1675 self.imprinted_cards.clear();
1676 }
1677
1678 pub fn add_to_chosen_map(&mut self, player: PlayerId, chosen: Vec<CardId>) {
1679 self.chosen_map.insert(player, chosen);
1680 }
1681
1682 pub fn add_gain_control_target(&mut self, card_id: CardId) {
1683 if !self.gain_control_targets.contains(&card_id) {
1684 self.gain_control_targets.push(card_id);
1685 }
1686 }
1687
1688 pub fn remove_gain_control_targets(&mut self, card_id: CardId) {
1689 self.gain_control_targets.retain(|&c| c != card_id);
1690 }
1691
1692 pub fn has_gain_control_target(&self) -> bool {
1693 !self.gain_control_targets.is_empty()
1694 }
1695
1696 pub fn add_until_leaves_battlefield(&mut self, card_id: CardId) {
1697 if !self.until_leaves_battlefield.contains(&card_id) {
1698 self.until_leaves_battlefield.push(card_id);
1699 }
1700 }
1701
1702 pub fn remove_until_leaves_battlefield(&mut self, card_id: CardId) {
1703 self.until_leaves_battlefield.retain(|&c| c != card_id);
1704 }
1705
1706 pub fn clear_until_leaves_battlefield(&mut self) {
1707 self.until_leaves_battlefield.clear();
1708 }
1709
1710 pub fn has_exiled_card(&self) -> bool {
1711 !self.exiled_cards.is_empty()
1712 }
1713
1714 pub fn add_exiled_card(&mut self, card_id: CardId) {
1715 if !self.exiled_cards.contains(&card_id) {
1716 self.exiled_cards.push(card_id);
1717 }
1718 }
1719
1720 pub fn add_exiled_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1721 for c in cards {
1722 self.add_exiled_card(c);
1723 }
1724 }
1725
1726 pub fn remove_exiled_card(&mut self, card_id: CardId) {
1727 self.exiled_cards.retain(|&c| c != card_id);
1728 }
1729
1730 pub fn remove_exiled_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1731 for c in cards {
1732 self.remove_exiled_card(c);
1733 }
1734 }
1735
1736 pub fn clear_exiled_cards(&mut self) {
1737 self.exiled_cards.clear();
1738 }
1739
1740 pub fn add_haunted_by(&mut self, card_id: CardId) {
1741 if !self.haunted_by.contains(&card_id) {
1742 self.haunted_by.push(card_id);
1743 }
1744 }
1745
1746 pub fn remove_haunted_by(&mut self, card_id: CardId) {
1747 self.haunted_by.retain(|&c| c != card_id);
1748 }
1749
1750 pub fn has_encoded_card(&self) -> bool {
1751 !self.encoded_cards.is_empty()
1752 }
1753
1754 pub fn add_encoded_card(&mut self, card_id: CardId) {
1755 if !self.encoded_cards.contains(&card_id) {
1756 self.encoded_cards.push(card_id);
1757 }
1758 }
1759
1760 pub fn add_encoded_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1761 for c in cards {
1762 self.add_encoded_card(c);
1763 }
1764 }
1765
1766 pub fn remove_encoded_card(&mut self, card_id: CardId) {
1767 self.encoded_cards.retain(|&c| c != card_id);
1768 }
1769
1770 pub fn clear_encoded_cards(&mut self) {
1771 self.encoded_cards.clear();
1772 }
1773
1774 pub fn has_merged_card(&self) -> bool {
1775 !self.melded_with.is_empty()
1776 }
1777
1778 pub fn add_merged_card(&mut self, card_id: CardId) {
1779 if !self.melded_with.contains(&card_id) {
1780 self.melded_with.push(card_id);
1781 }
1782 }
1783
1784 pub fn add_merged_card_to_top(&mut self, card_id: CardId) {
1785 if !self.melded_with.contains(&card_id) {
1786 self.melded_with.insert(0, card_id);
1787 }
1788 }
1789
1790 pub fn remove_merged_card(&mut self, card_id: CardId) {
1791 self.melded_with.retain(|&c| c != card_id);
1792 }
1793
1794 pub fn clear_merged_cards(&mut self) {
1795 self.melded_with.clear();
1796 }
1797
1798 pub fn remove_mutated_states(&mut self) {
1799 self.clear_merged_cards();
1800 }
1801
1802 pub fn rebuild_mutated_states(&mut self) {
1803 let mut seen = HashSet::new();
1804 self.melded_with.retain(|c| seen.insert(*c));
1805 }
1806
1807 pub fn move_merged_to_subgame(&mut self) {
1808 self.clear_merged_cards();
1809 }
1810
1811 pub fn entered_this_turn(&self) -> bool {
1812 self.entered_battlefield_this_turn
1813 }
1814
1815 pub fn entered_current_zone_this_turn(&self, turn_number: u32) -> bool {
1816 self.turn_in_zone == turn_number
1817 }
1818
1819 pub fn calculate_perpetual_adjusted_mana_cost(&mut self) {
1820 crate::card::card_state::calculate_perpetual_adjusted_mana_cost(self);
1821 }
1822
1823 pub fn has_chosen_player(&self) -> bool {
1824 self.chosen_player.is_some()
1825 }
1826
1827 pub fn reveal_chosen_player(&mut self) {
1828 self.chosen_player_revealed = true;
1829 }
1830
1831 pub fn has_promised_gift(&self) -> bool {
1832 self.promised_gift.is_some()
1833 }
1834
1835 pub fn has_chosen_number(&self) -> bool {
1836 self.chosen_number.is_some()
1837 }
1838
1839 pub fn clear_chosen_number(&mut self) {
1840 self.chosen_number = None;
1841 self.chosen_number_controller = None;
1842 self.chosen_number_revealed = false;
1843 }
1844
1845 pub fn has_chosen_type(&self) -> bool {
1846 self.chosen_type
1847 .as_ref()
1848 .map(|s| !s.is_empty())
1849 .unwrap_or(false)
1850 }
1851
1852 pub fn reveal_chosen_type(&mut self) {
1853 self.chosen_type_revealed = true;
1854 }
1855
1856 pub fn has_chosen_type2(&self) -> bool {
1857 self.chosen_type2
1858 .as_ref()
1859 .map(|s| !s.is_empty())
1860 .unwrap_or(false)
1861 }
1862
1863 pub fn has_any_noted_type(&self) -> bool {
1864 !self.noted_types.is_empty()
1865 }
1866
1867 pub fn add_noted_type(&mut self, ty: &str) {
1868 self.noted_types.push(ty.to_string());
1869 }
1870
1871 pub fn has_chosen_color(&self) -> bool {
1872 !self.chosen_colors.is_empty()
1873 }
1874
1875 pub fn has_chosen_card(&self) -> bool {
1876 !self.chosen_cards.is_empty()
1877 }
1878
1879 pub fn assign_sector(&mut self, sector: &str) {
1880 self.sector = Some(sector.to_string());
1881 }
1882
1883 pub fn has_attraction_light(&self, light: i32) -> bool {
1884 light > 0 && self.attraction_lights.contains(&(light as u32))
1885 }
1886
1887 pub fn has_sector(&self) -> bool {
1888 self.sector.is_some()
1889 }
1890
1891 pub fn handle_changed_controller_sprocket_reset(&mut self) {
1892 if self.sprocket != 0 {
1893 self.sprocket = -1;
1894 }
1895 }
1896
1897 pub fn add_named_card(&mut self, name: &str) {
1898 self.named_cards.push(name.to_string());
1899 }
1900
1901 pub fn has_named_card(&self) -> bool {
1902 !self.named_cards.is_empty()
1903 }
1904
1905 pub fn has_chosen_even_odd(&self) -> bool {
1906 self.chosen_even_odd.is_some()
1907 }
1908
1909 pub fn has_no_abilities(&self) -> bool {
1910 self.abilities.is_empty()
1911 && self.activated_abilities.is_empty()
1912 && self.triggers.is_empty()
1913 && self.static_abilities.is_empty()
1914 && self.replacement_effects.is_empty()
1915 }
1916
1917 pub fn can_tap(&self) -> bool {
1918 !self.tapped
1919 }
1920
1921 pub fn tap(&mut self) -> bool {
1922 if !self.can_tap() {
1923 return false;
1924 }
1925 self.tapped = true;
1926 true
1927 }
1928
1929 pub fn set_tapped(&mut self, tapped: bool) {
1930 if tapped {
1931 self.tap();
1932 } else {
1933 self.untap();
1934 }
1935 }
1936
1937 pub fn set_owner(&mut self, owner: PlayerId) {
1938 self.owner = owner;
1939 }
1940
1941 pub fn set_controller(&mut self, controller: PlayerId) {
1942 if self.controller != controller {
1943 self.came_under_control_since_last_upkeep = true;
1944 }
1945 self.controller = controller;
1946 }
1947
1948 pub fn set_is_token(&mut self, is_token: bool) {
1949 self.is_token = is_token;
1950 }
1951
1952 pub fn set_effect_source(&mut self, source: Option<CardId>) {
1953 self.effect_source = source;
1954 }
1955
1956 pub fn set_temp_effect_host(&mut self, host: Option<CardId>) {
1957 self.temp_effect_host = host;
1958 }
1959
1960 pub fn set_temp_effect_until_eot(&mut self, until_eot: bool) {
1961 self.temp_effect_until_eot = until_eot;
1962 }
1963
1964 pub fn set_forget_on_moved_origin(&mut self, zone: Option<ZoneType>) {
1965 self.forget_on_moved_origin = zone;
1966 }
1967
1968 pub fn set_exile_when_no_remembered(&mut self, exile: bool) {
1969 self.exile_when_no_remembered = exile;
1970 }
1971
1972 pub fn set_flipped(&mut self, flipped: bool) {
1973 self.flipped = flipped;
1974 }
1975
1976 pub fn can_untap(&self) -> bool {
1977 self.tapped
1978 }
1979
1980 pub fn untap(&mut self) -> bool {
1981 if !self.can_untap() {
1982 return false;
1983 }
1984 self.tapped = false;
1985 true
1986 }
1987
1988 pub fn exert(&mut self) {
1989 self.exerted = true;
1990 }
1991
1992 pub fn clear_exerted(&mut self) {
1993 self.exerted = false;
1994 }
1995
1996 pub fn remove_exerted_by(&mut self, _player: PlayerId) {
1997 self.exerted = false;
1998 }
1999
2000 pub fn detain(&mut self) {
2001 self.detained = true;
2002 }
2003
2004 pub fn add_goad(&mut self, player: PlayerId) {
2005 self.goaded_by = Some(player);
2006 }
2007
2008 pub fn remove_goad(&mut self, player: PlayerId) {
2009 if self.goaded_by == Some(player) {
2010 self.goaded_by = None;
2011 }
2012 }
2013
2014 pub fn un_goad(&mut self) {
2015 self.goaded_by = None;
2016 }
2017
2018 pub fn remove_detained_by(&mut self, _player: PlayerId) {
2019 self.detained = false;
2020 }
2021
2022 pub fn update_ability_text_for_view(&mut self) {
2023 self.update_spell_abilities();
2024 }
2025 pub fn update_non_ability_text_for_view(&mut self) {
2026 self.update_changed_text();
2027 }
2028 pub fn update_mana_cost_for_view(&mut self) {
2029 let _ = self.mana_value();
2030 }
2031 pub fn update_p_tfor_view(&mut self) {
2032 let _ = (self.power(), self.toughness());
2033 }
2034 pub fn update_color_for_view(&mut self) {
2035 let _ = self.color;
2036 }
2037 pub fn update_attacking_for_view(&mut self) {
2038 let _ = self.attacking_player;
2039 }
2040 pub fn update_blocking_for_view(&mut self) {
2041 let _ = self.must_block;
2042 }
2043 pub fn update_state_for_view(&mut self) {
2044 let _ = (self.zone, self.tapped, self.face_down);
2045 }
2046 pub fn update_namefor_view(&mut self) {
2047 self.card_name = self.card_name.trim().to_string();
2048 }
2049 pub fn update_token_view(&mut self) {
2050 let _ = self.is_token;
2051 }
2052 pub fn update_was_destroyed(&mut self) {
2053 let _ = self.damage >= self.toughness();
2054 }
2055 pub fn update_rules_view(&mut self) {
2056 let _ = (&self.abilities, &self.keywords);
2057 }
2058 pub fn update_commander_view(&mut self) {
2059 let _ = self.is_commander;
2060 }
2061 pub fn update_card(&mut self) {
2062 self.update_namefor_view();
2063 self.update_types_for_view();
2064 self.update_color_for_view();
2065 self.update_mana_cost_for_view();
2066 self.update_p_tfor_view();
2067 self.update_rules_view();
2068 self.update_state_for_view();
2069 }
2070 pub fn dangerously_set_game(&mut self) {
2071 self.update_card();
2072 }
2073 pub fn visit(&mut self) {
2074 self.update_card();
2075 }
2076
2077 pub fn has_state(&self) -> bool {
2078 self.is_transformed || self.other_part.is_some()
2079 }
2080
2081 pub fn is_double_faced(&self) -> bool {
2084 self.other_part.is_some()
2085 }
2086
2087 pub fn change_to_state(&mut self) {
2088 self.transform();
2089 }
2090
2091 pub fn add_alternate_state(&mut self, other: CardOtherPart) {
2092 self.other_part = Some(other);
2093 }
2094
2095 pub fn clear_states(&mut self) {
2096 self.other_part = None;
2097 self.is_transformed = false;
2098 }
2099
2100 pub fn change_card_state(&mut self) {
2101 self.transform();
2102 }
2103
2104 pub fn has_alternate_state(&self) -> bool {
2105 self.other_part.is_some()
2106 }
2107
2108 pub fn manifest(&mut self) {
2109 self.manifested = true;
2110 self.turn_face_down();
2111 }
2112
2113 pub fn cloak(&mut self) {
2114 self.cloaked = true;
2115 self.turn_face_down();
2116 }
2117
2118 pub fn turn_face_down(&mut self) {
2119 self.face_down = true;
2120 }
2121
2122 pub fn turn_face_down_no_update(&mut self) {
2123 self.face_down = true;
2124 }
2125
2126 pub fn can_be_turned_face_up(&self) -> bool {
2127 self.face_down
2128 }
2129
2130 pub fn force_turn_face_up(&mut self) {
2131 self.face_down = false;
2132 }
2133
2134 pub fn turn_face_up(&mut self) {
2135 self.face_down = false;
2136 }
2137
2138 pub fn set_face_down(&mut self, face_down: bool) {
2139 if face_down {
2140 self.turn_face_down();
2141 } else {
2142 self.turn_face_up();
2143 }
2144 }
2145
2146 pub fn set_manifested(&mut self, manifested: bool) {
2147 self.manifested = manifested;
2148 }
2149
2150 pub fn set_cloaked(&mut self, cloaked: bool) {
2151 self.cloaked = cloaked;
2152 }
2153
2154 pub fn set_discarded(&mut self, discarded: bool) {
2155 self.discarded = discarded;
2156 }
2157
2158 pub fn set_unearthed(&mut self, unearthed: bool) {
2159 self.unearthed = unearthed;
2160 }
2161
2162 pub fn set_summoning_sick(&mut self, summoning_sick: bool) {
2163 self.summoning_sick = summoning_sick;
2164 }
2165
2166 pub fn set_foretold(&mut self, foretold: bool) {
2167 self.foretold = foretold;
2168 }
2169
2170 pub fn set_foretold_cost_by_effect(&mut self, by_effect: bool) {
2171 self.foretold_cost_by_effect = by_effect;
2172 }
2173
2174 pub fn set_transformed(&mut self, transformed: bool) {
2175 self.is_transformed = transformed;
2176 }
2177
2178 pub fn set_attacking_player(&mut self, player: PlayerId) {
2179 self.attacking_player = Some(player);
2180 }
2181
2182 pub fn clear_attacking_player(&mut self) {
2183 self.attacking_player = None;
2184 }
2185
2186 pub fn mark_attacked_this_turn(&mut self) {
2187 self.attacked_this_turn = true;
2188 }
2189
2190 pub fn add_etb_counters_p1p1(&mut self, amount: i32) {
2191 self.etb_counters_p1p1 += amount;
2192 }
2193
2194 pub fn increment_commander_cast_count(&mut self) {
2195 self.commander_cast_count += 1;
2196 }
2197
2198 pub fn set_kicked(&mut self, kicked: bool) {
2199 self.kicked = kicked;
2200 }
2201
2202 pub fn mark_enlisted_this_combat(&mut self) {
2203 self.enlisted_this_combat = true;
2204 }
2205
2206 pub fn add_enlisted_power(&mut self, amount: i32) {
2207 self.power_modifier += amount;
2208 }
2209
2210 pub fn add_damage_source_this_turn(&mut self, source: CardId) {
2211 self.damage_sources_this_turn.push(source);
2212 }
2213
2214 pub fn mark_deathtouch_damage(&mut self) {
2215 self.has_deathtouch_damage = true;
2216 }
2217
2218 pub fn clear_deathtouch_damage(&mut self) {
2219 self.has_deathtouch_damage = false;
2220 }
2221
2222 pub fn clear_damage(&mut self) {
2223 self.damage = 0;
2224 }
2225
2226 pub fn reset_turn_modifiers(&mut self) {
2227 self.power_modifier = 0;
2228 self.toughness_modifier = 0;
2229 }
2230
2231 pub fn reset_regeneration_shields(&mut self) {
2232 self.regeneration_shields = 0;
2233 }
2234
2235 pub fn clear_original_controller_eot(&mut self) {
2236 self.original_controller_eot = None;
2237 }
2238
2239 pub fn set_chosen_modes(&mut self, modes: Vec<usize>) {
2240 self.chosen_modes = Some(modes);
2241 }
2242
2243 pub fn set_chosen_cards(&mut self, cards: Vec<CardId>) {
2244 self.chosen_cards = cards;
2245 }
2246
2247 pub fn set_chosen_number(&mut self, number: Option<i32>) {
2248 self.chosen_number = number;
2249 self.chosen_number_controller = None;
2250 self.chosen_number_revealed = number.is_some();
2251 }
2252
2253 pub fn set_chosen_number_for_player(
2254 &mut self,
2255 number: Option<i32>,
2256 chooser: PlayerId,
2257 revealed: bool,
2258 ) {
2259 self.chosen_number = number;
2260 self.chosen_number_controller = Some(chooser);
2261 self.chosen_number_revealed = revealed;
2262 }
2263
2264 pub fn set_chosen_mode(&mut self, mode: impl Into<String>) {
2265 self.chosen_mode = Some(mode.into());
2266 }
2267
2268 pub fn set_chosen_player(
2269 &mut self,
2270 player: Option<PlayerId>,
2271 chooser: Option<PlayerId>,
2272 revealed: bool,
2273 ) {
2274 self.chosen_player = player;
2275 self.chosen_player_controller = chooser;
2276 self.chosen_player_revealed = revealed;
2277 }
2278
2279 pub fn set_chosen_type(
2280 &mut self,
2281 chosen_type: Option<String>,
2282 chooser: Option<PlayerId>,
2283 revealed: bool,
2284 ) {
2285 self.chosen_type = chosen_type;
2286 self.chosen_type_controller = chooser;
2287 self.chosen_type_revealed = revealed;
2288 }
2289
2290 pub fn set_strive_extra_targets(&mut self, value: u32) {
2291 self.strive_extra_targets = value;
2292 }
2293
2294 pub fn set_colors_spent_to_cast(&mut self, colors: u16) {
2295 self.colors_spent_to_cast = colors;
2296 }
2297
2298 pub fn set_paying_mana_to_cast(&mut self, paying_mana: Vec<u16>) {
2299 self.paying_mana_to_cast = paying_mana;
2300 }
2301
2302 pub fn set_promised_gift(&mut self, player: Option<PlayerId>) {
2303 self.promised_gift = player;
2304 }
2305
2306 pub fn set_lki_power_toughness(&mut self, power: Option<i32>, toughness: Option<i32>) {
2307 self.lki_power = power;
2308 self.lki_toughness = toughness;
2309 }
2310
2311 pub fn restore_animate_snapshot(
2312 &mut self,
2313 type_line: CardTypeLine,
2314 base_power: Option<i32>,
2315 base_toughness: Option<i32>,
2316 color: ColorSet,
2317 ) {
2318 self.set_type_line(type_line);
2319 self.base_power = base_power;
2320 self.base_toughness = base_toughness;
2321 self.color = color;
2322 }
2323
2324 pub fn capture_clone_state(&self) -> CloneState {
2325 CloneState {
2326 expires_at_cleanup: false,
2327 original_card_name: self.card_name.clone(),
2328 original_oracle_text: self.oracle_text.clone(),
2329 original_type_line: self.type_line.clone(),
2330 original_mana_cost: self.mana_cost.clone(),
2331 original_color: self.color,
2332 original_base_power: self.base_power,
2333 original_base_toughness: self.base_toughness,
2334 original_keywords: self.keywords.clone(),
2335 original_abilities: self.abilities.clone(),
2336 original_activated_abilities: self.activated_abilities.clone(),
2337 original_triggers: self.triggers.clone(),
2338 original_svars: self.svars.clone(),
2339 original_static_abilities: self.static_abilities.clone(),
2340 original_replacement_effects: self.replacement_effects.clone(),
2341 original_base_ability_count: self.base_ability_count,
2342 original_base_trigger_count: self.base_trigger_count,
2343 }
2344 }
2345
2346 pub fn restore_clone_snapshot(&mut self, state: CloneState) {
2347 self.card_name = state.original_card_name;
2348 self.oracle_text = state.original_oracle_text;
2349 self.type_line = state.original_type_line;
2350 self.mana_cost = state.original_mana_cost;
2351 self.color = state.original_color;
2352 self.base_power = state.original_base_power;
2353 self.base_toughness = state.original_base_toughness;
2354 self.keywords = state.original_keywords;
2355 self.abilities = state.original_abilities;
2356 self.activated_abilities = state.original_activated_abilities;
2357 self.triggers = state.original_triggers;
2358 self.svars = state.original_svars;
2359 self.static_abilities = state.original_static_abilities;
2360 self.replacement_effects = state.original_replacement_effects;
2361 self.base_ability_count = state.original_base_ability_count;
2362 self.base_trigger_count = state.original_base_trigger_count;
2363 self.parsed_svar_cache.clear();
2364 self.refresh_action_specs();
2365 self.ensure_crew_activated_ability();
2366 self.remove_clone_state();
2367 }
2368
2369 pub fn set_counters_map(&mut self, counters: BTreeMap<CounterType, i32>) {
2370 self.counters = counters;
2371 }
2372
2373 pub fn set_zone(&mut self, zone: ZoneType) {
2374 self.zone = zone;
2375 }
2376
2377 pub fn set_color(&mut self, color: ColorSet) {
2378 self.color = color;
2379 }
2380
2381 pub fn set_animate_state(&mut self, state: Option<AnimateState>) {
2382 self.animate_state = state;
2383 }
2384
2385 pub fn set_clone_state(&mut self, state: Option<CloneState>) {
2386 self.clone_state = state;
2387 }
2388
2389 pub fn set_exiled_by(&mut self, source: Option<CardId>) {
2390 self.exiled_by = source;
2391 }
2392
2393 pub fn set_attached_to(&mut self, target: Option<CardId>) {
2394 self.attached_to = target;
2395 }
2396
2397 pub fn set_original_controller_eot(&mut self, controller: Option<PlayerId>) {
2398 self.original_controller_eot = controller;
2399 }
2400
2401 pub fn set_class_level(&mut self, level: i32) {
2402 self.class_level = level;
2403 }
2404
2405 pub fn set_paired_with(&mut self, pair: Option<CardId>) {
2406 self.paired_with = pair;
2407 }
2408
2409 pub fn set_must_block(&mut self, must_block: bool) {
2410 self.must_block = must_block;
2411 }
2412
2413 pub fn set_detained(&mut self, detained: bool) {
2414 self.detained = detained;
2415 }
2416
2417 pub fn set_goaded_by(&mut self, player: Option<PlayerId>) {
2418 self.goaded_by = player;
2419 }
2420
2421 pub fn set_phased_out(&mut self, phased_out: bool) {
2422 self.phased_out = phased_out;
2423 }
2424
2425 pub fn set_base_power(&mut self, power: Option<i32>) {
2426 self.base_power = power;
2427 }
2428
2429 pub fn set_base_toughness(&mut self, toughness: Option<i32>) {
2430 self.base_toughness = toughness;
2431 }
2432
2433 pub fn set_base_pt(&mut self, power: Option<i32>, toughness: Option<i32>) {
2434 self.base_power = power;
2435 self.base_toughness = toughness;
2436 }
2437
2438 pub fn capture_changed_characteristics_baseline_if_needed(&mut self) {
2439 if self.changed_type_line_base.is_none() {
2440 self.changed_type_line_base = Some(self.type_line.clone());
2441 }
2442 if self.changed_base_power.is_none() {
2443 self.changed_base_power = Some(self.base_power);
2444 }
2445 if self.changed_base_toughness.is_none() {
2446 self.changed_base_toughness = Some(self.base_toughness);
2447 }
2448 }
2449
2450 pub fn restore_changed_characteristics_baseline(&mut self) {
2451 if let Some(type_line) = self.changed_type_line_base.take() {
2452 self.set_type_line(type_line);
2453 }
2454 if let Some(power) = self.changed_base_power.take() {
2455 self.base_power = power;
2456 }
2457 if let Some(toughness) = self.changed_base_toughness.take() {
2458 self.base_toughness = toughness;
2459 }
2460 }
2461
2462 pub fn set_static_set_pt(&mut self, power: Option<i32>, toughness: Option<i32>) {
2463 self.static_set_power = power;
2464 self.static_set_toughness = toughness;
2465 }
2466
2467 pub fn set_power_modifier(&mut self, amount: i32) {
2468 self.power_modifier = amount;
2469 }
2470
2471 pub fn set_toughness_modifier(&mut self, amount: i32) {
2472 self.toughness_modifier = amount;
2473 }
2474
2475 pub fn set_card_name(&mut self, name: impl Into<String>) {
2476 self.card_name = name.into();
2477 }
2478
2479 pub fn set_mana_cost(&mut self, mana_cost: ManaCost) {
2480 self.mana_cost = mana_cost;
2481 }
2482
2483 pub fn set_abilities(&mut self, abilities: Vec<String>) {
2484 self.abilities = abilities;
2485 self.update_spell_abilities();
2486 self.refresh_action_specs();
2487 }
2488
2489 pub fn set_static_abilities(&mut self, abilities: Vec<StaticAbility>) {
2490 self.static_abilities = abilities;
2491 }
2492
2493 pub fn set_triggers(&mut self, triggers: Vec<Trigger>) {
2494 self.triggers = triggers;
2495 self.base_trigger_count = self.triggers.len();
2496 }
2497
2498 pub fn set_replacement_effects(&mut self, effects: Vec<ReplacementEffect>) {
2499 self.replacement_effects = effects;
2500 }
2501
2502 pub fn set_renowned(&mut self, renowned: bool) {
2503 self.is_renowned = renowned;
2504 }
2505
2506 pub fn set_monstrous(&mut self, monstrous: bool) {
2507 self.monstrous = monstrous;
2508 }
2509
2510 pub fn clear_granted_keywords(&mut self) {
2511 self.granted_keywords.clear();
2512 }
2513
2514 pub fn clear_pump_keywords(&mut self) {
2515 self.pump_keywords.clear();
2516 }
2517
2518 pub fn increment_pump_trigger_count(&mut self) {
2519 self.pump_trigger_count += 1;
2520 }
2521
2522 pub fn add_remembered_cards<I>(&mut self, cards: I)
2523 where
2524 I: IntoIterator<Item = CardId>,
2525 {
2526 for card in cards {
2527 self.add_remembered_card(card);
2528 }
2529 }
2530
2531 pub fn clear_chosen_colors(&mut self) {
2532 self.chosen_colors.clear();
2533 }
2534
2535 pub fn add_chosen_color(&mut self, color: impl Into<String>) {
2536 self.chosen_colors.push(color.into());
2537 }
2538
2539 pub fn add_chosen_card(&mut self, card: CardId) {
2540 if !self.chosen_cards.contains(&card) {
2541 self.chosen_cards.push(card);
2542 }
2543 }
2544
2545 pub fn add_pump_keyword(&mut self, keyword: &str) {
2546 self.pump_keywords.add(keyword);
2547 }
2548
2549 pub fn add_granted_keyword(&mut self, keyword: &str) {
2550 self.granted_keywords.add(keyword);
2551 }
2552
2553 pub fn was_turned_face_up_this_turn(&self) -> bool {
2554 !self.face_down && (self.manifested || self.cloaked)
2555 }
2556
2557 pub fn can_transform(&self) -> bool {
2558 self.other_part.is_some()
2559 }
2560
2561 pub fn has_name_overwrite(&self) -> bool {
2562 false
2563 }
2564
2565 pub fn has_non_legendary_creature_names(&self) -> bool {
2566 false
2567 }
2568
2569 pub fn add_changed_name(&mut self, name: &str) {
2570 if !self.has_s_var("OriginalName") {
2571 self.set_s_var("OriginalName", self.card_name.clone());
2572 }
2573 self.card_name = name.to_string();
2574 }
2575
2576 pub fn remove_changed_name(&mut self) {
2577 if let Some(orig) = self.svars.get("OriginalName").cloned() {
2578 self.card_name = orig;
2579 }
2580 }
2581
2582 pub fn clear_changed_name(&mut self) {
2583 self.remove_s_var("OriginalName");
2584 }
2585
2586 pub fn add_devoured(&mut self, card_id: CardId) {
2587 self.add_remembered_card(card_id);
2588 self.set_s_var("Devoured", "True");
2589 }
2590 pub fn add_exploited(&mut self, card_id: CardId) {
2591 self.add_remembered_card(card_id);
2592 self.set_s_var("Exploited", "True");
2593 }
2594 pub fn add_delved(&mut self, card_id: CardId) {
2595 self.add_remembered_card(card_id);
2596 self.set_s_var("Delved", "True");
2597 }
2598 pub fn clear_delved(&mut self) {
2599 self.remove_s_var("Delved");
2600 }
2601 pub fn retain_paid_list(&mut self) {
2602 self.remembered_cards.retain(|_| true);
2603 }
2604 pub fn add_stored_rolls(&mut self, roll: i32) {
2605 self.stored_rolls.push(roll);
2606 self.stored_rolls.sort_unstable();
2607 }
2608 pub fn replace_stored_roll(&mut self, from: i32, to: i32) {
2609 if let Some(index) = self.stored_rolls.iter().position(|roll| *roll == from) {
2610 self.stored_rolls.remove(index);
2611 self.stored_rolls.push(to);
2612 self.stored_rolls.sort_unstable();
2613 }
2614 }
2615 pub fn add_flip_result(&mut self, heads: bool) {
2616 self.set_s_var("FlipResult", if heads { "Heads" } else { "Tails" });
2617 }
2618 pub fn clear_flip_result(&mut self) {
2619 self.remove_s_var("FlipResult");
2620 }
2621 pub fn add_blocked_this_turn(&mut self, card_id: CardId) {
2622 self.add_remembered_card(card_id);
2623 self.set_s_var("BlockedThisTurn", "True");
2624 }
2625 pub fn clear_blocked_this_turn(&mut self) {
2626 self.remove_s_var("BlockedThisTurn");
2627 }
2628 pub fn add_blocked_by_this_turn(&mut self, card_id: CardId) {
2629 self.add_remembered_card(card_id);
2630 self.set_s_var("BlockedByThisTurn", "True");
2631 }
2632 pub fn clear_blocked_by_this_turn(&mut self) {
2633 self.remove_s_var("BlockedByThisTurn");
2634 }
2635
2636 pub fn add_must_block_card(&mut self, card_id: CardId) {
2637 if !self.must_block_cards.contains(&card_id) {
2638 self.must_block_cards.push(card_id);
2639 }
2640 }
2641
2642 pub fn add_must_block_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
2643 for c in cards {
2644 self.add_must_block_card(c);
2645 }
2646 }
2647
2648 pub fn remove_must_block_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
2649 let remove: HashSet<CardId> = cards.into_iter().collect();
2650 self.must_block_cards.retain(|c| !remove.contains(c));
2651 }
2652
2653 pub fn clear_must_block_cards(&mut self) {
2654 self.must_block_cards.clear();
2655 }
2656
2657 pub fn has_second_strike(&self) -> bool {
2658 self.has_double_strike()
2659 }
2660
2661 pub fn has_suspend(&self) -> bool {
2662 self.has_keyword("Suspend")
2663 }
2664
2665 pub fn has_converge(&self) -> bool {
2666 self.has_keyword("Converge")
2667 }
2668
2669 pub fn can_receive_counters(&self, _counter: &CounterType) -> bool {
2670 true
2671 }
2672
2673 pub fn can_remove_counters(&self, counter: &CounterType) -> bool {
2674 self.counter_count(counter) > 0
2675 }
2676
2677 pub fn add_counter_internal(&mut self, counter: &CounterType, amount: i32) {
2678 self.add_counter(counter, amount);
2679 }
2680
2681 pub fn create_counter_static(&mut self) {
2682 self.put_etb_counters();
2683 }
2684
2685 pub fn subtract_counter(&mut self, counter: &CounterType, amount: i32) {
2686 self.remove_counter(counter, amount);
2687 }
2688
2689 pub fn clear_counters(&mut self) {
2690 self.counters.clear();
2691 }
2692
2693 pub fn sum_all_counters(&self) -> i32 {
2694 self.counters.values().sum()
2695 }
2696
2697 pub fn put_etb_counters(&mut self) {
2698 if self.etb_counters_p1p1 > 0 {
2699 self.add_counter(&CounterType::P1P1, self.etb_counters_p1p1);
2700 self.etb_counters_p1p1 = 0;
2701 }
2702 }
2703
2704 pub fn copy_changed_s_vars_from(&mut self, other: &Card) {
2705 self.set_svars_map(other.svars.clone());
2706 }
2707
2708 pub fn add_changed_s_vars(&mut self, key: &str, value: &str) {
2709 self.set_s_var(key, value);
2710 }
2711
2712 pub fn remove_changed_s_vars(&mut self, key: &str) {
2713 self.remove_s_var(key);
2714 }
2715
2716 pub fn add_changed_mana_cost(&mut self, mana_cost: &str) {
2717 if !self.has_s_var("OriginalManaCost") {
2718 self.set_s_var("OriginalManaCost", self.mana_cost.to_string());
2719 }
2720 self.mana_cost = ManaCost::parse(mana_cost);
2721 self.calculate_perpetual_adjusted_mana_cost();
2722 self.update_mana_cost_for_view();
2723 }
2724 pub fn remove_changed_mana_cost(&mut self, _timestamp: i64, _static_id: i64) -> bool {
2725 let Some(original) = self.svars.get("OriginalManaCost").cloned() else {
2726 return false;
2727 };
2728 let before = self.mana_cost.clone();
2729 self.mana_cost = ManaCost::parse(&original);
2730 self.calculate_perpetual_adjusted_mana_cost();
2731 self.update_mana_cost_for_view();
2732 self.remove_s_var("OriginalManaCost");
2733 self.mana_cost != before
2734 }
2735
2736 pub fn cleanup_exiled_with(&mut self) {
2737 self.exiled_by = None;
2738 }
2739
2740 pub fn has_paper_foil(&self) -> bool {
2741 self.paper_foil
2742 }
2743
2744 pub fn has_marked_color(&self) -> bool {
2745 !self.color.is_colorless()
2746 }
2747
2748 pub fn can_produce_color_mana(
2749 &self,
2750 game: &GameState,
2751 colors: &std::collections::HashSet<String>,
2752 ) -> bool {
2753 crate::card::card_util::card_can_produce_color_mana(game, self.id, colors)
2754 }
2755
2756 pub fn can_produce_same_mana_type_with(&self, game: &GameState, other: &Card) -> bool {
2757 crate::card::card_util::card_can_produce_same_mana_type_with(game, self.id, other.id)
2758 }
2759
2760 pub fn has_remove_intrinsic(&self) -> bool {
2761 false
2762 }
2763
2764 pub fn update_spell_abilities(&mut self) {
2765 self.activated_abilities.clear();
2766 for (i, raw) in self.abilities.iter().enumerate() {
2767 if let Some(parsed) = crate::ability::activated::parse_activated_ability(raw, i) {
2768 self.activated_abilities.push(parsed);
2769 }
2770 }
2771 }
2772
2773 pub fn refresh_action_specs(&mut self) {
2774 let mut spell_specs = Vec::new();
2775 let mut spell_cost = None;
2776 let mut ai_phyrexian_payment = None;
2777 let mut spree_min_mode_cost = None;
2778
2779 for (ability_index, raw) in self.abilities.iter().enumerate() {
2780 let parsed = ParsedParams::parse(raw);
2781 if ai_phyrexian_payment.is_none() {
2782 ai_phyrexian_payment = parsed.get(keys::AI_PHYREXIAN_PAYMENT).map(str::to_string);
2783 }
2784 let Some(sp_kind) = parsed.get(keys::SP) else {
2785 continue;
2786 };
2787 let cost_contains_x = parsed
2788 .get(keys::COST)
2789 .is_some_and(|cost| cost.contains('X'));
2790 if spell_cost.is_none() {
2791 spell_cost = parsed.get(keys::COST).map(parse_cost);
2792 }
2793 spell_specs.push(CardActionSpellSpec {
2794 ability_index,
2795 has_valid_tgts: parsed.has(keys::VALID_TGTS),
2796 cost_contains_x,
2797 target_chain: self.collect_action_target_chain(raw),
2798 });
2799
2800 if sp_kind.eq_ignore_ascii_case("Charm") {
2801 if let Some(choices) = parsed.get(keys::CHOICES) {
2802 let min_mode_cost = choices
2803 .split(',')
2804 .filter_map(|name| {
2805 self.svars.get(name.trim()).and_then(|svar_val| {
2806 ParsedParams::parse(svar_val)
2807 .get(keys::MODE_COST)
2808 .map(|cost| forge_foundation::ManaCost::parse(cost).cmc())
2809 })
2810 })
2811 .min();
2812 spree_min_mode_cost = spree_min_mode_cost.or(min_mode_cost);
2813 }
2814 }
2815 }
2816
2817 self.action_spell_specs = spell_specs;
2818 self.action_spell_cost = spell_cost;
2819 self.ai_phyrexian_payment = ai_phyrexian_payment;
2820 self.spree_min_mode_cost = spree_min_mode_cost;
2821 }
2822
2823 fn refresh_action_specs_after_svar_change(&mut self) {
2824 if self.action_spell_specs.is_empty() {
2825 return;
2826 }
2827 self.refresh_action_specs();
2828 }
2829
2830 fn collect_action_target_chain(&self, ability_text: &str) -> Vec<CardActionTargetSpec> {
2831 let mut specs = Vec::new();
2832 let mut current = Some(ability_text.to_string());
2833
2834 while let Some(text) = current {
2835 let parsed = ParsedParams::parse(&text);
2836 let params = Params::from_parsed(&parsed);
2837 if let Some(target_restrictions) = TargetRestrictions::new_from_parsed(&parsed, ¶ms)
2838 {
2839 specs.push(CardActionTargetSpec {
2840 min_targets: parse_literal_target_count(&target_restrictions.min_targets),
2841 target_restrictions,
2842 });
2843 }
2844
2845 current = parsed
2846 .get(keys::SUB_ABILITY)
2847 .and_then(|name| self.svars.get(name.trim()))
2848 .cloned();
2849 }
2850
2851 specs
2852 }
2853
2854 pub fn inc_shield_count(&mut self) {
2855 self.damage_prevention += 1;
2856 }
2857
2858 pub fn dec_shield_count(&mut self) {
2859 self.damage_prevention = (self.damage_prevention - 1).max(0);
2860 }
2861
2862 pub fn reset_shield_count(&mut self) {
2863 self.damage_prevention = 0;
2864 }
2865
2866 pub fn add_regenerated_this_turn(&mut self) {
2867 self.regeneration_shields += 1;
2868 }
2869
2870 pub fn can_be_shielded(&self) -> bool {
2871 self.is_permanent()
2872 }
2873
2874 pub fn add_untap_command(&mut self) {
2875 self.set_s_var("_cmd_untap", "1");
2876 }
2877 pub fn add_unattach_command(&mut self) {
2878 self.set_s_var("_cmd_unattach", "1");
2879 }
2880 pub fn add_faceup_command(&mut self) {
2881 self.set_s_var("_cmd_faceup", "1");
2882 }
2883 pub fn add_facedown_command(&mut self) {
2884 self.set_s_var("_cmd_facedown", "1");
2885 }
2886 pub fn add_change_controller_command(&mut self) {
2887 self.set_s_var("_cmd_change_controller", "1");
2888 }
2889 pub fn add_phase_out_command(&mut self) {
2890 self.set_s_var("_cmd_phase_out", "1");
2891 }
2892 pub fn add_leaves_play_command(&mut self) {
2893 self.set_s_var("_cmd_leaves_play", "1");
2894 }
2895 pub fn add_static_command_list(&mut self) {
2896 self.set_s_var("_cmd_static", "1");
2897 }
2898 pub fn run_leaves_play_commands(&mut self) {
2899 if self.has_s_var("_cmd_leaves_play") {
2900 self.cleanup_exiled_with();
2901 self.remove_s_var("_cmd_leaves_play");
2902 }
2903 }
2904 pub fn run_untap_commands(&mut self) {
2905 if self.has_s_var("_cmd_untap") {
2906 self.untap();
2907 self.remove_s_var("_cmd_untap");
2908 }
2909 }
2910 pub fn run_unattach_commands(&mut self) {
2911 if self.has_s_var("_cmd_unattach") {
2912 self.unattach_from_entity();
2913 self.remove_s_var("_cmd_unattach");
2914 }
2915 }
2916 pub fn run_faceup_commands(&mut self) {
2917 if self.has_s_var("_cmd_faceup") {
2918 self.turn_face_up();
2919 self.remove_s_var("_cmd_faceup");
2920 }
2921 }
2922 pub fn run_facedown_commands(&mut self) {
2923 if self.has_s_var("_cmd_facedown") {
2924 self.turn_face_down();
2925 self.remove_s_var("_cmd_facedown");
2926 }
2927 }
2928 pub fn run_change_controller_commands(&mut self) {
2929 if self.has_s_var("_cmd_change_controller") {
2930 self.clear_temp_controllers();
2931 self.remove_s_var("_cmd_change_controller");
2932 }
2933 }
2934 pub fn run_phase_out_commands(&mut self) {
2935 if self.has_s_var("_cmd_phase_out") {
2936 self.phase();
2937 self.remove_s_var("_cmd_phase_out");
2938 }
2939 }
2940
2941 pub fn has_sickness(&self) -> bool {
2942 self.summoning_sick
2943 }
2944
2945 pub fn has_become_target_this_turn(&self) -> bool {
2946 self.became_target_this_turn
2947 }
2948
2949 pub fn add_target_from_this_turn(&mut self) {
2950 self.became_target_this_turn = true;
2951 }
2952
2953 pub fn has_started_the_turn_untapped(&self) -> bool {
2954 !self.started_turn_tapped
2955 }
2956
2957 pub fn came_under_control_since_last_upkeep(&self) -> bool {
2958 self.came_under_control_since_last_upkeep
2959 }
2960
2961 pub fn add_temp_controller(&mut self, player: PlayerId) {
2962 self.temp_controllers.push(player);
2963 }
2964
2965 pub fn remove_temp_controller(&mut self, player: PlayerId) {
2966 self.temp_controllers.retain(|&p| p != player);
2967 }
2968
2969 pub fn clear_temp_controllers(&mut self) {
2970 self.temp_controllers.clear();
2971 }
2972
2973 pub fn clear_controllers(&mut self) {
2974 self.controller = self.owner;
2975 self.clear_temp_controllers();
2976 }
2977
2978 pub fn may_player_look(&self, player: PlayerId) -> bool {
2979 self.may_look_at.contains(&player)
2980 }
2981
2982 pub fn add_may_look_face_down_exile(&mut self, player: PlayerId) {
2983 if !self.may_look_at.contains(&player) {
2984 self.may_look_at.push(player);
2985 }
2986 }
2987
2988 pub fn add_may_look_at(&mut self, player: PlayerId) {
2989 if !self.may_look_at.contains(&player) {
2990 self.may_look_at.push(player);
2991 }
2992 }
2993
2994 pub fn remove_may_look_at(&mut self, player: PlayerId) {
2995 self.may_look_at.retain(|&p| p != player);
2996 }
2997
2998 pub fn add_may_look_temp(&mut self, player: PlayerId) {
2999 self.add_may_look_at(player);
3000 }
3001
3002 pub fn remove_may_look_temp(&mut self, player: PlayerId) {
3003 self.remove_may_look_at(player);
3004 }
3005
3006 pub fn update_may_look(&mut self) {
3007 let mut seen = HashSet::new();
3008 self.may_look_at.retain(|p| seen.insert(*p));
3009 }
3010 pub fn update_may_play(&mut self) {
3011 let mut seen = HashSet::new();
3012 self.may_play.retain(|p| seen.insert(*p));
3013 }
3014
3015 pub fn may_play(&self, player: PlayerId) -> bool {
3016 self.may_play.contains(&player)
3017 }
3018
3019 pub fn remove_may_play(&mut self, player: PlayerId) {
3020 self.may_play.retain(|&p| p != player);
3021 }
3022
3023 pub fn reset_may_play_turn(&mut self) {
3024 self.may_play.clear();
3025 }
3026
3027 pub fn remove_attached_to(&mut self) {
3028 self.attached_to = None;
3029 }
3030
3031 pub fn attach_to_entity(&mut self, host: CardId) {
3032 self.attached_to = Some(host);
3033 }
3034
3035 pub fn add_attachment(&mut self, card_id: CardId) {
3036 if !self.attachments.contains(&card_id) {
3037 self.attachments.push(card_id);
3038 }
3039 }
3040
3041 pub fn remove_attachment(&mut self, card_id: CardId) {
3042 self.attachments.retain(|&id| id != card_id);
3043 }
3044
3045 pub fn unattach_from_entity(&mut self) {
3046 self.attached_to = None;
3047 }
3048
3049 pub fn clear_intrinsic_keywords(&mut self) {
3050 self.keywords.clear();
3051 }
3052
3053 pub fn clear_all_keyword_sets(&mut self) {
3054 self.keywords.clear();
3055 self.pump_keywords.clear();
3056 self.granted_keywords.clear();
3057 }
3058
3059 pub fn clear_subtypes(&mut self) {
3060 self.type_line.subtypes.clear();
3061 }
3062
3063 pub fn clear_changed_card_types(&mut self) {
3064 self.update_types();
3065 }
3066 pub fn clear_changed_card_colors(&mut self) {
3067 self.color = ColorSet::COLORLESS;
3068 }
3069 pub fn add_changed_card_types_by_text(&mut self) {
3070 self.update_types();
3071 }
3072 pub fn remove_changed_card_types_by_text(&mut self) {
3073 self.update_types();
3074 }
3075 pub fn add_changed_card_types(&mut self) {
3076 self.update_types();
3077 }
3078 pub fn remove_changed_card_types(&mut self) {
3079 self.update_types();
3080 }
3081 pub fn update_type_cache(&mut self) {
3082 self.type_line = CardTypeLine::parse(&self.type_line.to_string());
3083 }
3084 pub fn has_changed_card_colors(&self) -> bool {
3085 !self.color.is_colorless()
3086 }
3087 pub fn add_color_by_text(&mut self, color: ColorSet) {
3088 self.add_color(color);
3089 }
3090 pub fn remove_color_by_text(&mut self) {
3091 self.remove_color();
3092 }
3093 pub fn remove_color(&mut self) {
3094 self.color = ColorSet::COLORLESS;
3095 }
3096 pub fn add_clone_state(&mut self) {
3097 self.set_s_var("CloneState", "True");
3098 }
3099 pub fn remove_clone_state(&mut self) {
3100 self.remove_s_var("CloneState");
3101 }
3102 pub fn remove_clone_states(&mut self) {
3103 self.remove_s_var("CloneState");
3104 }
3105 pub fn add_new_pt_by_text(&mut self, p: i32, t: i32) {
3106 self.base_power = Some(p);
3107 self.base_toughness = Some(t);
3108 }
3109 pub fn remove_new_p_tby_text(&mut self) {
3110 self.clear_new_pt();
3111 }
3112 pub fn add_new_pt(&mut self, p: i32, t: i32) {
3113 self.base_power = Some(p);
3114 self.base_toughness = Some(t);
3115 }
3116 pub fn remove_new_pt(&mut self) {
3117 self.clear_new_pt();
3118 }
3119 pub fn clear_new_pt(&mut self) {
3120 self.base_power = None;
3121 self.base_toughness = None;
3122 }
3123 pub fn toughness_assigns_damage(&self) -> bool {
3124 self.has_keyword("CARDNAME assigns combat damage equal to its toughness")
3125 }
3126 pub fn assign_no_combat_damage(&self) -> bool {
3127 self.has_keyword("CARDNAME assigns no combat damage")
3128 }
3129 pub fn add_pt_boost(&mut self, p: i32, t: i32) {
3130 self.power_modifier += p;
3131 self.toughness_modifier += t;
3132 }
3133 pub fn remove_pt_boost(&mut self, p: i32, t: i32) {
3134 self.power_modifier -= p;
3135 self.toughness_modifier -= t;
3136 }
3137 pub fn add_draft_action(&mut self) {
3138 self.set_s_var("DraftAction", "True");
3139 }
3140 pub fn add_intensity(&mut self, v: i32) {
3141 self.intensity += v;
3142 }
3143 pub fn has_intensity(&self) -> bool {
3144 self.intensity > 0
3145 }
3146 pub fn has_perpetual(&self) -> bool {
3147 !self.perpetual.is_empty()
3148 }
3149 pub fn get_perpetual(&self) -> &[PerpetualRecord] {
3150 &self.perpetual
3151 }
3152 pub fn add_perpetual(&mut self, p: PerpetualRecord) {
3153 self.apply_perpetual_record(p, true);
3154 }
3155 pub fn remove_perpetual(&mut self, timestamp: i64) -> bool {
3156 if let Some(idx) = self
3157 .perpetual
3158 .iter()
3159 .position(|p| p.timestamp() == timestamp)
3160 {
3161 self.perpetual.remove(idx);
3162 true
3163 } else {
3164 false
3165 }
3166 }
3167 pub fn set_perpetual(&mut self, old_card: &Card, apply_effects: bool) {
3168 self.perpetual = old_card.perpetual.clone();
3169 if apply_effects {
3170 for p in self.perpetual.clone() {
3171 self.apply_perpetual_record(p, false);
3172 }
3173 }
3174 }
3175 pub fn set_perpetual_from(&mut self, old_card: &Card) {
3176 self.set_perpetual(old_card, true);
3177 }
3178 pub fn apply_perpetual_record(&mut self, p: PerpetualRecord, remember: bool) {
3179 if remember {
3180 self.perpetual.push(p.clone());
3181 }
3182 p.apply_effect(self);
3183 }
3184 pub fn add_trigger_for_static_ability(&mut self, trig: Trigger) {
3185 self.add_trigger(trig);
3186 }
3187 pub fn visit_keywords(&self) -> Vec<String> {
3188 self.keywords.as_string_list()
3189 }
3190 pub fn update_keywords(&mut self) {
3191 self.update_keywords_cache();
3192 }
3193 pub fn add_changed_card_keywords(&mut self, kw: &str) {
3194 self.add_intrinsic_keyword(kw);
3195 }
3196 pub fn add_keyword_for_static_ability(&mut self, kw: &str) {
3197 self.granted_keywords.add(kw);
3198 }
3199 pub fn add_changed_card_keywords_by_text(&mut self, kw: &str) {
3200 self.add_intrinsic_keyword(kw);
3201 }
3202 pub fn add_changed_card_keywords_internal(&mut self, kw: &str) {
3203 self.add_intrinsic_keyword(kw);
3204 }
3205 pub fn remove_changed_card_keywords(&mut self, kw: &str) {
3206 self.remove_intrinsic_keyword(kw);
3207 }
3208 pub fn remove_changed_card_keywords_by_text(&mut self, kw: &str) {
3209 self.remove_intrinsic_keyword(kw);
3210 }
3211 pub fn clear_changed_card_keywords(&mut self) {
3212 self.keywords.clear();
3213 }
3214 pub fn clear_static_changed_card_keywords(&mut self) {
3215 self.granted_keywords.clear();
3216 }
3217 pub fn add_hidden_extrinsic_keywords(&mut self, kw: &str) {
3218 self.granted_keywords.add(kw);
3219 }
3220 pub fn remove_hidden_extrinsic_keywords(&mut self, kw: &str) {
3221 self.granted_keywords.remove(kw);
3222 }
3223 pub fn remove_hidden_extrinsic_keyword(&mut self, kw: &str) {
3224 self.granted_keywords.remove(kw);
3225 }
3226 pub fn has_start_of_keyword(&self, prefix: &str) -> bool {
3227 self.keywords.iter_strings().any(|k| k.starts_with(prefix))
3228 }
3229 pub fn has_start_of_un_hidden_keyword(&self, prefix: &str) -> bool {
3230 self.has_start_of_keyword(prefix)
3231 }
3232 pub fn has_any_keyword(&self) -> bool {
3233 !self.keywords.as_string_list().is_empty()
3234 || !self.granted_keywords.as_string_list().is_empty()
3235 || !self.pump_keywords.as_string_list().is_empty()
3236 }
3237 pub fn add_cant_have_keyword(&mut self, kw: &str) {
3238 self.cant_have_keywords.insert(kw.to_ascii_lowercase());
3239 }
3240 pub fn remove_cant_have_keyword(&mut self, kw: &str) {
3241 self.cant_have_keywords.remove(&kw.to_ascii_lowercase());
3242 }
3243 pub fn add_changed_text_color_word(&mut self, from: &str, to: &str) {
3244 self.set_s_var(format!("TextColor:{from}"), to);
3245 }
3246 pub fn remove_changed_text_color_word(&mut self, from: &str) {
3247 self.remove_s_var(&format!("TextColor:{from}"));
3248 }
3249 pub fn add_changed_text_type_word(&mut self, from: &str, to: &str) {
3250 self.set_s_var(format!("TextType:{from}"), to);
3251 }
3252 pub fn remove_changed_text_type_word(&mut self, from: &str) {
3253 self.remove_s_var(&format!("TextType:{from}"));
3254 }
3255 pub fn copy_changed_text_from(&mut self, other: &Card) {
3256 for (k, v) in &other.svars {
3257 if k.starts_with("TextColor:") || k.starts_with("TextType:") {
3258 self.svars.insert(k.clone(), v.clone());
3259 }
3260 }
3261 }
3262 pub fn has_playable_land_face(&self) -> bool {
3263 self.is_land()
3264 || self
3265 .other_part
3266 .as_ref()
3267 .map(|p| p.type_line.is_land())
3268 .unwrap_or(false)
3269 }
3270 pub fn phase(&mut self) {
3271 self.phased_out = !self.phased_out;
3272 }
3273 pub fn associated_with_color(&self, game: &GameState, color: &str) -> bool {
3274 let mut colors = HashSet::new();
3275 colors.insert(color.to_string());
3276 forge_foundation::Color::from_name(&color.to_ascii_lowercase())
3277 .map(|parsed| self.color.has_any_color(parsed.mask()))
3278 .unwrap_or(false)
3279 || self.can_produce_color_mana(game, &colors)
3280 }
3281 pub fn has_no_name(&self) -> bool {
3282 self.card_name.trim().is_empty()
3283 }
3284 pub fn shares_name_with(&self, other: &Card) -> bool {
3285 self.card_name.eq_ignore_ascii_case(&other.card_name)
3286 }
3287 pub fn has_creature_type(&self, creature_type: &str) -> bool {
3288 if !self.is_creature() && !self.type_line.core_types.contains(&CoreType::Kindred) {
3289 return false;
3290 }
3291 if self.type_line.has_subtype(creature_type) {
3292 return true;
3293 }
3294 self.has_keyword("Changeling") && crate::game::TypeRegistry::is_creature_type(creature_type)
3295 }
3296 pub fn has_subtype(&self, subtype: &str) -> bool {
3297 self.type_line.has_subtype(subtype) || self.has_creature_type(subtype)
3298 }
3299 pub fn shares_color_with(&self, other: &Card) -> bool {
3300 (self.color.has_white() && other.color.has_white())
3301 || (self.color.has_blue() && other.color.has_blue())
3302 || (self.color.has_black() && other.color.has_black())
3303 || (self.color.has_red() && other.color.has_red())
3304 || (self.color.has_green() && other.color.has_green())
3305 || (self.color.is_colorless() && other.color.is_colorless())
3306 }
3307 pub fn shares_cmc_with(&self, other: &Card) -> bool {
3308 self.mana_value() == other.mana_value()
3309 }
3310 pub fn shares_creature_type_with(&self, other: &Card) -> bool {
3311 crate::game::TypeRegistry::creature_types()
3312 .iter()
3313 .any(|creature_type| {
3314 self.has_creature_type(creature_type) && other.has_creature_type(creature_type)
3315 })
3316 }
3317 pub fn shares_land_type_with(&self, other: &Card) -> bool {
3318 self.shares_creature_type_with(other) && self.is_land() && other.is_land()
3319 }
3320 pub fn shares_permanent_type_with(&self, other: &Card) -> bool {
3321 (self.is_creature() && other.is_creature())
3322 || (self.is_land() && other.is_land())
3323 || (self.type_line.is_artifact() && other.type_line.is_artifact())
3324 || (self.type_line.is_enchantment() && other.type_line.is_enchantment())
3325 || (self.type_line.is_planeswalker() && other.type_line.is_planeswalker())
3326 }
3327 pub fn shares_card_type_with(&self, other: &Card) -> bool {
3328 self.shares_permanent_type_with(other)
3329 }
3330 pub fn shares_all_card_types_with(&self, other: &Card) -> bool {
3331 self.type_line.core_types == other.type_line.core_types
3332 }
3333 pub fn shares_controller_with(&self, other: &Card) -> bool {
3334 self.controller == other.controller
3335 }
3336 pub fn has_a_basic_land_type(&self) -> bool {
3337 self.type_line.has_subtype("Plains")
3338 || self.type_line.has_subtype("Island")
3339 || self.type_line.has_subtype("Swamp")
3340 || self.type_line.has_subtype("Mountain")
3341 || self.type_line.has_subtype("Forest")
3342 }
3343 pub fn has_a_non_basic_land_type(&self) -> bool {
3344 self.is_land() && !self.has_a_basic_land_type()
3345 }
3346 pub fn has_dealt_damage_to_opponent_this_turn(&self) -> bool {
3347 self.total_damage_done_this_turn > 0
3348 }
3349 pub fn has_been_dealt_deathtouch_damage(&self) -> bool {
3350 self.has_deathtouch_damage
3351 }
3352 pub fn has_been_dealt_excess_damage_this_turn(&self) -> bool {
3353 self.damage > self.toughness()
3354 }
3355 pub fn log_excess_damage(&mut self) {
3356 self.set_s_var("ExcessDamageLogged", "True");
3357 }
3358 pub fn add_assigned_damage(&mut self, amount: i32) {
3359 self.assigned_damage += amount;
3360 }
3361 pub fn clear_assigned_damage(&mut self) {
3362 self.assigned_damage = 0;
3363 }
3364 pub fn can_damage_prevented(&self) -> bool {
3365 !self.has_keyword("Damage can't be prevented")
3366 }
3367 pub fn static_replace_damage(&self, amount: i32) -> i32 {
3368 amount
3369 }
3370 pub fn add_damage_after_prevention(&mut self, amount: i32) -> i32 {
3371 let dealt = if self.can_be_dealt_damage() {
3372 amount.max(0)
3373 } else {
3374 0
3375 };
3376 if dealt <= 0 {
3377 return 0;
3378 }
3379 if self.type_line.is_planeswalker() {
3380 self.remove_counter(&CounterType::Loyalty, dealt);
3381 }
3382 if self.type_line.core_types.contains(&CoreType::Battle) {
3383 self.remove_counter(&CounterType::Named("DEFENSE".to_string()), dealt);
3384 }
3385 if self.is_creature() {
3386 self.damage += dealt;
3387 }
3388 dealt
3389 }
3390 pub fn border_color(&self) -> &'static str {
3391 if self.color.is_colorless() {
3392 "Colorless"
3393 } else if self.color.has_white() {
3394 "White"
3395 } else if self.color.has_blue() {
3396 "Blue"
3397 } else if self.color.has_black() {
3398 "Black"
3399 } else if self.color.has_red() {
3400 "Red"
3401 } else {
3402 "Green"
3403 }
3404 }
3405 pub fn was_discarded(&self) -> bool {
3406 self.discarded
3407 }
3408 pub fn was_surveilled(&self) -> bool {
3409 self.surveilled
3410 }
3411 pub fn was_milled(&self) -> bool {
3412 self.milled
3413 }
3414 pub fn clear_ring_bearer(&mut self) {
3415 self.remove_s_var("RingBearer");
3416 }
3417 pub fn add_saddled_by_this_turn(&mut self, card: CardId) {
3418 self.set_s_var("SaddledBy", format!("{}", card.0));
3419 }
3420 pub fn reset_saddled(&mut self) {
3421 self.remove_s_var("SaddledBy");
3422 }
3423 pub fn can_specialize(&self) -> bool {
3424 self.has_keyword("Specialize")
3425 }
3426 pub fn can_crew(&self) -> bool {
3427 self.is_permanent()
3428 }
3429 pub fn reset_times_crewed_this_turn(&mut self) {
3430 self.times_crewed_this_turn = 0;
3431 }
3432 pub fn becomes_crewed(&mut self) {
3433 self.is_crewed = true;
3434 self.times_crewed_this_turn += 1;
3435 }
3436 pub fn reset_crewed(&mut self) {
3437 self.is_crewed = false;
3438 }
3439 pub fn add_crewed_by_this_turn(&mut self, _card: CardId) {
3440 self.times_crewed_this_turn += 1;
3441 }
3442 pub fn visit_attraction(&mut self) {
3443 self.visited_this_turn = true;
3444 }
3445 pub fn was_visited_this_turn(&self) -> bool {
3446 self.visited_this_turn
3447 }
3448 pub fn animate_bestow(&mut self) {
3449 self.is_bestowed = false;
3450 }
3451 pub fn unanimate_bestow(&mut self) {
3452 self.is_bestowed = true;
3453 }
3454 pub fn equals_with_game_timestamp(&self, other: &Card) -> bool {
3455 self.id == other.id && self.zone_timestamp == other.zone_timestamp
3456 }
3457 pub fn update_world_timestamp(&mut self) {
3458 self.zone_timestamp = self.zone_timestamp.saturating_add(1);
3459 }
3460 pub fn can_be_discarded_by(&self, _player: PlayerId) -> bool {
3461 true
3462 }
3463 pub fn can_be_destroyed(&self) -> bool {
3464 !self.has_indestructible()
3465 }
3466 pub fn can_be_targeted_by(&self, _player: PlayerId) -> bool {
3467 true
3468 }
3469 pub fn cant_be_attached_msg(&self) -> Option<String> {
3470 None
3471 }
3472 pub fn can_be_sacrificed_by(&self, _player: PlayerId) -> bool {
3473 true
3474 }
3475 pub fn can_exiled_by(&self, _player: PlayerId) -> bool {
3476 true
3477 }
3478 pub fn update_static_abilities(&mut self) {
3479 self.recompute_changed_card_traits();
3480 }
3481 pub fn update_triggers(&mut self) {
3482 self.recompute_changed_card_traits();
3483 }
3484 pub fn update_replacement_effects(&mut self) {
3485 self.recompute_changed_card_traits();
3486 }
3487 pub fn was_cast(&self) -> bool {
3488 self.cast_from.is_some()
3492 }
3493 pub fn on_end_of_combat(&mut self) {
3494 self.assigned_damage = 0;
3495 }
3496 pub fn on_cleanup_phase(&mut self) {
3497 self.became_target_this_turn = false;
3498 self.visited_this_turn = false;
3499 self.damage_prevention = 0;
3500 }
3501 pub fn has_etb_trigger(&self) -> bool {
3502 self.triggers.iter().any(|t| {
3503 t.kind == crate::trigger::TriggerType::ChangesZone
3504 && t.destination_zone() == Some(ZoneType::Battlefield)
3505 })
3506 }
3507 pub fn has_etb_replacement(&self) -> bool {
3508 self.has_replacement_effect()
3509 }
3510 pub fn can_move_to_command_zone(&self) -> bool {
3511 self.is_commander && self.move_to_command_zone
3512 }
3513 pub fn from_paper_card(&mut self) {
3514 self.is_token = false;
3515 }
3516 pub fn cleanup_copied_changes_from(&mut self) {
3517 self.clear_changed_card_traits();
3518 }
3519 pub fn activated_this_turn(&self) -> bool {
3520 self.ability_activated_this_turn > 0
3521 }
3522 pub fn add_ability_activated(&mut self) {
3523 self.ability_activated_this_turn += 1;
3524 }
3525 pub fn add_ability_activated_for(
3526 &mut self,
3527 ability: Option<&crate::spellability::SpellAbility>,
3528 ) {
3529 self.add_ability_activated_for_with_limit_increase(ability, false);
3530 }
3531 pub fn add_ability_activated_for_with_limit_increase(
3532 &mut self,
3533 ability: Option<&crate::spellability::SpellAbility>,
3534 loyalty_limit_increase: bool,
3535 ) {
3536 if let Some(ability) = ability {
3537 self.number_turn_activations.add(ability);
3538 self.number_game_activations.add(ability);
3539 if ability.ir.pw_ability {
3540 self.add_planeswalker_ability_activated(loyalty_limit_increase);
3541 }
3542 }
3543 self.add_ability_activated();
3544 }
3545 pub fn add_ability_resolved(&mut self) {
3546 self.ability_resolved_this_turn += 1;
3547 }
3548 pub fn add_ability_resolved_for(
3549 &mut self,
3550 ability: Option<&crate::spellability::SpellAbility>,
3551 ) {
3552 if let Some(ability) = ability {
3553 self.number_ability_resolved.add(ability);
3554 }
3555 self.add_ability_resolved();
3556 }
3557 pub fn get_ability_activated_this_turn(
3558 &self,
3559 ability: Option<&crate::spellability::SpellAbility>,
3560 ) -> u32 {
3561 ability
3562 .map(|ability| self.number_turn_activations.get(ability) as u32)
3563 .unwrap_or(0)
3564 }
3565 pub fn get_ability_activated_this_game(
3566 &self,
3567 ability: Option<&crate::spellability::SpellAbility>,
3568 ) -> u32 {
3569 ability
3570 .map(|ability| self.number_game_activations.get(ability) as u32)
3571 .unwrap_or(0)
3572 }
3573 pub fn get_ability_resolved_this_turn(
3574 &self,
3575 ability: Option<&crate::spellability::SpellAbility>,
3576 ) -> u32 {
3577 ability
3578 .map(|ability| self.number_ability_resolved.get(ability) as u32)
3579 .unwrap_or(0)
3580 }
3581 pub fn get_ability_resolved_this_turn_activators(
3582 &self,
3583 ability: Option<&crate::spellability::SpellAbility>,
3584 ) -> Vec<crate::ids::PlayerId> {
3585 ability
3586 .map(|ability| self.number_ability_resolved.get_activators(ability))
3587 .unwrap_or_default()
3588 }
3589 pub fn reset_ability_resolved_this_turn(&mut self) {
3590 self.ability_resolved_this_turn = 0;
3591 self.number_ability_resolved.clear();
3592 }
3593 pub fn add_chosen_modes(&mut self, modes: Vec<usize>, turn: u32) {
3594 self.chosen_modes = Some(modes);
3595 self.chosen_modes_turn = Some(turn);
3596 }
3597 pub fn reset_chosen_mode_turn(&mut self) {
3598 self.chosen_modes_turn = None;
3599 self.chosen_modes = None;
3600 }
3601 pub fn add_planeswalker_ability_activated(&mut self, loyalty_limit_increase: bool) {
3602 self.planeswalker_abilities_activated += 1;
3603 if self.planeswalker_abilities_activated == 2 && loyalty_limit_increase {
3604 self.planeswalker_activation_limit_used = true;
3605 }
3606 }
3607 pub fn planeswalker_activation_limit_used(&self) -> bool {
3608 self.planeswalker_activation_limit_used
3609 }
3610 pub fn reset_activations_per_turn(&mut self) {
3611 self.ability_activated_this_turn = 0;
3612 self.number_turn_activations.clear();
3613 self.planeswalker_abilities_activated = 0;
3614 self.planeswalker_activation_limit_used = false;
3615 }
3616 pub fn add_can_block_additional(&mut self, n: i32) {
3617 self.can_block_additional += n;
3618 }
3619 pub fn remove_can_block_additional(&mut self, n: i32) {
3620 self.can_block_additional = (self.can_block_additional - n).max(0);
3621 }
3622 pub fn can_block_additional(&self) -> i32 {
3623 self.can_block_additional
3624 }
3625 pub fn add_can_block_any(&mut self) {
3626 self.can_block_any = true;
3627 }
3628 pub fn remove_can_block_any(&mut self) {
3629 self.can_block_any = false;
3630 }
3631 pub fn can_block_any(&self) -> bool {
3632 self.can_block_any
3633 }
3634 pub fn ignore_legend_rule(&self) -> bool {
3635 self.ignore_legend_rule_flag
3636 }
3637 pub fn attack_vigilance(&self) -> bool {
3638 self.has_vigilance()
3639 }
3640 pub fn unlock_room(&mut self) {
3641 self.set_s_var("RoomLocked", "False");
3642 }
3643 pub fn lock_room(&mut self) {
3644 self.set_s_var("RoomLocked", "True");
3645 }
3646 pub fn update_rooms(&mut self) {
3647 if !self.has_s_var("RoomLocked") {
3648 self.set_s_var("RoomLocked", "False");
3649 }
3650 }
3651
3652 pub fn is_modal(&self) -> bool {
3659 self.other_part.as_ref().is_some_and(|other| other.is_modal)
3660 }
3661
3662 pub fn transform(&mut self) {
3663 if let Some(other) = self.other_part.as_mut() {
3664 std::mem::swap(&mut self.card_name, &mut other.name);
3665 std::mem::swap(&mut self.oracle_text, &mut other.oracle_text);
3666 std::mem::swap(&mut self.type_line, &mut other.type_line);
3667 std::mem::swap(&mut self.mana_cost, &mut other.mana_cost);
3668 std::mem::swap(&mut self.color, &mut other.color);
3669 std::mem::swap(&mut self.base_power, &mut other.base_power);
3670 std::mem::swap(&mut self.base_toughness, &mut other.base_toughness);
3671 std::mem::swap(&mut self.keywords, &mut other.keywords);
3672 std::mem::swap(&mut self.abilities, &mut other.abilities);
3673 std::mem::swap(&mut self.triggers, &mut other.triggers);
3674 std::mem::swap(&mut self.static_abilities, &mut other.static_abilities);
3675 std::mem::swap(
3676 &mut self.replacement_effects,
3677 &mut other.replacement_effects,
3678 );
3679 std::mem::swap(&mut self.svars, &mut other.svars);
3680
3681 self.power_modifier = 0;
3683 self.toughness_modifier = 0;
3684 self.damage = 0;
3685 self.granted_keywords.clear();
3686
3687 self.activated_abilities = self
3689 .abilities
3690 .iter()
3691 .enumerate()
3692 .filter_map(|(i, raw)| {
3693 parse_or_warn(parse_activated_ability(raw, i), "ActivatedAbility", raw)
3694 })
3695 .collect();
3696 self.base_ability_count = self.activated_abilities.len();
3697 self.base_trigger_count = self.triggers.len();
3698 self.parsed_svar_cache.clear();
3699 self.refresh_action_specs();
3700
3701 let mut res = std::mem::take(&mut self.replacement_effects);
3703 for re in &mut res {
3704 re.set_host_card(self);
3705 }
3706 self.replacement_effects = res;
3707
3708 self.is_transformed = !self.is_transformed;
3709
3710 self.reset_changed_card_traits_baseline();
3713 self.recompute_changed_card_traits();
3714 }
3715 }
3716
3717 fn activated_to_spell_abilities(&self, list: &[ActivatedAbility]) -> Vec<SpellAbility> {
3718 list.iter()
3719 .map(|ab| {
3720 let mut sa = crate::spellability::build_spell_ability_from_host_card(
3721 self,
3722 &ab.ability_text,
3723 self.controller,
3724 );
3725 sa.is_activated = true;
3726 sa
3727 })
3728 .collect()
3729 }
3730
3731 fn spell_to_activated_abilities(list: &[SpellAbility]) -> Vec<ActivatedAbility> {
3732 list.iter()
3733 .enumerate()
3734 .filter_map(|(i, sa)| parse_activated_ability(&sa.ability_text, i))
3735 .collect()
3736 }
3737
3738 fn capture_changed_card_traits_baseline_if_needed(&mut self) {
3739 if self.trait_base_activated_abilities.is_none() {
3740 self.trait_base_activated_abilities = Some(self.activated_abilities.clone());
3741 self.trait_base_triggers = Some(self.triggers.clone());
3742 self.trait_base_replacement_effects = Some(self.replacement_effects.clone());
3743 self.trait_base_static_abilities = Some(self.static_abilities.clone());
3744 self.trait_base_keywords = Some(self.keywords.clone());
3745 }
3746 }
3747
3748 fn reset_changed_card_traits_baseline(&mut self) {
3749 self.trait_base_activated_abilities = Some(self.activated_abilities.clone());
3750 self.trait_base_triggers = Some(self.triggers.clone());
3751 self.trait_base_replacement_effects = Some(self.replacement_effects.clone());
3752 self.trait_base_static_abilities = Some(self.static_abilities.clone());
3753 self.trait_base_keywords = Some(self.keywords.clone());
3754 }
3755
3756 pub(crate) fn reset_changed_card_traits_baseline_to_current(&mut self) {
3757 self.reset_changed_card_traits_baseline();
3758 self.recompute_changed_card_traits();
3759 }
3760
3761 fn recompute_changed_card_traits(&mut self) {
3762 let Some(base_activated) = self.trait_base_activated_abilities.clone() else {
3763 return;
3764 };
3765 let Some(base_triggers) = self.trait_base_triggers.clone() else {
3766 return;
3767 };
3768 let Some(base_replacements) = self.trait_base_replacement_effects.clone() else {
3769 return;
3770 };
3771 let Some(base_static) = self.trait_base_static_abilities.clone() else {
3772 return;
3773 };
3774 let Some(base_keywords) = self.trait_base_keywords.clone() else {
3775 return;
3776 };
3777
3778 let mut spell_abilities = self.activated_to_spell_abilities(&base_activated);
3779 let mut triggers = base_triggers;
3780 let mut replacements = base_replacements;
3781 let mut static_abilities = base_static;
3782 let mut keywords = base_keywords;
3783
3784 for layer in self.changed_card_traits_by_text.values() {
3785 spell_abilities = crate::card::card_state::apply_spell_ability(layer, spell_abilities);
3786 triggers = crate::card::card_state::apply_trigger(layer, triggers);
3787 replacements = crate::card::card_state::apply_replacement_effect(layer, replacements);
3788 static_abilities =
3789 crate::card::card_state::apply_static_ability(layer, static_abilities);
3790 keywords = crate::card::card_state::apply_keywords(layer, keywords);
3791 }
3792 for layer in self.changed_card_traits.values() {
3793 spell_abilities = crate::card::card_state::apply_spell_ability(layer, spell_abilities);
3794 triggers = crate::card::card_state::apply_trigger(layer, triggers);
3795 replacements = crate::card::card_state::apply_replacement_effect(layer, replacements);
3796 static_abilities =
3797 crate::card::card_state::apply_static_ability(layer, static_abilities);
3798 keywords = crate::card::card_state::apply_keywords(layer, keywords);
3799 }
3800
3801 self.activated_abilities = Self::spell_to_activated_abilities(&spell_abilities);
3802 self.triggers = triggers;
3803 self.replacement_effects = replacements;
3804 self.static_abilities = static_abilities;
3805 self.keywords = keywords;
3806 }
3807
3808 pub fn add_changed_card_traits(
3810 &mut self,
3811 layer: card_trait_changes::CardTraitChanges,
3812 timestamp: i64,
3813 static_id: i64,
3814 ) {
3815 self.capture_changed_card_traits_baseline_if_needed();
3816 self.changed_card_traits
3817 .insert((timestamp, static_id), layer);
3818 self.recompute_changed_card_traits();
3819 }
3820
3821 pub fn add_changed_card_traits_by_text(
3823 &mut self,
3824 layer: card_trait_changes::CardTraitChanges,
3825 timestamp: i64,
3826 static_id: i64,
3827 ) {
3828 self.capture_changed_card_traits_baseline_if_needed();
3829 self.changed_card_traits_by_text
3830 .insert((timestamp, static_id), layer);
3831 self.recompute_changed_card_traits();
3832 }
3833
3834 pub fn remove_changed_card_traits(&mut self, timestamp: i64, static_id: i64) -> bool {
3836 if self
3837 .changed_card_traits
3838 .remove(&(timestamp, static_id))
3839 .is_none()
3840 {
3841 return false;
3842 }
3843 if self.changed_card_traits.is_empty() && self.changed_card_traits_by_text.is_empty() {
3844 if let Some(v) = self.trait_base_activated_abilities.take() {
3845 self.activated_abilities = v;
3846 }
3847 if let Some(v) = self.trait_base_triggers.take() {
3848 self.triggers = v;
3849 }
3850 if let Some(v) = self.trait_base_replacement_effects.take() {
3851 self.replacement_effects = v;
3852 }
3853 if let Some(v) = self.trait_base_static_abilities.take() {
3854 self.static_abilities = v;
3855 }
3856 if let Some(v) = self.trait_base_keywords.take() {
3857 self.keywords = v;
3858 }
3859 return true;
3860 }
3861
3862 self.recompute_changed_card_traits();
3863 true
3864 }
3865
3866 pub fn remove_changed_card_traits_by_text(&mut self, timestamp: i64, static_id: i64) -> bool {
3868 if self
3869 .changed_card_traits_by_text
3870 .remove(&(timestamp, static_id))
3871 .is_none()
3872 {
3873 return false;
3874 }
3875 if self.changed_card_traits.is_empty() && self.changed_card_traits_by_text.is_empty() {
3876 if let Some(v) = self.trait_base_activated_abilities.take() {
3877 self.activated_abilities = v;
3878 }
3879 if let Some(v) = self.trait_base_triggers.take() {
3880 self.triggers = v;
3881 }
3882 if let Some(v) = self.trait_base_replacement_effects.take() {
3883 self.replacement_effects = v;
3884 }
3885 if let Some(v) = self.trait_base_static_abilities.take() {
3886 self.static_abilities = v;
3887 }
3888 if let Some(v) = self.trait_base_keywords.take() {
3889 self.keywords = v;
3890 }
3891 return true;
3892 }
3893
3894 self.recompute_changed_card_traits();
3895 true
3896 }
3897
3898 pub fn clear_changed_card_traits(&mut self) {
3900 self.changed_card_traits.clear();
3901 self.changed_card_traits_by_text.clear();
3902 if let Some(v) = self.trait_base_activated_abilities.take() {
3903 self.activated_abilities = v;
3904 }
3905 if let Some(v) = self.trait_base_triggers.take() {
3906 self.triggers = v;
3907 }
3908 if let Some(v) = self.trait_base_replacement_effects.take() {
3909 self.replacement_effects = v;
3910 }
3911 if let Some(v) = self.trait_base_static_abilities.take() {
3912 self.static_abilities = v;
3913 }
3914 if let Some(v) = self.trait_base_keywords.take() {
3915 self.keywords = v;
3916 }
3917 }
3918
3919 pub fn clear_static_layer_changed_card_traits(&mut self) {
3924 let before = self.changed_card_traits.len();
3925 self.changed_card_traits
3926 .retain(|(_, static_id), _| *static_id >= 0);
3927 if self.changed_card_traits.len() == before {
3928 return;
3929 }
3930 if self.changed_card_traits.is_empty() && self.changed_card_traits_by_text.is_empty() {
3931 if let Some(v) = self.trait_base_activated_abilities.take() {
3932 self.activated_abilities = v;
3933 }
3934 if let Some(v) = self.trait_base_triggers.take() {
3935 self.triggers = v;
3936 }
3937 if let Some(v) = self.trait_base_replacement_effects.take() {
3938 self.replacement_effects = v;
3939 }
3940 if let Some(v) = self.trait_base_static_abilities.take() {
3941 self.static_abilities = v;
3942 }
3943 if let Some(v) = self.trait_base_keywords.take() {
3944 self.keywords = v;
3945 }
3946 return;
3947 }
3948
3949 self.recompute_changed_card_traits();
3950 }
3951
3952 pub fn remove_changed_state(&mut self) {
3953 self.clear_changed_card_traits();
3954 }
3955}
3956
3957impl HasSVars for Card {
3958 fn get_svar(&self, name: &str) -> Option<&str> {
3959 self.get_s_var(name)
3960 }
3961
3962 fn set_svar(&mut self, name: String, value: String) {
3963 self.set_s_var(name, value);
3964 }
3965
3966 fn set_svars(&mut self, new_svars: std::collections::HashMap<String, String>) {
3967 self.set_svars_map(new_svars.into_iter().collect());
3968 }
3969
3970 fn get_svars(&self) -> &std::collections::HashMap<String, String> {
3971 panic!("Card::get_svars is not supported yet; use get_s_var/has_s_var parity accessors");
3972 }
3973
3974 fn remove_svar(&mut self, var: &str) {
3975 self.remove_s_var(var);
3976 }
3977}
3978
3979#[cfg(test)]
3980mod tests {
3981 use super::*;
3982 use std::collections::HashSet;
3983
3984 use forge_carddb::parse_card_script;
3985 use forge_foundation::ManaCost;
3986
3987 #[test]
3988 fn card_power_toughness() {
3989 let mut card = Card::new(
3990 CardId(0),
3991 "Test".to_string(),
3992 PlayerId(0),
3993 CardTypeLine::parse("Creature Bear"),
3994 ManaCost::parse("1 G"),
3995 ColorSet::GREEN,
3996 Some(2),
3997 Some(2),
3998 vec![],
3999 vec![],
4000 );
4001 assert_eq!(card.power(), 2);
4002 assert_eq!(card.toughness(), 2);
4003
4004 card.add_counter(&CounterType::P1P1, 1);
4005 assert_eq!(card.power(), 3);
4006 assert_eq!(card.toughness(), 3);
4007 }
4008
4009 #[test]
4010 fn can_attack() {
4011 let mut card = Card::new(
4012 CardId(0),
4013 "Test".to_string(),
4014 PlayerId(0),
4015 CardTypeLine::parse("Creature Bear"),
4016 ManaCost::parse("1 G"),
4017 ColorSet::GREEN,
4018 Some(2),
4019 Some(2),
4020 vec![],
4021 vec![],
4022 );
4023 card.zone = ZoneType::Battlefield;
4024 assert!(!card.can_attack()); card.summoning_sick = false;
4027 assert!(card.can_attack());
4028
4029 card.tapped = true;
4030 assert!(!card.can_attack()); }
4032
4033 #[test]
4034 fn haste_bypasses_summoning_sickness() {
4035 let mut card = Card::new(
4036 CardId(0),
4037 "Test".to_string(),
4038 PlayerId(0),
4039 CardTypeLine::parse("Creature Bear"),
4040 ManaCost::parse("1 G"),
4041 ColorSet::GREEN,
4042 Some(2),
4043 Some(2),
4044 vec!["Haste".to_string()],
4045 vec![],
4046 );
4047 card.zone = ZoneType::Battlefield;
4048 assert!(card.can_attack()); }
4050
4051 #[test]
4052 fn keyword_helpers() {
4053 let card = Card::new(
4054 CardId(0),
4055 "Test".to_string(),
4056 PlayerId(0),
4057 CardTypeLine::parse("Creature Bear"),
4058 ManaCost::parse("1 G"),
4059 ColorSet::GREEN,
4060 Some(2),
4061 Some(2),
4062 vec![
4063 "Hexproof".to_string(),
4064 "Menace".to_string(),
4065 "Indestructible".to_string(),
4066 ],
4067 vec![],
4068 );
4069 assert!(card.has_hexproof());
4070 assert!(card.has_menace());
4071 assert!(card.has_indestructible());
4072 assert!(!card.has_shroud());
4073 assert!(!card.has_fear());
4074 assert!(!card.has_shadow());
4075 }
4076
4077 #[test]
4078 fn protection_from_color() {
4079 let knight = Card::new(
4080 CardId(0),
4081 "White Knight".to_string(),
4082 PlayerId(0),
4083 CardTypeLine::parse("Creature Knight"),
4084 ManaCost::parse("W W"),
4085 ColorSet::WHITE,
4086 Some(2),
4087 Some(2),
4088 vec!["Protection from black".to_string()],
4089 vec![],
4090 );
4091 let black_source = Card::new(
4092 CardId(1),
4093 "Doom Blade".to_string(),
4094 PlayerId(1),
4095 CardTypeLine::parse("Instant"),
4096 ManaCost::parse("1 B"),
4097 ColorSet::BLACK,
4098 None,
4099 None,
4100 vec![],
4101 vec![],
4102 );
4103 let green_source = Card::new(
4104 CardId(2),
4105 "Giant Growth".to_string(),
4106 PlayerId(1),
4107 CardTypeLine::parse("Instant"),
4108 ManaCost::parse("G"),
4109 ColorSet::GREEN,
4110 None,
4111 None,
4112 vec![],
4113 vec![],
4114 );
4115 assert!(knight.is_protected_from(&black_source));
4116 assert!(!knight.is_protected_from(&green_source));
4117 assert!(knight.has_protection_from("black"));
4118 assert!(!knight.has_protection_from("red"));
4119 }
4120
4121 #[test]
4122 fn ward_and_toxic_parsing() {
4123 let ward_card = Card::new(
4124 CardId(0),
4125 "Ward Bear".to_string(),
4126 PlayerId(0),
4127 CardTypeLine::parse("Creature Bear"),
4128 ManaCost::parse("1 U"),
4129 ColorSet::BLUE,
4130 Some(2),
4131 Some(2),
4132 vec!["Ward:2".to_string()],
4133 vec![],
4134 );
4135 assert_eq!(ward_card.get_ward_cost(), Some("2".to_string()));
4136
4137 let toxic_card = Card::new(
4138 CardId(1),
4139 "Toxic Elf".to_string(),
4140 PlayerId(0),
4141 CardTypeLine::parse("Creature Elf"),
4142 ManaCost::parse("G"),
4143 ColorSet::GREEN,
4144 Some(1),
4145 Some(1),
4146 vec!["Toxic:1".to_string()],
4147 vec![],
4148 );
4149 assert_eq!(toxic_card.get_toxic_count(), Some(1));
4150
4151 let plain = Card::new(
4153 CardId(2),
4154 "Bear".to_string(),
4155 PlayerId(0),
4156 CardTypeLine::parse("Creature Bear"),
4157 ManaCost::parse("1 G"),
4158 ColorSet::GREEN,
4159 Some(2),
4160 Some(2),
4161 vec![],
4162 vec![],
4163 );
4164 assert_eq!(plain.get_ward_cost(), None);
4165 assert_eq!(plain.get_toxic_count(), None);
4166 }
4167
4168 #[test]
4169 fn from_rules_copies_attraction_lights() {
4170 let rules = parse_card_script(
4171 "Name:Balloon Stand\nTypes:Artifact Attraction\nLights: 2 4 6\nOracle:Test.",
4172 )
4173 .expect("card script should parse");
4174 let card = Card::from_rules(&rules, PlayerId(0));
4175 assert_eq!(card.attraction_lights, vec![2, 4, 6]);
4176 assert!(card.has_attraction_light(4));
4177 assert!(!card.has_attraction_light(3));
4178 }
4179
4180 #[test]
4181 fn can_produce_color_mana_uses_mana_abilities_and_reflection() {
4182 let mut game = GameState::new(&["Alice", "Bob"], 20);
4183 let p0 = PlayerId(0);
4184
4185 let white_land = Card::new(
4186 CardId(0),
4187 "White Source".to_string(),
4188 p0,
4189 CardTypeLine::parse("Land"),
4190 ManaCost::parse(""),
4191 ColorSet::COLORLESS,
4192 None,
4193 None,
4194 vec![],
4195 vec!["AB$ Mana | Cost$ T | Produced$ W | SpellDescription$ Add {W}.".to_string()],
4196 );
4197 let reflecting_pool = Card::new(
4198 CardId(1),
4199 "Reflecting Pool".to_string(),
4200 p0,
4201 CardTypeLine::parse("Land"),
4202 ManaCost::parse(""),
4203 ColorSet::COLORLESS,
4204 None,
4205 None,
4206 vec![],
4207 vec!["AB$ ManaReflected | Cost$ T | Valid$ Land.YouCtrl | ReflectProperty$ Produce | ColorOrType$ Type | Produced$ W | SpellDescription$ Add one mana of any type that a land you control could produce.".to_string()],
4208 );
4209
4210 let white_id = game.create_card(white_land);
4211 let pool_id = game.create_card(reflecting_pool);
4212 game.move_card(white_id, ZoneType::Battlefield, p0);
4213 game.move_card(pool_id, ZoneType::Battlefield, p0);
4214
4215 let mut white = HashSet::new();
4216 white.insert("white".to_string());
4217 assert!(game.card(white_id).can_produce_color_mana(&game, &white));
4218 assert!(game.card(pool_id).can_produce_color_mana(&game, &white));
4219 }
4220
4221 #[test]
4222 fn can_produce_same_mana_type_with_uses_mana_ability_overlap() {
4223 let mut game = GameState::new(&["Alice", "Bob"], 20);
4224 let p0 = PlayerId(0);
4225
4226 let island = Card::new(
4227 CardId(0),
4228 "Island Source".to_string(),
4229 p0,
4230 CardTypeLine::parse("Land"),
4231 ManaCost::parse(""),
4232 ColorSet::COLORLESS,
4233 None,
4234 None,
4235 vec![],
4236 vec!["AB$ Mana | Cost$ T | Produced$ U | SpellDescription$ Add {U}.".to_string()],
4237 );
4238 let prism = Card::new(
4239 CardId(1),
4240 "Prism".to_string(),
4241 p0,
4242 CardTypeLine::parse("Artifact"),
4243 ManaCost::parse("2"),
4244 ColorSet::COLORLESS,
4245 None,
4246 None,
4247 vec![],
4248 vec!["AB$ Mana | Cost$ T | Produced$ U | SpellDescription$ Add {U}.".to_string()],
4249 );
4250
4251 let island_id = game.create_card(island);
4252 let prism_id = game.create_card(prism);
4253 game.move_card(island_id, ZoneType::Battlefield, p0);
4254 game.move_card(prism_id, ZoneType::Battlefield, p0);
4255
4256 assert!(game
4257 .card(prism_id)
4258 .can_produce_same_mana_type_with(&game, game.card(island_id)));
4259 }
4260}