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