Skip to main content

manabrew_engine/card/
mod.rs

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
37/// Type alias for the Keyword enum, used by keyword helper methods.
38use crate::keyword::keyword_instance::Keyword as Kw;
39
40// ── Keyword marker constants ──────────────────────────────────────────
41// These are synthetic keywords injected at runtime to track card state.
42// Using constants avoids magic strings scattered across the codebase.
43
44/// Prefix for the Plotted marker. Full keyword is `"Plotted:{turn}"`.
45/// The turn number prevents casting on the same turn the card was plotted.
46pub const KEYWORD_PLOTTED_PREFIX: &str = "Plotted:";
47
48/// Marker for cards exiled via Warp's end-of-turn trigger.
49/// These cards can be cast from exile on a later turn for their normal mana cost.
50pub 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
70/// Build the full `"Plotted:{turn}"` keyword string.
71fn 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
86/// Extract the turn number from a `"Plotted:{turn}"` keyword, if present.
87pub 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/// Stores alternate-face characteristics for double-faced cards (DFCs).
93/// The `transform()` method swaps `Card` fields with these values.
94/// Mirrors Java's `CardState` stored as the "backside" state.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct CardOtherPart {
97    pub name: String,
98    #[serde(default)]
99    pub oracle_text: String,
100    /// True when the card's split type is `Modal` (MDFC). Only a modal back face
101    /// may be played from hand; transform/meld backs may not. Mirrors
102    /// `Card.isModal()` (`getRules().getSplitType() == CardSplitType.Modal`).
103    /// Invariant across `transform()`, so it is not swapped there.
104    #[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/// When a `SP$ GainControl` steals a permanent, the revert trigger is stored
135/// here. Fires during the appropriate phase or event handler, at which point
136/// the card's `original_controller_eot` is restored.
137///
138/// Mirrors the subset of Java `ControlGainEffect.LoseControl$` variants that
139/// schedule a `GameCommand`. Java also has variants we intentionally skip
140/// here (`StaticCommandCheck` driven by an SVar comparator, `UntilSourceUnattached`,
141/// `UntilTheEndOfYourNextTurn`) — they require either a scheduler that scans
142/// every tick or a turn-owner counter that the engine doesn't maintain yet.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum_macros::EnumString)]
144#[strum(ascii_case_insensitive)]
145pub enum LoseControlCondition {
146    /// Revert at the end of the current turn (default EOT branch).
147    #[strum(serialize = "EOT", serialize = "UntilEOT", serialize = "EndOfTurn")]
148    EndOfTurn,
149    /// Revert the next time this card untaps.
150    #[strum(serialize = "Untap", serialize = "UntilUntap", serialize = "NextUntap")]
151    NextUntap,
152    /// Revert at end of combat (Threaten-style steal-and-swing).
153    EndOfCombat,
154    /// Revert when the card leaves the battlefield.
155    LeavesPlay,
156}
157
158/// Saved pre-animate state for AnimateEffect, restored at cleanup.
159#[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    /// Snapshot of intrinsic keywords before animate added any. Restored
166    /// when the card leaves the battlefield (CR 400.7) so granted keywords
167    /// (e.g. Animate `Keywords$ Haste`) do not persist into the new object.
168    #[serde(default)]
169    pub original_keywords: Option<crate::keyword::keyword_collection::KeywordCollection>,
170}
171
172/// Saved pre-clone copiable characteristics.
173#[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    /// Intrinsic ability count *before* the clone overwrote it. The static
193    /// layer truncates `activated_abilities` to `base_ability_count` each
194    /// pass, so reverting `activated_abilities` without also restoring this
195    /// would let the layer trim the recovered abilities right back to the
196    /// clone's count.
197    #[serde(default)]
198    pub original_base_ability_count: usize,
199    /// Intrinsic trigger count *before* the clone, for the same reason.
200    #[serde(default)]
201    pub original_base_trigger_count: usize,
202}
203
204/// A card instance in a game. This is the mutable game-state representation,
205/// as opposed to CardRules which is the immutable definition.
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct Card {
208    pub id: CardId,
209    /// The card's active face name (front face for single/split cards, active face for DFC).
210    /// On the battlefield, this is the name that's displayed.
211    pub card_name: String,
212    /// The full combined name for split/room cards (e.g. "Walk-In Closet // Forgotten Cellar").
213    /// For non-split cards, this equals `card_name`. Used for hand/graveyard display and
214    /// database lookups.
215    pub full_name: String,
216    #[serde(default)]
217    pub oracle_text: String,
218
219    // Ownership and control
220    pub owner: PlayerId,
221    pub controller: PlayerId,
222
223    // Current zone
224    pub zone: ZoneType,
225
226    // Type line (can be modified by effects)
227    pub type_line: CardTypeLine,
228
229    // Mana cost (can be modified)
230    pub mana_cost: ManaCost,
231
232    // Color (can be modified)
233    pub color: ColorSet,
234
235    /// Immutable color identity from the card's rules (CR 903.4): mana cost
236    /// colors plus any mana symbols found in the oracle text (outside reminder
237    /// text). Used for commander color-identity checks and Combo ColorIdentity
238    /// mana productions. Mirrors Java `CardRules.getColorIdentity()`.
239    #[serde(default = "colorless_color_set")]
240    pub color_identity: ColorSet,
241
242    // Power/Toughness (base values, can be modified)
243    pub base_power: Option<i32>,
244    pub base_toughness: Option<i32>,
245    /// Printed starting loyalty for planeswalkers.
246    pub initial_loyalty: Option<String>,
247    /// Temporary P/T modifications from spells/abilities resolving this turn
248    /// (e.g. Giant Growth).  Reset when leaving the battlefield.
249    pub power_modifier: i32,
250    pub toughness_modifier: i32,
251    /// Perpetual P/T modifications — persist across zone changes (never reset).
252    /// Applied by `PumpAll` / `Pump` effects with `Duration$ Perpetual`.
253    pub perpetual_power_modifier: i32,
254    pub perpetual_toughness_modifier: i32,
255    /// Java-parity storage of all perpetual effect records applied to this card.
256    #[serde(default)]
257    pub perpetual: Vec<PerpetualRecord>,
258    /// Layer 7b override: set by `SetPower$` / `SetToughness$` continuous effects.
259    /// `None` means use `base_power` / `base_toughness` as normal.
260    /// Reset to `None` each time [`layer::apply_continuous_effects`] runs.
261    pub static_set_power: Option<i32>,
262    pub static_set_toughness: Option<i32>,
263    /// Layer 7c bonus: accumulated from `AddPower$` / `AddToughness$` anthems.
264    /// Reset to 0 each time [`layer::apply_continuous_effects`] runs.
265    pub static_power_modifier: i32,
266    pub static_toughness_modifier: i32,
267
268    // Combat/state
269    pub tapped: bool,
270    /// Mana atoms produced the last time this land was tapped for mana.
271    /// Used for mana rollback — when untapping, remove exactly this mana from pool.
272    /// Covers base production + aura triggers + static doublers + any other source.
273    #[serde(skip)]
274    pub last_mana_produced: Option<Vec<u16>>,
275    pub flipped: bool,
276    pub face_down: bool,
277    /// True if this card has Morph or Megamorph and can be cast face-down for {3}.
278    pub has_morph: bool,
279    /// True if this card was discarded (CR 400.7k, for TrackDiscarded$ effects).
280    pub discarded: bool,
281    /// True if this card was unearthed (should be exiled at EOT or if leaving battlefield).
282    pub unearthed: bool,
283    /// Class enchantment level (1 = base, 2+ = leveled up).
284    pub class_level: i32,
285    /// Soulbond: paired creature (if any).
286    pub paired_with: Option<CardId>,
287    /// True if this card was manifested (face-down as 2/2 creature).
288    pub manifested: bool,
289    /// True if this card was cloaked (face-down with ward {2}).
290    pub cloaked: bool,
291    /// True if this card was foretold (exiled face-down via Foretell).
292    pub foretold: bool,
293    /// Other card(s) melded/merged with this one. When this card changes zones,
294    /// all melded parts move together (CR 712.4).
295    pub melded_with: Vec<CardId>,
296    /// True if foretold cost was set by an effect (not the card's own Foretell ability).
297    pub foretold_cost_by_effect: bool,
298    /// True if this card is currently bestowed (attached as an Aura via Bestow).
299    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    /// Zone the card was cast from (mirrors Java `Card.castFrom`). `Some` only
306    /// while the card represents a spell that was actually cast — set during
307    /// cast resolution, cleared on every zone change so the next "object" the
308    /// card becomes (CR 400.7) starts with no cast history. Used by
309    /// `wasCast`/`wasCastByYou` valid filters (e.g. Sunderflock's ETB).
310    pub cast_from: Option<ZoneType>,
311
312    // Counters
313    pub counters: BTreeMap<CounterType, i32>,
314
315    // Keywords intrinsic to this card (from its card definition).
316    // Now stored as a `KeywordCollection` for structured typed lookups.
317    pub keywords: crate::keyword::keyword_collection::KeywordCollection,
318    /// Keywords granted by continuous static effects (Layer 6).
319    /// Reset and recomputed each time [`layer::apply_continuous_effects`] runs.
320    pub granted_keywords: crate::keyword::keyword_collection::KeywordCollection,
321    /// SVars supplied by granted text (e.g. AddTrigger$/AddAbility$).
322    /// Reset and recomputed each time [`layer::apply_continuous_effects`] runs.
323    #[serde(default)]
324    pub granted_svars: BTreeMap<String, String>,
325    /// Type tokens added by continuous static effects (Layer 4, `AddType$`).
326    /// Reset and recomputed each time [`layer::apply_continuous_effects`] runs.
327    /// The listed strings may be supertypes, core card types, or subtypes;
328    /// keeping a separate list lets us revert on reset without losing the
329    /// card's intrinsic type line.
330    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    /// Keywords granted temporarily by pump effects (`KW$` parameter) until end of turn.
340    /// Cleared during step_cleanup alongside power_modifier / toughness_modifier.
341    pub pump_keywords: crate::keyword::keyword_collection::KeywordCollection,
342    /// Number of triggers added temporarily by `DB$ Animate | Triggers$` effects.
343    /// At cleanup, this many triggers are popped from the end of the `triggers` vec.
344    pub pump_trigger_count: usize,
345
346    // Abilities (raw strings from card definition)
347    pub abilities: Vec<String>,
348    /// Prebound SP$ ability metadata used by action-space filters.
349    #[serde(default)]
350    pub action_spell_specs: Vec<CardActionSpellSpec>,
351    /// Prebound first SP$ Cost used by action-space non-mana cost checks.
352    #[serde(default)]
353    pub action_spell_cost: Option<Cost>,
354    /// Prebound AIPhyrexianPayment$ policy from printed ability text.
355    #[serde(default)]
356    pub ai_phyrexian_payment: Option<String>,
357    /// Prebound minimum Spree mode cost from Choices$ -> SVar ModeCost$.
358    #[serde(default)]
359    pub spree_min_mode_cost: Option<i32>,
360
361    // Parsed activated abilities (from AB$ lines in abilities)
362    pub activated_abilities: Vec<ActivatedAbility>,
363    /// Number of base activated abilities (before continuous effects add more via AddAbility$).
364    /// Used by `apply_continuous_effects` to truncate granted abilities on reset.
365    pub base_ability_count: usize,
366    /// Number of base triggers (before continuous effects add more via AddTrigger$).
367    /// Used by `apply_continuous_effects` to truncate granted triggers on reset.
368    pub base_trigger_count: usize,
369    /// Applied card-trait mutation layers keyed by (timestamp, static_id).
370    /// Mirrors Java `changedCardTraits` table.
371    pub changed_card_traits:
372        std::collections::BTreeMap<(i64, i64), card_trait_changes::CardTraitChanges>,
373    /// Text-layer trait changes keyed by (timestamp, static_id).
374    /// Mirrors Java `changedCardTraitsByText` table.
375    pub changed_card_traits_by_text:
376        std::collections::BTreeMap<(i64, i64), card_trait_changes::CardTraitChanges>,
377
378    /// Parsed static abilities (from S$ lines in abilities).
379    /// Mirrors Java Forge `Card.getStaticAbilities()`.
380    pub static_abilities: Vec<StaticAbility>,
381
382    // Combat tracking
383    pub has_deathtouch_damage: bool,
384    /// Set by `Mode$ CantAttack` static effects. Reset each time
385    /// [`layer::apply_continuous_effects`] runs.
386    pub cant_attack_static: bool,
387    /// Set by `Mode$ CantBlock` static effects. Reset each time
388    /// [`layer::apply_continuous_effects`] runs.
389    pub cant_block_static: bool,
390
391    // Turn tracking
392    #[serde(default)]
393    pub turn_in_zone: u32,
394    pub entered_battlefield_this_turn: bool,
395    pub attacked_this_turn: bool,
396    /// Snapshot of whether this permanent was tapped at the start of its
397    /// controller's current turn (before untap step).
398    pub started_turn_tapped: bool,
399
400    // Triggers — mirrors Java Card.getTriggers()
401    pub triggers: Vec<Trigger>,
402    // SVars — mirrors Java Card.getSVars()
403    pub svars: BTreeMap<String, String>,
404    #[serde(skip, default)]
405    pub parsed_svar_cache: ParsedSVarCache,
406
407    // Commander tracking
408    /// True if this card is designated as a commander.
409    pub is_commander: bool,
410    /// True if this commander entered graveyard or exile since the last SBA check
411    /// and may still be moved to the command zone.
412    pub move_to_command_zone: bool,
413    /// How many times this commander has been cast from the command zone (for tax).
414    pub commander_cast_count: u32,
415
416    /// True if this permanent is a token or a copy-token (ceases to exist on zone change).
417    pub is_token: bool,
418
419    /// Set when the card is cast from graveyard via Flashback. Used by the
420    /// flashback replacement effect to exile the card when it leaves the stack.
421    pub cast_with_flashback: bool,
422    /// Set when the card is cast from graveyard via Harmonize. Used by the
423    /// Harmonize replacement effect to exile the card when it leaves the stack.
424    pub cast_with_harmonize: bool,
425
426    // Replacement effects — parsed from R$ lines in card abilities.
427    // Mirrors Java `Card.getReplacementEffects()`.
428    pub replacement_effects: Vec<ReplacementEffect>,
429
430    // Attachment tracking (Auras / Equipment).
431    // Mirrors Java `Card.getAttachedTo()` / `Card.getAttachedCards()`.
432    /// The permanent this card is currently attached to (for Auras/Equipment).
433    pub attached_to: Option<CardId>,
434    pub attached_to_player: Option<PlayerId>,
435    /// Whether this equipment was attached/moved this turn (AI memory to prevent ping-ponging).
436    /// Cleared at start of each turn. Mirrors Java `AiCardMemory.MemorySet.ATTACHED_THIS_TURN`.
437    pub attached_this_turn: bool,
438    /// Cards currently attached to this permanent (inverse of `attached_to`).
439    pub attachments: Vec<CardId>,
440
441    // Memory for "Remember" and "Imprint" parameters
442    /// Cards remembered by this card (for RememberCountered, etc.)
443    pub remembered_cards: Vec<CardId>,
444    /// Players remembered by this card (for Player.IsRemembered checks).
445    pub remembered_players: Vec<PlayerId>,
446    /// Cards imprinted on this card (for Imprint mechanic, e.g. Chrome Mox).
447    pub imprinted_cards: Vec<CardId>,
448    /// Cards associated via gain-control effects.
449    pub gain_control_targets: Vec<CardId>,
450    /// Cards linked by "until leaves battlefield" tracking.
451    pub until_leaves_battlefield: Vec<CardId>,
452    /// Cards exiled by this card/effect.
453    pub exiled_cards: Vec<CardId>,
454    /// Cards exiled specifically to pay this card's current activation/cast cost.
455    /// This is reset at the start of each cost payment attempt.
456    pub paid_cost_exiled_cards: Vec<CardId>,
457    /// Cards haunting this card.
458    pub haunted_by: Vec<CardId>,
459    /// Card currently haunted by this card.
460    pub haunting: Option<CardId>,
461    /// Per-player chosen card map.
462    pub chosen_map: HashMap<PlayerId, Vec<CardId>>,
463    /// CMC values remembered by this card
464    pub remembered_cmc: Vec<i32>,
465    #[serde(default)]
466    pub stored_rolls: Vec<i32>,
467    /// Source card that created this effect card (for Card.EffectSource checks).
468    pub effect_source: Option<CardId>,
469    #[serde(default)]
470    pub clone_origin: Option<CardId>,
471    #[serde(default)]
472    pub copied_permanent: Option<CardId>,
473    /// The spell ability used to cast this card instance onto the stack.
474    /// Mirrors Java `Card.getCastSA()`. Populated when the card hits the stack,
475    /// cleared when it leaves the battlefield.
476    #[serde(skip, default)]
477    pub cast_sa: Option<Box<SpellAbility>>,
478    /// For `SP$ Charm`: last turn each mode (keyed by its SVar name) was chosen
479    /// on this card instance. Feeds `ChoiceRestriction$` filtering.
480    /// Mirrors the per-card mode history Java keeps on `Card`.
481    #[serde(default)]
482    pub chosen_charm_modes: HashMap<String, i32>,
483    /// LKI (last-known-information) snapshots of cards remembered by this
484    /// card via `RememberLKI$`. Each entry is a frozen copy taken at remember
485    /// time via `CardCopyService::get_lki_copy`. Callers that care about
486    /// "what was this creature when it died" query this list instead of
487    /// `remembered_cards` (which stores live IDs and drifts).
488    #[serde(skip, default)]
489    pub remembered_lki_cards: Vec<Card>,
490    /// When set, the card's `original_controller_eot` must be restored on the
491    /// trigger described here. Mirrors the Java `ControlGainEffect` set of
492    /// `LoseControl$` variants that register distinct GameCommands.
493    #[serde(default)]
494    pub lose_control_condition: Option<LoseControlCondition>,
495    /// True if this temporary effect expires at end of turn cleanup.
496    pub temp_effect_until_eot: bool,
497    /// Host card this temporary effect is linked to; when host leaves the
498    /// battlefield, this effect expires.
499    pub temp_effect_host: Option<CardId>,
500    /// Forget remembered cards when they move from this origin zone.
501    pub forget_on_moved_origin: Option<ZoneType>,
502    /// Exile this effect when remembered cards become empty after forget logic.
503    pub exile_when_no_remembered: bool,
504    /// When this card is in exile, the card that caused it to be exiled here.
505    /// Used for `Duration$ UntilHostLeavesPlay` effects (e.g. Deputy of Detention):
506    /// when `exiled_by` leaves the battlefield, this card returns to its owner's battlefield.
507    pub exiled_by: Option<CardId>,
508
509    /// Original controller to restore at end of turn (for `LoseControl$ EOT`).
510    pub original_controller_eot: Option<PlayerId>,
511
512    // Double-faced card (DFC) state
513    /// True if this card is currently showing its back face.
514    pub is_transformed: bool,
515    /// Back-face characteristics for DFC cards. `None` for single-faced cards.
516    pub other_part: Option<CardOtherPart>,
517
518    /// Optional set code (e.g., "M21") for specific printings.
519    pub set_code: Option<String>,
520
521    /// Optional collector number within a set (e.g., "1", "42").
522    /// For tokens, this is the token's collector number in the token set
523    /// (e.g., collector "1" in set "THOU" for Adorned Pouncer token).
524    pub card_number: Option<String>,
525
526    #[serde(default)]
527    pub paper_foil: bool,
528
529    // Phase-out state (issue #22, Phases effect).
530    pub phased_out: bool,
531
532    // Regeneration shields (issue #22, Regenerate effect).
533    // Decremented instead of destroying; resets at end of turn.
534    pub regeneration_shields: i32,
535
536    /// Whether this permanent was kicked when cast.
537    /// Mirrors Java `Card.isKicked()`. Stored on the card so triggers
538    /// with `ValidCard$ Card.Self+kicked` can check it after resolution.
539    pub kicked: bool,
540    /// Whether this permanent has become monstrous.
541    /// Mirrors Java `Card.isMonstrous()`. Resets when the permanent changes zones.
542    pub monstrous: bool,
543
544    /// Colors chosen by ChooseColorEffect (stored for later reference by other effects).
545    pub chosen_colors: Vec<String>,
546    /// Cards chosen by ChooseCardEffect (stored for later reference by other effects).
547    pub chosen_cards: Vec<CardId>,
548
549    /// Saved state for AnimateEffect — restored during step_cleanup.
550    pub animate_state: Option<AnimateState>,
551    /// Saved state for temporary Clone effects — restored during step_cleanup.
552    pub clone_state: Option<CloneState>,
553
554    // ── Issue #53: High-priority effect fields ──────────────────────────
555    /// Type chosen by ChooseType effect (e.g. "Goblin", "Artifact").
556    pub chosen_type: Option<String>,
557    /// Secondary chosen type used by a subset of cards (e.g. Illusionary Terrain).
558    pub chosen_type2: Option<String>,
559    /// Noted types tracked by effects that accumulate type names.
560    pub noted_types: Vec<String>,
561    /// Card names chosen by NameCard effect.
562    pub named_cards: Vec<String>,
563    /// Number chosen by ChooseNumber effect.
564    pub chosen_number: Option<i32>,
565    pub chosen_number_controller: Option<PlayerId>,
566    pub chosen_number_revealed: bool,
567    pub chosen_mode: Option<String>,
568    /// Player chosen by ChoosePlayer effect.
569    pub chosen_player: Option<PlayerId>,
570    /// Controller who made the chosen-player choice.
571    pub chosen_player_controller: Option<PlayerId>,
572    /// Controller who made the chosen-type choice.
573    pub chosen_type_controller: Option<PlayerId>,
574    /// Whether the chosen player has been revealed.
575    pub chosen_player_revealed: bool,
576    /// Whether the chosen type has been revealed.
577    pub chosen_type_revealed: bool,
578    /// Opponent chosen for PromiseGift cost.
579    pub promised_gift: Option<PlayerId>,
580    /// Attraction lights printed on the card face.
581    pub attraction_lights: Vec<u32>,
582    /// Attraction sector assignment.
583    pub sector: Option<String>,
584    /// Chosen sector before assignment effects resolve.
585    pub chosen_sector: Option<String>,
586    /// Contraption sprocket assignment.
587    pub sprocket: i32,
588    /// Chosen even/odd marker.
589    pub chosen_even_odd: Option<String>,
590    /// True if detained — can't attack, block, or activate abilities. Clears at controller's next turn.
591    pub detained: bool,
592    /// Set during combat to the player this creature is attacking; None if not attacking.
593    pub attacking_player: Option<PlayerId>,
594    /// Player who goaded this creature. Goaded creature must attack but can't attack goader.
595    pub goaded_by: Option<PlayerId>,
596    /// Damage prevention shields (decremented when damage would be dealt). Resets at EOT.
597    pub damage_prevention: i32,
598    /// Damage assigned in current combat assignment step.
599    pub assigned_damage: i32,
600    /// True if this creature must block if able.
601    pub must_block: bool,
602    /// Spell cards encoded/ciphered onto this creature.
603    pub encoded_cards: Vec<CardId>,
604    /// Cards that dealt damage to this creature this turn (for DamagedBy trigger filters).
605    /// Mirrors Java `CardDamageHistory.getDamageReceivedThisTurn()`.
606    pub damage_sources_this_turn: Vec<CardId>,
607    /// Total damage dealt by this card this turn (for Count$TotalDamageDoneByThisTurn).
608    /// Mirrors Java `Card.getTotalDamageDoneBy()` via `DamageHistory.getDamageDoneThisTurn()`.
609    /// Reset each turn in `new_turn()`.
610    pub total_damage_done_this_turn: i32,
611    /// Last-known information: power when this card last left the battlefield.
612    /// Mirrors Java's LKI system for `TriggeredCard$CardPower`.
613    /// `None` means LKI was never captured; `Some(0)` means power was 0.
614    pub lki_power: Option<i32>,
615    /// Last-known information: toughness when this card last left the battlefield.
616    /// `None` means LKI was never captured; `Some(0)` means toughness was 0.
617    pub lki_toughness: Option<i32>,
618    /// Last-known information: counters when this card last left the battlefield.
619    /// Used by `TriggeredCard$CardCounters.TYPE` (e.g. Servant of the Scale death trigger).
620    pub lki_counters: Option<std::collections::BTreeMap<CounterType, i32>>,
621    /// Damage history tracking (attacks, blocks, damage dealt).
622    /// Mirrors Java `CardDamageHistory`.
623    #[serde(skip)]
624    pub damage_history: damage_history::DamageHistory,
625    /// Specific cards this creature must block (set by effects like Lure variants).
626    pub must_block_cards: Vec<CardId>,
627    /// +1/+1 counters to add on ETB (from mana that adds counters, e.g. Guildmages' Forum).
628    pub etb_counters_p1p1: i32,
629    /// Bitmask of colors of mana spent to cast this spell (for Sunburst/Converge).
630    /// Uses ManaAtom bit flags (W=1, U=2, B=4, R=8, G=16).
631    pub colors_spent_to_cast: u16,
632    /// Exact mana atoms spent to cast this spell, in payment order.
633    /// Mirrors Java's castSA.getPayingMana() use sites such as Adamant.
634    pub paying_mana_to_cast: Vec<u16>,
635    /// Pre-selected charm/mode indices (for Spree — modes chosen before payment).
636    /// If `Some`, charm_effect should use these instead of asking the player again.
637    pub chosen_modes: Option<Vec<usize>>,
638    /// Number of extra targets paid for via Strive (0 = no extra targets).
639    pub strive_extra_targets: u32,
640    /// Tracks if this card became a target this turn.
641    pub became_target_this_turn: bool,
642    /// Temporary controllers layered on this card.
643    pub temp_controllers: Vec<PlayerId>,
644    /// Players that may look at this card.
645    pub may_look_at: Vec<PlayerId>,
646    /// Players that may play this card.
647    pub may_play: Vec<PlayerId>,
648    /// Additional blockers this creature can declare.
649    pub can_block_additional: i32,
650    /// Whether this creature can block any number of creatures.
651    pub can_block_any: bool,
652    /// Keywords this card is prevented from having.
653    pub cant_have_keywords: HashSet<String>,
654    /// Intensity marker value.
655    pub intensity: i32,
656    /// Card was surveilled this turn.
657    pub surveilled: bool,
658    /// Card was milled this turn.
659    pub milled: bool,
660    /// Attraction visited this turn.
661    pub visited_this_turn: bool,
662    /// Number of times this permanent has crewed this turn.
663    pub times_crewed_this_turn: u32,
664    /// Whether this permanent is currently crewed.
665    pub is_crewed: bool,
666    /// Whether this card should ignore legend rule checks.
667    pub ignore_legend_rule_flag: bool,
668    /// Ability activation counts this turn.
669    pub ability_activated_this_turn: u32,
670    /// Ability resolution counts this turn.
671    pub ability_resolved_this_turn: u32,
672    /// Java parity: per-ability activation tracking this turn.
673    #[serde(skip)]
674    pub number_turn_activations: ActivationTable,
675    /// Java parity: per-ability activation tracking this game.
676    #[serde(skip)]
677    pub number_game_activations: ActivationTable,
678    /// Java parity: per-ability resolution tracking this turn.
679    #[serde(skip)]
680    pub number_ability_resolved: ActivationTable,
681    /// Planeswalker activation count this turn.
682    pub planeswalker_abilities_activated: u32,
683    /// Whether a static effect's increased planeswalker activation limit was used this turn.
684    pub planeswalker_activation_limit_used: bool,
685    /// Chosen mode count tracking turn marker.
686    pub chosen_modes_turn: Option<u32>,
687    /// Set when this creature enlisted another creature in the current combat.
688    pub enlisted_this_combat: bool,
689    /// Per-ability activation count this game (for PowerUp once-per-game restriction).
690    pub activations_this_game: std::collections::BTreeMap<usize, u32>,
691    /// True once Renown has triggered (creature dealt combat damage to a player).
692    /// Mirrors Java `Card.isRenowned()`.
693    pub is_renowned: bool,
694    /// Monotonically increasing timestamp set each time the card enters a zone.
695    /// Used to order same-player triggers by zone entry order, matching
696    /// Java's `Zone.cardList` insertion order used by `forEachCardInGame`.
697    pub zone_timestamp: u64,
698
699    /// Baseline snapshots used to recompute live lists when trait-change layers
700    /// are removed/cleared.
701    #[serde(skip)]
702    trait_base_activated_abilities: Option<Vec<ActivatedAbility>>,
703    #[serde(skip)]
704    trait_base_triggers: Option<Vec<Trigger>>,
705    #[serde(skip)]
706    trait_base_replacement_effects: Option<Vec<ReplacementEffect>>,
707    #[serde(skip)]
708    trait_base_static_abilities: Option<Vec<StaticAbility>>,
709    #[serde(skip)]
710    trait_base_keywords: Option<crate::keyword::keyword_collection::KeywordCollection>,
711}
712
713/// Transitional alias for downstream code still importing `CardInstance`.
714pub type CardInstance = Card;
715
716impl Card {
717    pub fn new(
718        id: CardId,
719        card_name: String,
720        owner: PlayerId,
721        type_line: CardTypeLine,
722        mana_cost: ManaCost,
723        color: ColorSet,
724        base_power: Option<i32>,
725        base_toughness: Option<i32>,
726        keywords: Vec<String>,
727        abilities: Vec<String>,
728    ) -> Self {
729        // Parse activated abilities from raw ability strings.
730        let activated_abilities: Vec<ActivatedAbility> = abilities
731            .iter()
732            .enumerate()
733            .filter_map(|(i, raw)| {
734                parse_or_warn(parse_activated_ability(raw, i), "ActivatedAbility", raw)
735            })
736            .collect();
737
738        // Parse replacement effects from R$ lines in card abilities.
739        // Mirrors Java Card constructor calling ReplacementHandler registration.
740        let replacement_effects: Vec<ReplacementEffect> = abilities
741            .iter()
742            .filter_map(|raw| {
743                parse_or_warn(parse_replacement_effect(raw), "ReplacementEffect", raw)
744            })
745            .collect();
746
747        // Parse static abilities from S$ lines.
748        // Mirrors Java Forge Card constructor calling StaticAbility.create().
749        let static_abilities: Vec<StaticAbility> = abilities
750            .iter()
751            .filter_map(|raw| parse_or_warn(parse_static_ability(raw), "StaticAbility", raw))
752            .collect();
753
754        let full_name = card_name.clone();
755        let color_identity = color;
756        let mut card = Card {
757            id,
758            card_name,
759            full_name,
760            oracle_text: String::new(),
761            owner,
762            controller: owner,
763            zone: ZoneType::None,
764            type_line,
765            mana_cost,
766            color,
767            color_identity,
768            base_power,
769            base_toughness,
770            initial_loyalty: None,
771            power_modifier: 0,
772            toughness_modifier: 0,
773            perpetual_power_modifier: 0,
774            perpetual_toughness_modifier: 0,
775            perpetual: Vec::new(),
776            static_set_power: None,
777            static_set_toughness: None,
778            static_power_modifier: 0,
779            static_toughness_modifier: 0,
780            tapped: false,
781            last_mana_produced: None,
782            flipped: false,
783            face_down: false,
784            has_morph: false,
785            discarded: false,
786            unearthed: false,
787            class_level: 1,
788            paired_with: None,
789            manifested: false,
790            cloaked: false,
791            foretold: false,
792            foretold_cost_by_effect: false,
793            melded_with: Vec::new(),
794            is_bestowed: false,
795            summoning_sick: true,
796            came_under_control_since_last_upkeep: false,
797            exerted: false,
798            damage: 0,
799            cast_from: None,
800            counters: BTreeMap::new(),
801            keywords: crate::keyword::keyword_collection::KeywordCollection::from_strings(
802                &keywords,
803            ),
804            granted_keywords: crate::keyword::keyword_collection::KeywordCollection::new(),
805            granted_svars: BTreeMap::new(),
806            static_added_subtypes: Vec::new(),
807            static_type_line_base: None,
808            changed_type_line_base: None,
809            changed_base_power: None,
810            changed_base_toughness: None,
811            pump_keywords: crate::keyword::keyword_collection::KeywordCollection::new(),
812            pump_trigger_count: 0,
813            abilities,
814            action_spell_specs: Vec::new(),
815            action_spell_cost: None,
816            ai_phyrexian_payment: None,
817            spree_min_mode_cost: None,
818            activated_abilities,
819            base_ability_count: 0,
820            base_trigger_count: 0,
821            changed_card_traits: std::collections::BTreeMap::new(),
822            changed_card_traits_by_text: std::collections::BTreeMap::new(),
823            static_abilities,
824            has_deathtouch_damage: false,
825            cant_attack_static: false,
826            cant_block_static: false,
827            turn_in_zone: 0,
828            entered_battlefield_this_turn: false,
829            attacked_this_turn: false,
830            started_turn_tapped: false,
831            triggers: Vec::new(),
832            svars: BTreeMap::new(),
833            parsed_svar_cache: ParsedSVarCache::default(),
834            is_commander: false,
835            move_to_command_zone: false,
836            commander_cast_count: 0,
837            is_token: false,
838            cast_with_flashback: false,
839            cast_with_harmonize: false,
840            replacement_effects,
841            attached_to: None,
842            attached_to_player: None,
843            attached_this_turn: false,
844            attachments: Vec::new(),
845            remembered_cards: Vec::new(),
846            remembered_players: Vec::new(),
847            imprinted_cards: Vec::new(),
848            gain_control_targets: Vec::new(),
849            until_leaves_battlefield: Vec::new(),
850            exiled_cards: Vec::new(),
851            paid_cost_exiled_cards: Vec::new(),
852            haunted_by: Vec::new(),
853            haunting: None,
854            chosen_map: HashMap::new(),
855            remembered_cmc: Vec::new(),
856            stored_rolls: Vec::new(),
857            effect_source: None,
858            clone_origin: None,
859            copied_permanent: None,
860            cast_sa: None,
861            chosen_charm_modes: HashMap::new(),
862            remembered_lki_cards: Vec::new(),
863            lose_control_condition: None,
864            temp_effect_until_eot: false,
865            temp_effect_host: None,
866            forget_on_moved_origin: None,
867            exile_when_no_remembered: false,
868            exiled_by: None,
869            original_controller_eot: None,
870            is_transformed: false,
871            other_part: None,
872            set_code: None,
873            card_number: None,
874            paper_foil: false,
875            phased_out: false,
876            regeneration_shields: 0,
877            kicked: false,
878            monstrous: false,
879            chosen_colors: Vec::new(),
880            chosen_cards: Vec::new(),
881            animate_state: None,
882            clone_state: None,
883            chosen_type: None,
884            chosen_type2: None,
885            noted_types: Vec::new(),
886            named_cards: Vec::new(),
887            chosen_number: None,
888            chosen_number_controller: None,
889            chosen_number_revealed: false,
890            chosen_mode: None,
891            chosen_player: None,
892            chosen_player_controller: None,
893            chosen_type_controller: None,
894            chosen_player_revealed: false,
895            chosen_type_revealed: false,
896            promised_gift: None,
897            attraction_lights: Vec::new(),
898            sector: None,
899            chosen_sector: None,
900            sprocket: 0,
901            chosen_even_odd: None,
902            detained: false,
903            attacking_player: None,
904            goaded_by: None,
905            damage_prevention: 0,
906            assigned_damage: 0,
907            must_block: false,
908            encoded_cards: Vec::new(),
909            damage_sources_this_turn: Vec::new(),
910            total_damage_done_this_turn: 0,
911            lki_power: None,
912            lki_toughness: None,
913            lki_counters: None,
914            damage_history: damage_history::DamageHistory::default(),
915            must_block_cards: Vec::new(),
916            etb_counters_p1p1: 0,
917            colors_spent_to_cast: 0,
918            paying_mana_to_cast: Vec::new(),
919            chosen_modes: None,
920            strive_extra_targets: 0,
921            became_target_this_turn: false,
922            temp_controllers: Vec::new(),
923            may_look_at: Vec::new(),
924            may_play: Vec::new(),
925            can_block_additional: 0,
926            can_block_any: false,
927            cant_have_keywords: HashSet::new(),
928            intensity: 0,
929            surveilled: false,
930            milled: false,
931            visited_this_turn: false,
932            times_crewed_this_turn: 0,
933            is_crewed: false,
934            ignore_legend_rule_flag: false,
935            ability_activated_this_turn: 0,
936            ability_resolved_this_turn: 0,
937            number_turn_activations: ActivationTable::default(),
938            number_game_activations: ActivationTable::default(),
939            number_ability_resolved: ActivationTable::default(),
940            planeswalker_abilities_activated: 0,
941            planeswalker_activation_limit_used: false,
942            chosen_modes_turn: None,
943            enlisted_this_combat: false,
944            activations_this_game: std::collections::BTreeMap::new(),
945            is_renowned: false,
946            zone_timestamp: 0,
947            trait_base_activated_abilities: None,
948            trait_base_triggers: None,
949            trait_base_replacement_effects: None,
950            trait_base_static_abilities: None,
951            trait_base_keywords: None,
952        };
953
954        // Generate intrinsic abilities from card properties (mirrors Java CardFactoryUtil)
955        card.generate_basic_land_mana_abilities();
956        card.generate_keyword_abilities();
957        card.generate_keyword_triggers();
958        crate::card::card_state::update_types(&mut card);
959        crate::card::card_state::update_keywords_cache(&mut card);
960        crate::card::card_state::calculate_perpetual_adjusted_mana_cost(&mut card);
961        card.refresh_action_specs();
962        // Record base ability count so continuous effects can truncate granted abilities.
963        card.base_ability_count = card.activated_abilities.len();
964        card.base_trigger_count = card.triggers.len();
965        card
966    }
967
968    pub fn clone_for_parity_snapshot(&self) -> Self {
969        let mut out = self.clone();
970        out.abilities.clear();
971        out.activated_abilities.clear();
972        out.triggers.clear();
973        for static_ability in &mut out.static_abilities {
974            *static_ability.base = crate::card_trait_base::CardTraitBase::default();
975        }
976        out.replacement_effects.clear();
977        out.cast_sa = None;
978        out.trait_base_activated_abilities = None;
979        out.trait_base_triggers = None;
980        out.trait_base_replacement_effects = None;
981        out.trait_base_static_abilities = None;
982        out.trait_base_keywords = None;
983        out
984    }
985
986    /// Construct a `Card` from a `CardRules` definition.
987    /// This is the single entry point for creating game-ready cards from the
988    /// card database. Mirrors Java's `CardFactory.readCard()` + `CardFactoryUtil`.
989    ///
990    /// Handles:
991    /// - Base stats (name, mana cost, type line, color, P/T, keywords, abilities)
992    /// - Trigger parsing (T: lines) including SpellCastOrCopy → SpellCopied duplication
993    /// - Static ability parsing (S: lines) with alternative cost keyword conversion
994    /// - Replacement effect parsing (R: lines)
995    /// - SVars
996    /// - Double-faced card back face setup
997    /// - Intrinsic mana abilities (basic land subtypes)
998    /// - Keyword-generated abilities and triggers (Cycling, Prowess, Bushido)
999    pub fn from_rules(rules: &CardRules, owner: PlayerId) -> Self {
1000        card_factory::build_from_rules(rules, owner)
1001    }
1002
1003    /// Effective power, accounting for all layer effects and counters.
1004    ///
1005    /// Calculation order (CR 613):
1006    /// - Layer 7b: `static_set_power` overrides `base_power` if set.
1007    /// - Layer 7c: `static_power_modifier` (anthem bonuses) is added.
1008    /// - Temporary: `power_modifier` (from spells like Giant Growth) is added.
1009    /// - Layer 7d: +1/+1 and -1/-1 counters are factored in.
1010    pub fn power(&self) -> i32 {
1011        let base = self
1012            .static_set_power
1013            .unwrap_or(self.base_power.unwrap_or(0));
1014        base + self.static_power_modifier
1015            + self.power_modifier
1016            + self.perpetual_power_modifier
1017            + self.counter_count(&CounterType::P1P1)
1018            - self.counter_count(&CounterType::M1M1)
1019    }
1020
1021    /// Effective toughness, accounting for all layer effects and counters.
1022    pub fn toughness(&self) -> i32 {
1023        let base = self
1024            .static_set_toughness
1025            .unwrap_or(self.base_toughness.unwrap_or(0));
1026        base + self.static_toughness_modifier
1027            + self.toughness_modifier
1028            + self.perpetual_toughness_modifier
1029            + self.counter_count(&CounterType::P1P1)
1030            - self.counter_count(&CounterType::M1M1)
1031    }
1032
1033    pub fn lethal_damage(&self) -> bool {
1034        self.damage >= self.toughness()
1035    }
1036
1037    pub fn can_be_dealt_damage(&self) -> bool {
1038        self.zone == ZoneType::Battlefield
1039            && (self.is_creature()
1040                || self.type_line.is_planeswalker()
1041                || self.type_line.core_types.contains(&CoreType::Battle))
1042    }
1043
1044    pub fn is_creature(&self) -> bool {
1045        !self.is_bestowed && self.type_line.is_creature()
1046    }
1047
1048    pub fn is_land(&self) -> bool {
1049        self.type_line.is_land()
1050    }
1051
1052    pub fn is_permanent(&self) -> bool {
1053        self.type_line.is_permanent()
1054    }
1055
1056    // CardState-style adapters wired on Card for Java-parity call sites.
1057    pub fn update_types(&mut self) {
1058        crate::card::card_state::update_types(self);
1059    }
1060
1061    pub fn update_types_for_view(&mut self) {
1062        crate::card::card_state::update_types_for_view(self);
1063    }
1064
1065    pub fn add_type(&mut self, ty: &str) {
1066        crate::card::card_state::add_type(self, ty);
1067        self.update_types();
1068        self.update_types_for_view();
1069    }
1070
1071    pub fn remove_type(&mut self, ty: &str) {
1072        crate::card::card_state::remove_type(self, ty);
1073        self.update_types();
1074        self.update_types_for_view();
1075    }
1076
1077    pub fn remove_card_types(&mut self) {
1078        crate::card::card_state::remove_card_types(self);
1079        self.update_types();
1080        self.update_types_for_view();
1081    }
1082
1083    pub fn set_type(&mut self, type_line: &str) {
1084        crate::card::card_state::set_type(self, type_line);
1085        self.update_types();
1086        self.update_types_for_view();
1087    }
1088
1089    pub fn set_type_line(&mut self, type_line: CardTypeLine) {
1090        self.type_line = type_line;
1091        self.update_types();
1092        self.update_types_for_view();
1093    }
1094
1095    pub fn add_color(&mut self, color: ColorSet) {
1096        crate::card::card_state::add_color(self, color);
1097    }
1098
1099    pub fn has_intrinsic_keyword(&self, keyword: &str) -> bool {
1100        crate::card::card_state::has_intrinsic_keyword(self, keyword)
1101    }
1102
1103    pub fn add_intrinsic_keyword(&mut self, keyword: &str) -> bool {
1104        let changed = crate::card::card_state::add_intrinsic_keyword(self, keyword);
1105        if changed {
1106            crate::card::card_state::update_keywords_cache(self);
1107        }
1108        changed
1109    }
1110
1111    pub fn add_intrinsic_keywords<'a>(
1112        &mut self,
1113        keywords: impl IntoIterator<Item = &'a str>,
1114    ) -> bool {
1115        let changed = crate::card::card_state::add_intrinsic_keywords(self, keywords);
1116        if changed {
1117            crate::card::card_state::update_keywords_cache(self);
1118        }
1119        changed
1120    }
1121
1122    pub fn remove_intrinsic_keyword(&mut self, keyword: &str) -> bool {
1123        let changed = crate::card::card_state::remove_intrinsic_keyword(self, keyword);
1124        if changed {
1125            crate::card::card_state::update_keywords_cache(self);
1126        }
1127        changed
1128    }
1129
1130    pub fn has_spell_ability(&self, sa: &SpellAbility) -> bool {
1131        crate::card::card_state::has_spell_ability(self, sa)
1132    }
1133
1134    pub fn add_spell_ability(&mut self, sa: &SpellAbility) -> bool {
1135        let added = crate::card::card_state::add_spell_ability(self, sa);
1136        self.refresh_action_specs();
1137        added
1138    }
1139
1140    pub fn has_trigger(&self, trigger_id: u32) -> bool {
1141        crate::card::card_state::has_trigger(self, trigger_id)
1142    }
1143
1144    pub fn add_trigger(&mut self, trig: Trigger) -> bool {
1145        crate::card::card_state::add_trigger(self, trig)
1146    }
1147
1148    pub fn clear_pump_triggers(&mut self) {
1149        let count = self.pump_trigger_count;
1150        if count == 0 {
1151            return;
1152        }
1153        let new_len = self
1154            .triggers
1155            .len()
1156            .saturating_sub(count)
1157            .max(self.base_trigger_count);
1158        self.triggers.truncate(new_len);
1159        self.pump_trigger_count = 0;
1160    }
1161
1162    pub fn copiable_triggers(&self) -> Vec<Trigger> {
1163        self.trait_base_triggers
1164            .clone()
1165            .unwrap_or_else(|| self.triggers.clone())
1166    }
1167
1168    pub fn copiable_replacement_effects(&self) -> Vec<ReplacementEffect> {
1169        self.trait_base_replacement_effects
1170            .clone()
1171            .unwrap_or_else(|| self.replacement_effects.clone())
1172    }
1173
1174    pub fn add_static_ability(&mut self, st_ab: StaticAbility) -> bool {
1175        crate::card::card_state::add_static_ability(self, st_ab)
1176    }
1177
1178    pub fn remove_static_ability(&mut self, mode: crate::staticability::StaticMode) -> bool {
1179        crate::card::card_state::remove_static_ability(self, mode)
1180    }
1181
1182    pub fn add_replacement_effect(&mut self, re: ReplacementEffect) -> bool {
1183        crate::card::card_state::add_replacement_effect(self, re)
1184    }
1185
1186    pub fn has_replacement_effect(&self) -> bool {
1187        crate::card::card_state::has_replacement_effect(self)
1188    }
1189
1190    pub fn has_s_var(&self, key: &str) -> bool {
1191        crate::card::card_state::has_s_var(self, key)
1192    }
1193
1194    pub fn get_s_var(&self, key: &str) -> Option<&str> {
1195        self.svars
1196            .get(key)
1197            .or_else(|| self.granted_svars.get(key))
1198            .map(String::as_str)
1199    }
1200
1201    pub fn parsed_s_var(&mut self, key: &str) -> Option<ParsedSVar> {
1202        let raw = self.get_s_var(key)?.to_string();
1203        Some(self.parsed_svar_cache.get_or_parse(key, &raw).clone())
1204    }
1205
1206    pub fn remove_s_var(&mut self, key: &str) {
1207        crate::card::card_state::remove_s_var(self, key);
1208        self.parsed_svar_cache.remove(key);
1209        self.refresh_action_specs_after_svar_change();
1210    }
1211
1212    pub fn set_s_var(&mut self, key: impl Into<String>, value: impl Into<String>) {
1213        let key = key.into();
1214        self.parsed_svar_cache.remove(&key);
1215        self.svars.insert(key, value.into());
1216        self.refresh_action_specs_after_svar_change();
1217    }
1218
1219    pub fn set_s_var_if_absent(&mut self, key: impl Into<String>, value: impl Into<String>) {
1220        let key = key.into();
1221        if self.svars.contains_key(&key) {
1222            return;
1223        }
1224        self.svars.insert(key, value.into());
1225        self.refresh_action_specs_after_svar_change();
1226    }
1227
1228    pub fn set_svars_map(&mut self, svars: BTreeMap<String, String>) {
1229        self.svars = svars;
1230        self.parsed_svar_cache.clear();
1231        self.refresh_action_specs();
1232    }
1233
1234    pub fn copy_from_card_state(&mut self, source: &Card) {
1235        crate::card::card_state::copy_from(source, self);
1236    }
1237
1238    pub fn copy_from(&mut self, source: &Card) {
1239        self.copy_from_card_state(source);
1240    }
1241
1242    pub fn add_abilities_from(&mut self, source: &Card) {
1243        crate::card::card_state::add_abilities_from(source, self);
1244    }
1245
1246    pub fn has_property(&self, property: &str) -> bool {
1247        crate::card::card_state::has_property(self, property)
1248    }
1249
1250    pub fn reset_original_host(&mut self) {
1251        crate::card::card_state::reset_original_host(self);
1252    }
1253
1254    pub fn update_changed_text(&mut self) {
1255        crate::card::card_state::update_changed_text(self);
1256    }
1257
1258    pub fn update_keywords_cache(&mut self) {
1259        crate::card::card_state::update_keywords_cache(self);
1260    }
1261
1262    pub fn change_text_intrinsic(&mut self) {
1263        crate::card::card_state::change_text_intrinsic(self);
1264    }
1265
1266    pub fn has_chapter(&self) -> bool {
1267        crate::card::card_state::has_chapter(self)
1268    }
1269
1270    pub fn get_final_chapter_nr(&self) -> i32 {
1271        crate::card::card_state::get_final_chapter_nr(self)
1272    }
1273
1274    /// Check whether this card has a keyword — intrinsically, granted by a
1275    /// continuous static effect (Layer 6), or temporarily from a pump effect.
1276    /// Count distinct colors of mana spent to cast this spell (for Sunburst/Converge).
1277    pub fn sunburst_count(&self) -> i32 {
1278        use forge_foundation::mana::ManaAtom;
1279        let mut count = 0;
1280        for &bit in &[
1281            ManaAtom::WHITE,
1282            ManaAtom::BLUE,
1283            ManaAtom::BLACK,
1284            ManaAtom::RED,
1285            ManaAtom::GREEN,
1286        ] {
1287            if (self.colors_spent_to_cast & bit) != 0 {
1288                count += 1;
1289            }
1290        }
1291        count
1292    }
1293
1294    pub fn has_keyword(&self, kw: &str) -> bool {
1295        crate::card::card_state::has_keyword(self, kw)
1296    }
1297
1298    /// Check for a keyword using the typed Keyword enum.
1299    /// Checks the structured `keyword_collection` first (O(1) HashMap lookup),
1300    /// then falls back to string matching on granted/pump keywords.
1301    /// Mirrors Java's `Card.hasKeyword(Keyword)`.
1302    pub fn has_keyword_enum(&self, kw: Kw) -> bool {
1303        if self
1304            .cant_have_keywords
1305            .contains(&kw.display_name().to_ascii_lowercase())
1306        {
1307            return false;
1308        }
1309        self.keywords.contains_keyword(kw)
1310            || self.granted_keywords.contains_keyword(kw)
1311            || self.pump_keywords.contains_keyword(kw)
1312    }
1313
1314    pub fn has_haste(&self) -> bool {
1315        self.has_keyword_enum(crate::keyword::keyword_instance::Keyword::Haste)
1316    }
1317
1318    pub fn has_flying(&self) -> bool {
1319        self.has_keyword_enum(crate::keyword::keyword_instance::Keyword::Flying)
1320    }
1321
1322    pub fn has_reach(&self) -> bool {
1323        self.has_keyword_enum(Kw::Reach)
1324    }
1325
1326    pub fn has_first_strike(&self) -> bool {
1327        self.has_keyword_enum(Kw::FirstStrike)
1328    }
1329
1330    pub fn has_double_strike(&self) -> bool {
1331        self.has_keyword_enum(Kw::DoubleStrike)
1332    }
1333
1334    pub fn has_trample(&self) -> bool {
1335        self.has_keyword_enum(Kw::Trample)
1336    }
1337
1338    pub fn has_deathtouch(&self) -> bool {
1339        self.has_keyword_enum(Kw::Deathtouch)
1340    }
1341
1342    pub fn has_lifelink(&self) -> bool {
1343        self.has_keyword_enum(Kw::Lifelink)
1344    }
1345
1346    pub fn has_vigilance(&self) -> bool {
1347        self.has_keyword_enum(Kw::Vigilance)
1348    }
1349
1350    pub fn has_defender(&self) -> bool {
1351        self.has_keyword_enum(Kw::Defender)
1352    }
1353
1354    pub fn has_hexproof(&self) -> bool {
1355        self.has_keyword_enum(Kw::Hexproof)
1356    }
1357
1358    pub fn has_shroud(&self) -> bool {
1359        self.has_keyword_enum(Kw::Shroud)
1360    }
1361
1362    pub fn has_menace(&self) -> bool {
1363        self.has_keyword_enum(Kw::Menace)
1364    }
1365
1366    pub fn has_fear(&self) -> bool {
1367        self.has_keyword_enum(Kw::Fear)
1368    }
1369
1370    pub fn has_intimidate(&self) -> bool {
1371        self.has_keyword_enum(Kw::Intimidate)
1372    }
1373
1374    pub fn has_shadow(&self) -> bool {
1375        self.has_keyword_enum(Kw::Shadow)
1376    }
1377
1378    pub fn has_skulk(&self) -> bool {
1379        self.has_keyword_enum(Kw::Skulk)
1380    }
1381
1382    pub fn has_horsemanship(&self) -> bool {
1383        self.has_keyword_enum(Kw::Horsemanship)
1384    }
1385
1386    pub fn has_indestructible(&self) -> bool {
1387        self.has_keyword_enum(Kw::Indestructible)
1388    }
1389
1390    pub fn has_infect(&self) -> bool {
1391        self.has_keyword_enum(Kw::Infect)
1392    }
1393
1394    pub fn has_wither(&self) -> bool {
1395        self.has_keyword_enum(Kw::Wither)
1396    }
1397
1398    pub fn has_prowess(&self) -> bool {
1399        self.has_keyword_enum(Kw::Prowess)
1400    }
1401
1402    pub fn has_rebound(&self) -> bool {
1403        self.has_keyword_enum(Kw::Rebound)
1404    }
1405
1406    /// Check "Hexproof from <color>" variants (e.g. "Hexproof from blue").
1407    pub fn has_hexproof_from(&self, color: &str) -> bool {
1408        let target = format!("Hexproof from {color}");
1409        self.keywords.contains_string_ignore_case(&target)
1410            || self.granted_keywords.contains_string_ignore_case(&target)
1411    }
1412
1413    /// Get Toxic count (e.g. "Toxic:1" → Some(1)).
1414    pub fn get_toxic_count(&self) -> Option<i32> {
1415        self.get_keyword_cost("Toxic").and_then(|s| s.parse().ok())
1416    }
1417
1418    /// Whether this card has the Storm keyword.
1419    pub fn has_storm(&self) -> bool {
1420        self.has_keyword_enum(Kw::Storm)
1421    }
1422
1423    pub fn has_cascade(&self) -> bool {
1424        self.has_keyword_enum(Kw::Cascade)
1425    }
1426
1427    /// Converted mana cost (mana value).
1428    pub fn mana_value(&self) -> i32 {
1429        self.mana_cost.cmc()
1430    }
1431
1432    /// Check "Protection from <quality>" (e.g. "Protection from red").
1433    pub fn has_protection_from(&self, quality: &str) -> bool {
1434        let target = format!("Protection from {quality}");
1435        self.keywords.contains_string_ignore_case(&target)
1436            || self.granted_keywords.contains_string_ignore_case(&target)
1437    }
1438
1439    /// Get all "Protection from X" values this card has.
1440    pub fn get_protections(&self) -> Vec<String> {
1441        let mut prots = Vec::new();
1442        for kw in self
1443            .keywords
1444            .iter_strings()
1445            .chain(self.granted_keywords.iter_strings())
1446        {
1447            if let Some(from) = kw.strip_prefix("Protection from ") {
1448                prots.push(from.to_lowercase());
1449            }
1450        }
1451        prots
1452    }
1453
1454    /// Check if this card is protected from a source card.
1455    /// Protection from <color> checks source's color.
1456    /// Protection from <type> checks source's type (e.g. "artifacts", "creatures").
1457    pub fn is_protected_from(&self, source: &Card) -> bool {
1458        for prot in self.get_protections() {
1459            match prot.as_str() {
1460                "white" => {
1461                    if source.color.has_white() {
1462                        return true;
1463                    }
1464                }
1465                "blue" => {
1466                    if source.color.has_blue() {
1467                        return true;
1468                    }
1469                }
1470                "black" => {
1471                    if source.color.has_black() {
1472                        return true;
1473                    }
1474                }
1475                "red" => {
1476                    if source.color.has_red() {
1477                        return true;
1478                    }
1479                }
1480                "green" => {
1481                    if source.color.has_green() {
1482                        return true;
1483                    }
1484                }
1485                "colorless" => {
1486                    if source.color.is_colorless() {
1487                        return true;
1488                    }
1489                }
1490                "artifacts" => {
1491                    if source.type_line.is_artifact() {
1492                        return true;
1493                    }
1494                }
1495                "creatures" => {
1496                    if source.type_line.is_creature() {
1497                        return true;
1498                    }
1499                }
1500                "enchantments" => {
1501                    if source.type_line.is_enchantment() {
1502                        return true;
1503                    }
1504                }
1505                _ => {}
1506            }
1507        }
1508        false
1509    }
1510
1511    pub fn can_attack(&self) -> bool {
1512        self.is_creature()
1513            && !self.tapped
1514            && !self.has_defender()
1515            && !self.cant_attack_static
1516            && !self.detained
1517            && (self.has_haste() || !self.summoning_sick)
1518            && self.zone == ZoneType::Battlefield
1519    }
1520
1521    pub fn can_block(&self) -> bool {
1522        self.is_creature()
1523            && !self.tapped
1524            && !self.cant_block_static
1525            && !self.detained
1526            && self.zone == ZoneType::Battlefield
1527    }
1528
1529    /// Check if this card can be controlled by the given player
1530    /// (e.g., checks for "Other players can't gain control of CARDNAME.")
1531    pub fn can_be_controlled_by(&self, player: PlayerId) -> bool {
1532        if player == self.controller {
1533            return true;
1534        }
1535        !self.has_keyword("Other players can't gain control of CARDNAME.")
1536    }
1537
1538    pub fn counter_count(&self, ct: &CounterType) -> i32 {
1539        *self.counters.get(ct).unwrap_or(&0)
1540    }
1541
1542    pub fn add_counter(&mut self, ct: &CounterType, count: i32) {
1543        let entry = self.counters.entry(ct.clone()).or_insert(0);
1544        *entry += count;
1545    }
1546
1547    pub fn remove_counter(&mut self, ct: &CounterType, count: i32) {
1548        let entry = self.counters.entry(ct.clone()).or_insert(0);
1549        *entry = (*entry - count).max(0);
1550    }
1551
1552    /// Reset state when entering the battlefield.
1553    pub fn enter_battlefield(&mut self) {
1554        self.tapped = false;
1555        self.damage = 0;
1556        self.summoning_sick = true;
1557        self.came_under_control_since_last_upkeep = true;
1558        self.has_deathtouch_damage = false;
1559        self.entered_battlefield_this_turn = true;
1560        self.attacked_this_turn = false;
1561        self.damage_sources_this_turn.clear();
1562    }
1563
1564    /// Reset per-turn state at start of turn.
1565    pub fn clear_global_turn_state(&mut self) {
1566        self.entered_battlefield_this_turn = false;
1567        self.attacked_this_turn = false;
1568        self.attached_this_turn = false;
1569        self.has_deathtouch_damage = false;
1570        self.damage_sources_this_turn.clear();
1571        self.total_damage_done_this_turn = 0;
1572    }
1573
1574    /// Reset controller-specific state at the start of that player's turn.
1575    pub fn new_turn(&mut self) {
1576        self.clear_global_turn_state();
1577        if self.zone == ZoneType::Battlefield {
1578            if let Ok(filter) = std::env::var("FORGE_CARD_TRACE") {
1579                if !filter.is_empty()
1580                    && self.card_name.eq_ignore_ascii_case(&filter)
1581                    && self.summoning_sick
1582                {
1583                    eprintln!(
1584                        "[card-trace] new_turn clears sickness on {}#{:?} (controller={:?})",
1585                        self.card_name, self.id, self.controller,
1586                    );
1587                }
1588            }
1589            self.summoning_sick = false;
1590        }
1591    }
1592
1593    /// Add a remembered card (for RememberCountered, etc.)
1594    pub fn add_remembered_card(&mut self, card_id: CardId) {
1595        if !self.remembered_cards.contains(&card_id) {
1596            self.remembered_cards.push(card_id);
1597        }
1598    }
1599
1600    /// Add a remembered CMC value
1601    pub fn add_remembered_cmc(&mut self, cmc: i32) {
1602        self.remembered_cmc.push(cmc);
1603    }
1604
1605    pub fn add_remembered_player(&mut self, player: PlayerId) {
1606        if !self.remembered_players.contains(&player) {
1607            self.remembered_players.push(player);
1608        }
1609    }
1610
1611    pub fn add_remembered_players<I>(&mut self, players: I)
1612    where
1613        I: IntoIterator<Item = PlayerId>,
1614    {
1615        for p in players {
1616            self.add_remembered_player(p);
1617        }
1618    }
1619
1620    pub fn has_remembered(&self) -> bool {
1621        !self.remembered_cards.is_empty()
1622            || !self.remembered_players.is_empty()
1623            || !self.remembered_cmc.is_empty()
1624    }
1625
1626    pub fn add_remembered(&mut self, card_id: CardId) {
1627        self.add_remembered_card(card_id);
1628    }
1629
1630    pub fn remove_remembered(&mut self, card_id: CardId) {
1631        self.remembered_cards.retain(|&c| c != card_id);
1632    }
1633
1634    pub fn clear_remembered(&mut self) {
1635        self.remembered_cards.clear();
1636        self.remembered_players.clear();
1637        self.remembered_cmc.clear();
1638    }
1639
1640    pub fn update_remembered(&mut self) {
1641        let mut seen = HashSet::new();
1642        self.remembered_cards.retain(|c| seen.insert(*c));
1643    }
1644
1645    pub fn has_imprinted_card(&self) -> bool {
1646        !self.imprinted_cards.is_empty()
1647    }
1648
1649    pub fn add_imprinted_card(&mut self, card_id: CardId) {
1650        if !self.imprinted_cards.contains(&card_id) {
1651            self.imprinted_cards.push(card_id);
1652        }
1653    }
1654
1655    pub fn add_imprinted_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1656        for c in cards {
1657            self.add_imprinted_card(c);
1658        }
1659    }
1660
1661    pub fn remove_imprinted_card(&mut self, card_id: CardId) {
1662        self.imprinted_cards.retain(|&c| c != card_id);
1663    }
1664
1665    pub fn remove_imprinted_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1666        for c in cards {
1667            self.remove_imprinted_card(c);
1668        }
1669    }
1670
1671    pub fn clear_imprinted_cards(&mut self) {
1672        self.imprinted_cards.clear();
1673    }
1674
1675    pub fn add_to_chosen_map(&mut self, player: PlayerId, chosen: Vec<CardId>) {
1676        self.chosen_map.insert(player, chosen);
1677    }
1678
1679    pub fn add_gain_control_target(&mut self, card_id: CardId) {
1680        if !self.gain_control_targets.contains(&card_id) {
1681            self.gain_control_targets.push(card_id);
1682        }
1683    }
1684
1685    pub fn remove_gain_control_targets(&mut self, card_id: CardId) {
1686        self.gain_control_targets.retain(|&c| c != card_id);
1687    }
1688
1689    pub fn has_gain_control_target(&self) -> bool {
1690        !self.gain_control_targets.is_empty()
1691    }
1692
1693    pub fn add_until_leaves_battlefield(&mut self, card_id: CardId) {
1694        if !self.until_leaves_battlefield.contains(&card_id) {
1695            self.until_leaves_battlefield.push(card_id);
1696        }
1697    }
1698
1699    pub fn remove_until_leaves_battlefield(&mut self, card_id: CardId) {
1700        self.until_leaves_battlefield.retain(|&c| c != card_id);
1701    }
1702
1703    pub fn clear_until_leaves_battlefield(&mut self) {
1704        self.until_leaves_battlefield.clear();
1705    }
1706
1707    pub fn has_exiled_card(&self) -> bool {
1708        !self.exiled_cards.is_empty()
1709    }
1710
1711    pub fn add_exiled_card(&mut self, card_id: CardId) {
1712        if !self.exiled_cards.contains(&card_id) {
1713            self.exiled_cards.push(card_id);
1714        }
1715    }
1716
1717    pub fn add_exiled_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1718        for c in cards {
1719            self.add_exiled_card(c);
1720        }
1721    }
1722
1723    pub fn remove_exiled_card(&mut self, card_id: CardId) {
1724        self.exiled_cards.retain(|&c| c != card_id);
1725    }
1726
1727    pub fn remove_exiled_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1728        for c in cards {
1729            self.remove_exiled_card(c);
1730        }
1731    }
1732
1733    pub fn clear_exiled_cards(&mut self) {
1734        self.exiled_cards.clear();
1735    }
1736
1737    pub fn add_haunted_by(&mut self, card_id: CardId) {
1738        if !self.haunted_by.contains(&card_id) {
1739            self.haunted_by.push(card_id);
1740        }
1741    }
1742
1743    pub fn remove_haunted_by(&mut self, card_id: CardId) {
1744        self.haunted_by.retain(|&c| c != card_id);
1745    }
1746
1747    pub fn has_encoded_card(&self) -> bool {
1748        !self.encoded_cards.is_empty()
1749    }
1750
1751    pub fn add_encoded_card(&mut self, card_id: CardId) {
1752        if !self.encoded_cards.contains(&card_id) {
1753            self.encoded_cards.push(card_id);
1754        }
1755    }
1756
1757    pub fn add_encoded_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
1758        for c in cards {
1759            self.add_encoded_card(c);
1760        }
1761    }
1762
1763    pub fn remove_encoded_card(&mut self, card_id: CardId) {
1764        self.encoded_cards.retain(|&c| c != card_id);
1765    }
1766
1767    pub fn clear_encoded_cards(&mut self) {
1768        self.encoded_cards.clear();
1769    }
1770
1771    pub fn has_merged_card(&self) -> bool {
1772        !self.melded_with.is_empty()
1773    }
1774
1775    pub fn add_merged_card(&mut self, card_id: CardId) {
1776        if !self.melded_with.contains(&card_id) {
1777            self.melded_with.push(card_id);
1778        }
1779    }
1780
1781    pub fn add_merged_card_to_top(&mut self, card_id: CardId) {
1782        if !self.melded_with.contains(&card_id) {
1783            self.melded_with.insert(0, card_id);
1784        }
1785    }
1786
1787    pub fn remove_merged_card(&mut self, card_id: CardId) {
1788        self.melded_with.retain(|&c| c != card_id);
1789    }
1790
1791    pub fn clear_merged_cards(&mut self) {
1792        self.melded_with.clear();
1793    }
1794
1795    pub fn remove_mutated_states(&mut self) {
1796        self.clear_merged_cards();
1797    }
1798
1799    pub fn rebuild_mutated_states(&mut self) {
1800        let mut seen = HashSet::new();
1801        self.melded_with.retain(|c| seen.insert(*c));
1802    }
1803
1804    pub fn move_merged_to_subgame(&mut self) {
1805        self.clear_merged_cards();
1806    }
1807
1808    pub fn entered_this_turn(&self) -> bool {
1809        self.entered_battlefield_this_turn
1810    }
1811
1812    pub fn entered_current_zone_this_turn(&self, turn_number: u32) -> bool {
1813        self.turn_in_zone == turn_number
1814    }
1815
1816    pub fn calculate_perpetual_adjusted_mana_cost(&mut self) {
1817        crate::card::card_state::calculate_perpetual_adjusted_mana_cost(self);
1818    }
1819
1820    pub fn has_chosen_player(&self) -> bool {
1821        self.chosen_player.is_some()
1822    }
1823
1824    pub fn reveal_chosen_player(&mut self) {
1825        self.chosen_player_revealed = true;
1826    }
1827
1828    pub fn has_promised_gift(&self) -> bool {
1829        self.promised_gift.is_some()
1830    }
1831
1832    pub fn has_chosen_number(&self) -> bool {
1833        self.chosen_number.is_some()
1834    }
1835
1836    pub fn clear_chosen_number(&mut self) {
1837        self.chosen_number = None;
1838        self.chosen_number_controller = None;
1839        self.chosen_number_revealed = false;
1840    }
1841
1842    pub fn has_chosen_type(&self) -> bool {
1843        self.chosen_type
1844            .as_ref()
1845            .map(|s| !s.is_empty())
1846            .unwrap_or(false)
1847    }
1848
1849    pub fn reveal_chosen_type(&mut self) {
1850        self.chosen_type_revealed = true;
1851    }
1852
1853    pub fn has_chosen_type2(&self) -> bool {
1854        self.chosen_type2
1855            .as_ref()
1856            .map(|s| !s.is_empty())
1857            .unwrap_or(false)
1858    }
1859
1860    pub fn has_any_noted_type(&self) -> bool {
1861        !self.noted_types.is_empty()
1862    }
1863
1864    pub fn add_noted_type(&mut self, ty: &str) {
1865        self.noted_types.push(ty.to_string());
1866    }
1867
1868    pub fn has_chosen_color(&self) -> bool {
1869        !self.chosen_colors.is_empty()
1870    }
1871
1872    pub fn has_chosen_card(&self) -> bool {
1873        !self.chosen_cards.is_empty()
1874    }
1875
1876    pub fn assign_sector(&mut self, sector: &str) {
1877        self.sector = Some(sector.to_string());
1878    }
1879
1880    pub fn has_attraction_light(&self, light: i32) -> bool {
1881        light > 0 && self.attraction_lights.contains(&(light as u32))
1882    }
1883
1884    pub fn has_sector(&self) -> bool {
1885        self.sector.is_some()
1886    }
1887
1888    pub fn handle_changed_controller_sprocket_reset(&mut self) {
1889        if self.sprocket != 0 {
1890            self.sprocket = -1;
1891        }
1892    }
1893
1894    pub fn add_named_card(&mut self, name: &str) {
1895        self.named_cards.push(name.to_string());
1896    }
1897
1898    pub fn has_named_card(&self) -> bool {
1899        !self.named_cards.is_empty()
1900    }
1901
1902    pub fn has_chosen_even_odd(&self) -> bool {
1903        self.chosen_even_odd.is_some()
1904    }
1905
1906    pub fn has_no_abilities(&self) -> bool {
1907        self.abilities.is_empty()
1908            && self.activated_abilities.is_empty()
1909            && self.triggers.is_empty()
1910            && self.static_abilities.is_empty()
1911            && self.replacement_effects.is_empty()
1912    }
1913
1914    pub fn can_tap(&self) -> bool {
1915        !self.tapped
1916    }
1917
1918    pub fn tap(&mut self) -> bool {
1919        if !self.can_tap() {
1920            return false;
1921        }
1922        self.tapped = true;
1923        true
1924    }
1925
1926    pub fn set_tapped(&mut self, tapped: bool) {
1927        if tapped {
1928            self.tap();
1929        } else {
1930            self.untap();
1931        }
1932    }
1933
1934    pub fn set_owner(&mut self, owner: PlayerId) {
1935        self.owner = owner;
1936    }
1937
1938    pub fn set_controller(&mut self, controller: PlayerId) {
1939        if self.controller != controller {
1940            self.came_under_control_since_last_upkeep = true;
1941        }
1942        self.controller = controller;
1943    }
1944
1945    pub fn set_is_token(&mut self, is_token: bool) {
1946        self.is_token = is_token;
1947    }
1948
1949    pub fn set_effect_source(&mut self, source: Option<CardId>) {
1950        self.effect_source = source;
1951    }
1952
1953    pub fn set_temp_effect_host(&mut self, host: Option<CardId>) {
1954        self.temp_effect_host = host;
1955    }
1956
1957    pub fn set_temp_effect_until_eot(&mut self, until_eot: bool) {
1958        self.temp_effect_until_eot = until_eot;
1959    }
1960
1961    pub fn set_forget_on_moved_origin(&mut self, zone: Option<ZoneType>) {
1962        self.forget_on_moved_origin = zone;
1963    }
1964
1965    pub fn set_exile_when_no_remembered(&mut self, exile: bool) {
1966        self.exile_when_no_remembered = exile;
1967    }
1968
1969    pub fn set_flipped(&mut self, flipped: bool) {
1970        self.flipped = flipped;
1971    }
1972
1973    pub fn can_untap(&self) -> bool {
1974        self.tapped
1975    }
1976
1977    pub fn untap(&mut self) -> bool {
1978        if !self.can_untap() {
1979            return false;
1980        }
1981        self.tapped = false;
1982        true
1983    }
1984
1985    pub fn exert(&mut self) {
1986        self.exerted = true;
1987    }
1988
1989    pub fn clear_exerted(&mut self) {
1990        self.exerted = false;
1991    }
1992
1993    pub fn remove_exerted_by(&mut self, _player: PlayerId) {
1994        self.exerted = false;
1995    }
1996
1997    pub fn detain(&mut self) {
1998        self.detained = true;
1999    }
2000
2001    pub fn add_goad(&mut self, player: PlayerId) {
2002        self.goaded_by = Some(player);
2003    }
2004
2005    pub fn remove_goad(&mut self, player: PlayerId) {
2006        if self.goaded_by == Some(player) {
2007            self.goaded_by = None;
2008        }
2009    }
2010
2011    pub fn un_goad(&mut self) {
2012        self.goaded_by = None;
2013    }
2014
2015    pub fn remove_detained_by(&mut self, _player: PlayerId) {
2016        self.detained = false;
2017    }
2018
2019    pub fn update_ability_text_for_view(&mut self) {
2020        self.update_spell_abilities();
2021    }
2022    pub fn update_non_ability_text_for_view(&mut self) {
2023        self.update_changed_text();
2024    }
2025    pub fn update_mana_cost_for_view(&mut self) {
2026        let _ = self.mana_value();
2027    }
2028    pub fn update_p_tfor_view(&mut self) {
2029        let _ = (self.power(), self.toughness());
2030    }
2031    pub fn update_color_for_view(&mut self) {
2032        let _ = self.color;
2033    }
2034    pub fn update_attacking_for_view(&mut self) {
2035        let _ = self.attacking_player;
2036    }
2037    pub fn update_blocking_for_view(&mut self) {
2038        let _ = self.must_block;
2039    }
2040    pub fn update_state_for_view(&mut self) {
2041        let _ = (self.zone, self.tapped, self.face_down);
2042    }
2043    pub fn update_namefor_view(&mut self) {
2044        self.card_name = self.card_name.trim().to_string();
2045    }
2046    pub fn update_token_view(&mut self) {
2047        let _ = self.is_token;
2048    }
2049    pub fn update_was_destroyed(&mut self) {
2050        let _ = self.damage >= self.toughness();
2051    }
2052    pub fn update_rules_view(&mut self) {
2053        let _ = (&self.abilities, &self.keywords);
2054    }
2055    pub fn update_commander_view(&mut self) {
2056        let _ = self.is_commander;
2057    }
2058    pub fn update_card(&mut self) {
2059        self.update_namefor_view();
2060        self.update_types_for_view();
2061        self.update_color_for_view();
2062        self.update_mana_cost_for_view();
2063        self.update_p_tfor_view();
2064        self.update_rules_view();
2065        self.update_state_for_view();
2066    }
2067    pub fn dangerously_set_game(&mut self) {
2068        self.update_card();
2069    }
2070    pub fn visit(&mut self) {
2071        self.update_card();
2072    }
2073
2074    pub fn has_state(&self) -> bool {
2075        self.is_transformed || self.other_part.is_some()
2076    }
2077
2078    /// Whether this card is double-faced (has a back side).
2079    /// Mirrors Java `Card.isDoubleFaced()`.
2080    pub fn is_double_faced(&self) -> bool {
2081        self.other_part.is_some()
2082    }
2083
2084    pub fn change_to_state(&mut self) {
2085        self.transform();
2086    }
2087
2088    pub fn add_alternate_state(&mut self, other: CardOtherPart) {
2089        self.other_part = Some(other);
2090    }
2091
2092    pub fn clear_states(&mut self) {
2093        self.other_part = None;
2094        self.is_transformed = false;
2095    }
2096
2097    pub fn change_card_state(&mut self) {
2098        self.transform();
2099    }
2100
2101    pub fn has_alternate_state(&self) -> bool {
2102        self.other_part.is_some()
2103    }
2104
2105    pub fn manifest(&mut self) {
2106        self.manifested = true;
2107        self.turn_face_down();
2108    }
2109
2110    pub fn cloak(&mut self) {
2111        self.cloaked = true;
2112        self.turn_face_down();
2113    }
2114
2115    pub fn turn_face_down(&mut self) {
2116        self.face_down = true;
2117    }
2118
2119    pub fn turn_face_down_no_update(&mut self) {
2120        self.face_down = true;
2121    }
2122
2123    pub fn can_be_turned_face_up(&self) -> bool {
2124        self.face_down
2125    }
2126
2127    pub fn force_turn_face_up(&mut self) {
2128        self.face_down = false;
2129    }
2130
2131    pub fn turn_face_up(&mut self) {
2132        self.face_down = false;
2133    }
2134
2135    pub fn set_face_down(&mut self, face_down: bool) {
2136        if face_down {
2137            self.turn_face_down();
2138        } else {
2139            self.turn_face_up();
2140        }
2141    }
2142
2143    pub fn set_manifested(&mut self, manifested: bool) {
2144        self.manifested = manifested;
2145    }
2146
2147    pub fn set_cloaked(&mut self, cloaked: bool) {
2148        self.cloaked = cloaked;
2149    }
2150
2151    pub fn set_discarded(&mut self, discarded: bool) {
2152        self.discarded = discarded;
2153    }
2154
2155    pub fn set_unearthed(&mut self, unearthed: bool) {
2156        self.unearthed = unearthed;
2157    }
2158
2159    pub fn set_summoning_sick(&mut self, summoning_sick: bool) {
2160        self.summoning_sick = summoning_sick;
2161    }
2162
2163    pub fn set_foretold(&mut self, foretold: bool) {
2164        self.foretold = foretold;
2165    }
2166
2167    pub fn set_foretold_cost_by_effect(&mut self, by_effect: bool) {
2168        self.foretold_cost_by_effect = by_effect;
2169    }
2170
2171    pub fn set_transformed(&mut self, transformed: bool) {
2172        self.is_transformed = transformed;
2173    }
2174
2175    pub fn set_attacking_player(&mut self, player: PlayerId) {
2176        self.attacking_player = Some(player);
2177    }
2178
2179    pub fn clear_attacking_player(&mut self) {
2180        self.attacking_player = None;
2181    }
2182
2183    pub fn mark_attacked_this_turn(&mut self) {
2184        self.attacked_this_turn = true;
2185    }
2186
2187    pub fn add_etb_counters_p1p1(&mut self, amount: i32) {
2188        self.etb_counters_p1p1 += amount;
2189    }
2190
2191    pub fn increment_commander_cast_count(&mut self) {
2192        self.commander_cast_count += 1;
2193    }
2194
2195    pub fn set_kicked(&mut self, kicked: bool) {
2196        self.kicked = kicked;
2197    }
2198
2199    pub fn mark_enlisted_this_combat(&mut self) {
2200        self.enlisted_this_combat = true;
2201    }
2202
2203    pub fn add_enlisted_power(&mut self, amount: i32) {
2204        self.power_modifier += amount;
2205    }
2206
2207    pub fn add_damage_source_this_turn(&mut self, source: CardId) {
2208        self.damage_sources_this_turn.push(source);
2209    }
2210
2211    pub fn mark_deathtouch_damage(&mut self) {
2212        self.has_deathtouch_damage = true;
2213    }
2214
2215    pub fn clear_deathtouch_damage(&mut self) {
2216        self.has_deathtouch_damage = false;
2217    }
2218
2219    pub fn clear_damage(&mut self) {
2220        self.damage = 0;
2221    }
2222
2223    pub fn reset_turn_modifiers(&mut self) {
2224        self.power_modifier = 0;
2225        self.toughness_modifier = 0;
2226    }
2227
2228    pub fn reset_regeneration_shields(&mut self) {
2229        self.regeneration_shields = 0;
2230    }
2231
2232    pub fn clear_original_controller_eot(&mut self) {
2233        self.original_controller_eot = None;
2234    }
2235
2236    pub fn set_chosen_modes(&mut self, modes: Vec<usize>) {
2237        self.chosen_modes = Some(modes);
2238    }
2239
2240    pub fn set_chosen_cards(&mut self, cards: Vec<CardId>) {
2241        self.chosen_cards = cards;
2242    }
2243
2244    pub fn set_chosen_number(&mut self, number: Option<i32>) {
2245        self.chosen_number = number;
2246        self.chosen_number_controller = None;
2247        self.chosen_number_revealed = number.is_some();
2248    }
2249
2250    pub fn set_chosen_number_for_player(
2251        &mut self,
2252        number: Option<i32>,
2253        chooser: PlayerId,
2254        revealed: bool,
2255    ) {
2256        self.chosen_number = number;
2257        self.chosen_number_controller = Some(chooser);
2258        self.chosen_number_revealed = revealed;
2259    }
2260
2261    pub fn set_chosen_mode(&mut self, mode: impl Into<String>) {
2262        self.chosen_mode = Some(mode.into());
2263    }
2264
2265    pub fn set_chosen_player(
2266        &mut self,
2267        player: Option<PlayerId>,
2268        chooser: Option<PlayerId>,
2269        revealed: bool,
2270    ) {
2271        self.chosen_player = player;
2272        self.chosen_player_controller = chooser;
2273        self.chosen_player_revealed = revealed;
2274    }
2275
2276    pub fn set_chosen_type(
2277        &mut self,
2278        chosen_type: Option<String>,
2279        chooser: Option<PlayerId>,
2280        revealed: bool,
2281    ) {
2282        self.chosen_type = chosen_type;
2283        self.chosen_type_controller = chooser;
2284        self.chosen_type_revealed = revealed;
2285    }
2286
2287    pub fn set_strive_extra_targets(&mut self, value: u32) {
2288        self.strive_extra_targets = value;
2289    }
2290
2291    pub fn set_colors_spent_to_cast(&mut self, colors: u16) {
2292        self.colors_spent_to_cast = colors;
2293    }
2294
2295    pub fn set_paying_mana_to_cast(&mut self, paying_mana: Vec<u16>) {
2296        self.paying_mana_to_cast = paying_mana;
2297    }
2298
2299    pub fn set_promised_gift(&mut self, player: Option<PlayerId>) {
2300        self.promised_gift = player;
2301    }
2302
2303    pub fn set_lki_power_toughness(&mut self, power: Option<i32>, toughness: Option<i32>) {
2304        self.lki_power = power;
2305        self.lki_toughness = toughness;
2306    }
2307
2308    pub fn restore_animate_snapshot(
2309        &mut self,
2310        type_line: CardTypeLine,
2311        base_power: Option<i32>,
2312        base_toughness: Option<i32>,
2313        color: ColorSet,
2314    ) {
2315        self.set_type_line(type_line);
2316        self.base_power = base_power;
2317        self.base_toughness = base_toughness;
2318        self.color = color;
2319    }
2320
2321    pub fn capture_clone_state(&self) -> CloneState {
2322        CloneState {
2323            expires_at_cleanup: false,
2324            original_card_name: self.card_name.clone(),
2325            original_oracle_text: self.oracle_text.clone(),
2326            original_type_line: self.type_line.clone(),
2327            original_mana_cost: self.mana_cost.clone(),
2328            original_color: self.color,
2329            original_base_power: self.base_power,
2330            original_base_toughness: self.base_toughness,
2331            original_keywords: self.keywords.clone(),
2332            original_abilities: self.abilities.clone(),
2333            original_activated_abilities: self.activated_abilities.clone(),
2334            original_triggers: self.triggers.clone(),
2335            original_svars: self.svars.clone(),
2336            original_static_abilities: self.static_abilities.clone(),
2337            original_replacement_effects: self.replacement_effects.clone(),
2338            original_base_ability_count: self.base_ability_count,
2339            original_base_trigger_count: self.base_trigger_count,
2340        }
2341    }
2342
2343    pub fn restore_clone_snapshot(&mut self, state: CloneState) {
2344        self.card_name = state.original_card_name;
2345        self.oracle_text = state.original_oracle_text;
2346        self.type_line = state.original_type_line;
2347        self.mana_cost = state.original_mana_cost;
2348        self.color = state.original_color;
2349        self.base_power = state.original_base_power;
2350        self.base_toughness = state.original_base_toughness;
2351        self.keywords = state.original_keywords;
2352        self.abilities = state.original_abilities;
2353        self.activated_abilities = state.original_activated_abilities;
2354        self.triggers = state.original_triggers;
2355        self.svars = state.original_svars;
2356        self.static_abilities = state.original_static_abilities;
2357        self.replacement_effects = state.original_replacement_effects;
2358        self.base_ability_count = state.original_base_ability_count;
2359        self.base_trigger_count = state.original_base_trigger_count;
2360        self.parsed_svar_cache.clear();
2361        self.refresh_action_specs();
2362        self.ensure_crew_activated_ability();
2363        self.remove_clone_state();
2364    }
2365
2366    pub fn set_counters_map(&mut self, counters: BTreeMap<CounterType, i32>) {
2367        self.counters = counters;
2368    }
2369
2370    pub fn set_zone(&mut self, zone: ZoneType) {
2371        self.zone = zone;
2372    }
2373
2374    pub fn set_color(&mut self, color: ColorSet) {
2375        self.color = color;
2376    }
2377
2378    pub fn set_animate_state(&mut self, state: Option<AnimateState>) {
2379        self.animate_state = state;
2380    }
2381
2382    pub fn set_clone_state(&mut self, state: Option<CloneState>) {
2383        self.clone_state = state;
2384    }
2385
2386    pub fn set_exiled_by(&mut self, source: Option<CardId>) {
2387        self.exiled_by = source;
2388    }
2389
2390    pub fn set_attached_to(&mut self, target: Option<CardId>) {
2391        self.attached_to = target;
2392    }
2393
2394    pub fn set_original_controller_eot(&mut self, controller: Option<PlayerId>) {
2395        self.original_controller_eot = controller;
2396    }
2397
2398    pub fn set_class_level(&mut self, level: i32) {
2399        self.class_level = level;
2400    }
2401
2402    pub fn set_paired_with(&mut self, pair: Option<CardId>) {
2403        self.paired_with = pair;
2404    }
2405
2406    pub fn set_must_block(&mut self, must_block: bool) {
2407        self.must_block = must_block;
2408    }
2409
2410    pub fn set_detained(&mut self, detained: bool) {
2411        self.detained = detained;
2412    }
2413
2414    pub fn set_goaded_by(&mut self, player: Option<PlayerId>) {
2415        self.goaded_by = player;
2416    }
2417
2418    pub fn set_phased_out(&mut self, phased_out: bool) {
2419        self.phased_out = phased_out;
2420    }
2421
2422    pub fn set_base_power(&mut self, power: Option<i32>) {
2423        self.base_power = power;
2424    }
2425
2426    pub fn set_base_toughness(&mut self, toughness: Option<i32>) {
2427        self.base_toughness = toughness;
2428    }
2429
2430    pub fn set_base_pt(&mut self, power: Option<i32>, toughness: Option<i32>) {
2431        self.base_power = power;
2432        self.base_toughness = toughness;
2433    }
2434
2435    pub fn capture_changed_characteristics_baseline_if_needed(&mut self) {
2436        if self.changed_type_line_base.is_none() {
2437            self.changed_type_line_base = Some(self.type_line.clone());
2438        }
2439        if self.changed_base_power.is_none() {
2440            self.changed_base_power = Some(self.base_power);
2441        }
2442        if self.changed_base_toughness.is_none() {
2443            self.changed_base_toughness = Some(self.base_toughness);
2444        }
2445    }
2446
2447    pub fn restore_changed_characteristics_baseline(&mut self) {
2448        if let Some(type_line) = self.changed_type_line_base.take() {
2449            self.set_type_line(type_line);
2450        }
2451        if let Some(power) = self.changed_base_power.take() {
2452            self.base_power = power;
2453        }
2454        if let Some(toughness) = self.changed_base_toughness.take() {
2455            self.base_toughness = toughness;
2456        }
2457    }
2458
2459    pub fn set_static_set_pt(&mut self, power: Option<i32>, toughness: Option<i32>) {
2460        self.static_set_power = power;
2461        self.static_set_toughness = toughness;
2462    }
2463
2464    pub fn set_power_modifier(&mut self, amount: i32) {
2465        self.power_modifier = amount;
2466    }
2467
2468    pub fn set_toughness_modifier(&mut self, amount: i32) {
2469        self.toughness_modifier = amount;
2470    }
2471
2472    pub fn set_card_name(&mut self, name: impl Into<String>) {
2473        self.card_name = name.into();
2474    }
2475
2476    pub fn set_mana_cost(&mut self, mana_cost: ManaCost) {
2477        self.mana_cost = mana_cost;
2478    }
2479
2480    pub fn set_abilities(&mut self, abilities: Vec<String>) {
2481        self.abilities = abilities;
2482        self.update_spell_abilities();
2483        self.refresh_action_specs();
2484    }
2485
2486    pub fn set_static_abilities(&mut self, abilities: Vec<StaticAbility>) {
2487        self.static_abilities = abilities;
2488    }
2489
2490    pub fn set_triggers(&mut self, triggers: Vec<Trigger>) {
2491        self.triggers = triggers;
2492        self.base_trigger_count = self.triggers.len();
2493    }
2494
2495    pub fn set_replacement_effects(&mut self, effects: Vec<ReplacementEffect>) {
2496        self.replacement_effects = effects;
2497    }
2498
2499    pub fn set_renowned(&mut self, renowned: bool) {
2500        self.is_renowned = renowned;
2501    }
2502
2503    pub fn set_monstrous(&mut self, monstrous: bool) {
2504        self.monstrous = monstrous;
2505    }
2506
2507    pub fn clear_granted_keywords(&mut self) {
2508        self.granted_keywords.clear();
2509    }
2510
2511    pub fn clear_pump_keywords(&mut self) {
2512        self.pump_keywords.clear();
2513    }
2514
2515    pub fn increment_pump_trigger_count(&mut self) {
2516        self.pump_trigger_count += 1;
2517    }
2518
2519    pub fn add_remembered_cards<I>(&mut self, cards: I)
2520    where
2521        I: IntoIterator<Item = CardId>,
2522    {
2523        for card in cards {
2524            self.add_remembered_card(card);
2525        }
2526    }
2527
2528    pub fn clear_chosen_colors(&mut self) {
2529        self.chosen_colors.clear();
2530    }
2531
2532    pub fn add_chosen_color(&mut self, color: impl Into<String>) {
2533        self.chosen_colors.push(color.into());
2534    }
2535
2536    pub fn add_chosen_card(&mut self, card: CardId) {
2537        if !self.chosen_cards.contains(&card) {
2538            self.chosen_cards.push(card);
2539        }
2540    }
2541
2542    pub fn add_pump_keyword(&mut self, keyword: &str) {
2543        self.pump_keywords.add(keyword);
2544    }
2545
2546    pub fn add_granted_keyword(&mut self, keyword: &str) {
2547        self.granted_keywords.add(keyword);
2548    }
2549
2550    pub fn was_turned_face_up_this_turn(&self) -> bool {
2551        !self.face_down && (self.manifested || self.cloaked)
2552    }
2553
2554    pub fn can_transform(&self) -> bool {
2555        self.other_part.is_some()
2556    }
2557
2558    pub fn has_name_overwrite(&self) -> bool {
2559        false
2560    }
2561
2562    pub fn has_non_legendary_creature_names(&self) -> bool {
2563        false
2564    }
2565
2566    pub fn add_changed_name(&mut self, name: &str) {
2567        if !self.has_s_var("OriginalName") {
2568            self.set_s_var("OriginalName", self.card_name.clone());
2569        }
2570        self.card_name = name.to_string();
2571    }
2572
2573    pub fn remove_changed_name(&mut self) {
2574        if let Some(orig) = self.svars.get("OriginalName").cloned() {
2575            self.card_name = orig;
2576        }
2577    }
2578
2579    pub fn clear_changed_name(&mut self) {
2580        self.remove_s_var("OriginalName");
2581    }
2582
2583    pub fn add_devoured(&mut self, card_id: CardId) {
2584        self.add_remembered_card(card_id);
2585        self.set_s_var("Devoured", "True");
2586    }
2587    pub fn add_exploited(&mut self, card_id: CardId) {
2588        self.add_remembered_card(card_id);
2589        self.set_s_var("Exploited", "True");
2590    }
2591    pub fn add_delved(&mut self, card_id: CardId) {
2592        self.add_remembered_card(card_id);
2593        self.set_s_var("Delved", "True");
2594    }
2595    pub fn clear_delved(&mut self) {
2596        self.remove_s_var("Delved");
2597    }
2598    pub fn retain_paid_list(&mut self) {
2599        self.remembered_cards.retain(|_| true);
2600    }
2601    pub fn add_stored_rolls(&mut self, roll: i32) {
2602        self.stored_rolls.push(roll);
2603        self.stored_rolls.sort_unstable();
2604    }
2605    pub fn replace_stored_roll(&mut self, from: i32, to: i32) {
2606        if let Some(index) = self.stored_rolls.iter().position(|roll| *roll == from) {
2607            self.stored_rolls.remove(index);
2608            self.stored_rolls.push(to);
2609            self.stored_rolls.sort_unstable();
2610        }
2611    }
2612    pub fn add_flip_result(&mut self, heads: bool) {
2613        self.set_s_var("FlipResult", if heads { "Heads" } else { "Tails" });
2614    }
2615    pub fn clear_flip_result(&mut self) {
2616        self.remove_s_var("FlipResult");
2617    }
2618    pub fn add_blocked_this_turn(&mut self, card_id: CardId) {
2619        self.add_remembered_card(card_id);
2620        self.set_s_var("BlockedThisTurn", "True");
2621    }
2622    pub fn clear_blocked_this_turn(&mut self) {
2623        self.remove_s_var("BlockedThisTurn");
2624    }
2625    pub fn add_blocked_by_this_turn(&mut self, card_id: CardId) {
2626        self.add_remembered_card(card_id);
2627        self.set_s_var("BlockedByThisTurn", "True");
2628    }
2629    pub fn clear_blocked_by_this_turn(&mut self) {
2630        self.remove_s_var("BlockedByThisTurn");
2631    }
2632
2633    pub fn add_must_block_card(&mut self, card_id: CardId) {
2634        if !self.must_block_cards.contains(&card_id) {
2635            self.must_block_cards.push(card_id);
2636        }
2637    }
2638
2639    pub fn add_must_block_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
2640        for c in cards {
2641            self.add_must_block_card(c);
2642        }
2643    }
2644
2645    pub fn remove_must_block_cards(&mut self, cards: impl IntoIterator<Item = CardId>) {
2646        let remove: HashSet<CardId> = cards.into_iter().collect();
2647        self.must_block_cards.retain(|c| !remove.contains(c));
2648    }
2649
2650    pub fn clear_must_block_cards(&mut self) {
2651        self.must_block_cards.clear();
2652    }
2653
2654    pub fn has_second_strike(&self) -> bool {
2655        self.has_double_strike()
2656    }
2657
2658    pub fn has_suspend(&self) -> bool {
2659        self.has_keyword("Suspend")
2660    }
2661
2662    pub fn has_converge(&self) -> bool {
2663        self.has_keyword("Converge")
2664    }
2665
2666    pub fn can_receive_counters(&self, _counter: &CounterType) -> bool {
2667        true
2668    }
2669
2670    pub fn can_remove_counters(&self, counter: &CounterType) -> bool {
2671        self.counter_count(counter) > 0
2672    }
2673
2674    pub fn add_counter_internal(&mut self, counter: &CounterType, amount: i32) {
2675        self.add_counter(counter, amount);
2676    }
2677
2678    pub fn create_counter_static(&mut self) {
2679        self.put_etb_counters();
2680    }
2681
2682    pub fn subtract_counter(&mut self, counter: &CounterType, amount: i32) {
2683        self.remove_counter(counter, amount);
2684    }
2685
2686    pub fn clear_counters(&mut self) {
2687        self.counters.clear();
2688    }
2689
2690    pub fn sum_all_counters(&self) -> i32 {
2691        self.counters.values().sum()
2692    }
2693
2694    pub fn put_etb_counters(&mut self) {
2695        if self.etb_counters_p1p1 > 0 {
2696            self.add_counter(&CounterType::P1P1, self.etb_counters_p1p1);
2697            self.etb_counters_p1p1 = 0;
2698        }
2699    }
2700
2701    pub fn copy_changed_s_vars_from(&mut self, other: &Card) {
2702        self.set_svars_map(other.svars.clone());
2703    }
2704
2705    pub fn add_changed_s_vars(&mut self, key: &str, value: &str) {
2706        self.set_s_var(key, value);
2707    }
2708
2709    pub fn remove_changed_s_vars(&mut self, key: &str) {
2710        self.remove_s_var(key);
2711    }
2712
2713    pub fn add_changed_mana_cost(&mut self, mana_cost: &str) {
2714        if !self.has_s_var("OriginalManaCost") {
2715            self.set_s_var("OriginalManaCost", self.mana_cost.to_string());
2716        }
2717        self.mana_cost = ManaCost::parse(mana_cost);
2718        self.calculate_perpetual_adjusted_mana_cost();
2719        self.update_mana_cost_for_view();
2720    }
2721    pub fn remove_changed_mana_cost(&mut self, _timestamp: i64, _static_id: i64) -> bool {
2722        let Some(original) = self.svars.get("OriginalManaCost").cloned() else {
2723            return false;
2724        };
2725        let before = self.mana_cost.clone();
2726        self.mana_cost = ManaCost::parse(&original);
2727        self.calculate_perpetual_adjusted_mana_cost();
2728        self.update_mana_cost_for_view();
2729        self.remove_s_var("OriginalManaCost");
2730        self.mana_cost != before
2731    }
2732
2733    pub fn cleanup_exiled_with(&mut self) {
2734        self.exiled_by = None;
2735    }
2736
2737    pub fn has_paper_foil(&self) -> bool {
2738        self.paper_foil
2739    }
2740
2741    pub fn has_marked_color(&self) -> bool {
2742        !self.color.is_colorless()
2743    }
2744
2745    pub fn can_produce_color_mana(
2746        &self,
2747        game: &GameState,
2748        colors: &std::collections::HashSet<String>,
2749    ) -> bool {
2750        crate::card::card_util::card_can_produce_color_mana(game, self.id, colors)
2751    }
2752
2753    pub fn can_produce_same_mana_type_with(&self, game: &GameState, other: &Card) -> bool {
2754        crate::card::card_util::card_can_produce_same_mana_type_with(game, self.id, other.id)
2755    }
2756
2757    pub fn has_remove_intrinsic(&self) -> bool {
2758        false
2759    }
2760
2761    pub fn update_spell_abilities(&mut self) {
2762        self.activated_abilities.clear();
2763        for (i, raw) in self.abilities.iter().enumerate() {
2764            if let Some(parsed) = crate::ability::activated::parse_activated_ability(raw, i) {
2765                self.activated_abilities.push(parsed);
2766            }
2767        }
2768    }
2769
2770    pub fn refresh_action_specs(&mut self) {
2771        let mut spell_specs = Vec::new();
2772        let mut spell_cost = None;
2773        let mut ai_phyrexian_payment = None;
2774        let mut spree_min_mode_cost = None;
2775
2776        for (ability_index, raw) in self.abilities.iter().enumerate() {
2777            let parsed = ParsedParams::parse(raw);
2778            if ai_phyrexian_payment.is_none() {
2779                ai_phyrexian_payment = parsed.get(keys::AI_PHYREXIAN_PAYMENT).map(str::to_string);
2780            }
2781            let Some(sp_kind) = parsed.get(keys::SP) else {
2782                continue;
2783            };
2784            let cost_contains_x = parsed
2785                .get(keys::COST)
2786                .is_some_and(|cost| cost.contains('X'));
2787            if spell_cost.is_none() {
2788                spell_cost = parsed.get(keys::COST).map(parse_cost);
2789            }
2790            spell_specs.push(CardActionSpellSpec {
2791                ability_index,
2792                has_valid_tgts: parsed.has(keys::VALID_TGTS),
2793                cost_contains_x,
2794                target_chain: self.collect_action_target_chain(raw),
2795            });
2796
2797            if sp_kind.eq_ignore_ascii_case("Charm") {
2798                if let Some(choices) = parsed.get(keys::CHOICES) {
2799                    let min_mode_cost = choices
2800                        .split(',')
2801                        .filter_map(|name| {
2802                            self.svars.get(name.trim()).and_then(|svar_val| {
2803                                ParsedParams::parse(svar_val)
2804                                    .get(keys::MODE_COST)
2805                                    .map(|cost| forge_foundation::ManaCost::parse(cost).cmc())
2806                            })
2807                        })
2808                        .min();
2809                    spree_min_mode_cost = spree_min_mode_cost.or(min_mode_cost);
2810                }
2811            }
2812        }
2813
2814        self.action_spell_specs = spell_specs;
2815        self.action_spell_cost = spell_cost;
2816        self.ai_phyrexian_payment = ai_phyrexian_payment;
2817        self.spree_min_mode_cost = spree_min_mode_cost;
2818    }
2819
2820    fn refresh_action_specs_after_svar_change(&mut self) {
2821        if self.action_spell_specs.is_empty() {
2822            return;
2823        }
2824        self.refresh_action_specs();
2825    }
2826
2827    fn collect_action_target_chain(&self, ability_text: &str) -> Vec<CardActionTargetSpec> {
2828        let mut specs = Vec::new();
2829        let mut current = Some(ability_text.to_string());
2830
2831        while let Some(text) = current {
2832            let parsed = ParsedParams::parse(&text);
2833            let params = Params::from_parsed(&parsed);
2834            if let Some(target_restrictions) = TargetRestrictions::new_from_parsed(&parsed, &params)
2835            {
2836                specs.push(CardActionTargetSpec {
2837                    min_targets: parse_literal_target_count(&target_restrictions.min_targets),
2838                    target_restrictions,
2839                });
2840            }
2841
2842            current = parsed
2843                .get(keys::SUB_ABILITY)
2844                .and_then(|name| self.svars.get(name.trim()))
2845                .cloned();
2846        }
2847
2848        specs
2849    }
2850
2851    pub fn inc_shield_count(&mut self) {
2852        self.damage_prevention += 1;
2853    }
2854
2855    pub fn dec_shield_count(&mut self) {
2856        self.damage_prevention = (self.damage_prevention - 1).max(0);
2857    }
2858
2859    pub fn reset_shield_count(&mut self) {
2860        self.damage_prevention = 0;
2861    }
2862
2863    pub fn add_regenerated_this_turn(&mut self) {
2864        self.regeneration_shields += 1;
2865    }
2866
2867    pub fn can_be_shielded(&self) -> bool {
2868        self.is_permanent()
2869    }
2870
2871    pub fn add_untap_command(&mut self) {
2872        self.set_s_var("_cmd_untap", "1");
2873    }
2874    pub fn add_unattach_command(&mut self) {
2875        self.set_s_var("_cmd_unattach", "1");
2876    }
2877    pub fn add_faceup_command(&mut self) {
2878        self.set_s_var("_cmd_faceup", "1");
2879    }
2880    pub fn add_facedown_command(&mut self) {
2881        self.set_s_var("_cmd_facedown", "1");
2882    }
2883    pub fn add_change_controller_command(&mut self) {
2884        self.set_s_var("_cmd_change_controller", "1");
2885    }
2886    pub fn add_phase_out_command(&mut self) {
2887        self.set_s_var("_cmd_phase_out", "1");
2888    }
2889    pub fn add_leaves_play_command(&mut self) {
2890        self.set_s_var("_cmd_leaves_play", "1");
2891    }
2892    pub fn add_static_command_list(&mut self) {
2893        self.set_s_var("_cmd_static", "1");
2894    }
2895    pub fn run_leaves_play_commands(&mut self) {
2896        if self.has_s_var("_cmd_leaves_play") {
2897            self.cleanup_exiled_with();
2898            self.remove_s_var("_cmd_leaves_play");
2899        }
2900    }
2901    pub fn run_untap_commands(&mut self) {
2902        if self.has_s_var("_cmd_untap") {
2903            self.untap();
2904            self.remove_s_var("_cmd_untap");
2905        }
2906    }
2907    pub fn run_unattach_commands(&mut self) {
2908        if self.has_s_var("_cmd_unattach") {
2909            self.unattach_from_entity();
2910            self.remove_s_var("_cmd_unattach");
2911        }
2912    }
2913    pub fn run_faceup_commands(&mut self) {
2914        if self.has_s_var("_cmd_faceup") {
2915            self.turn_face_up();
2916            self.remove_s_var("_cmd_faceup");
2917        }
2918    }
2919    pub fn run_facedown_commands(&mut self) {
2920        if self.has_s_var("_cmd_facedown") {
2921            self.turn_face_down();
2922            self.remove_s_var("_cmd_facedown");
2923        }
2924    }
2925    pub fn run_change_controller_commands(&mut self) {
2926        if self.has_s_var("_cmd_change_controller") {
2927            self.clear_temp_controllers();
2928            self.remove_s_var("_cmd_change_controller");
2929        }
2930    }
2931    pub fn run_phase_out_commands(&mut self) {
2932        if self.has_s_var("_cmd_phase_out") {
2933            self.phase();
2934            self.remove_s_var("_cmd_phase_out");
2935        }
2936    }
2937
2938    pub fn has_sickness(&self) -> bool {
2939        self.summoning_sick
2940    }
2941
2942    pub fn has_become_target_this_turn(&self) -> bool {
2943        self.became_target_this_turn
2944    }
2945
2946    pub fn add_target_from_this_turn(&mut self) {
2947        self.became_target_this_turn = true;
2948    }
2949
2950    pub fn has_started_the_turn_untapped(&self) -> bool {
2951        !self.started_turn_tapped
2952    }
2953
2954    pub fn came_under_control_since_last_upkeep(&self) -> bool {
2955        self.came_under_control_since_last_upkeep
2956    }
2957
2958    pub fn add_temp_controller(&mut self, player: PlayerId) {
2959        self.temp_controllers.push(player);
2960    }
2961
2962    pub fn remove_temp_controller(&mut self, player: PlayerId) {
2963        self.temp_controllers.retain(|&p| p != player);
2964    }
2965
2966    pub fn clear_temp_controllers(&mut self) {
2967        self.temp_controllers.clear();
2968    }
2969
2970    pub fn clear_controllers(&mut self) {
2971        self.controller = self.owner;
2972        self.clear_temp_controllers();
2973    }
2974
2975    pub fn may_player_look(&self, player: PlayerId) -> bool {
2976        self.may_look_at.contains(&player)
2977    }
2978
2979    pub fn add_may_look_face_down_exile(&mut self, player: PlayerId) {
2980        if !self.may_look_at.contains(&player) {
2981            self.may_look_at.push(player);
2982        }
2983    }
2984
2985    pub fn add_may_look_at(&mut self, player: PlayerId) {
2986        if !self.may_look_at.contains(&player) {
2987            self.may_look_at.push(player);
2988        }
2989    }
2990
2991    pub fn remove_may_look_at(&mut self, player: PlayerId) {
2992        self.may_look_at.retain(|&p| p != player);
2993    }
2994
2995    pub fn add_may_look_temp(&mut self, player: PlayerId) {
2996        self.add_may_look_at(player);
2997    }
2998
2999    pub fn remove_may_look_temp(&mut self, player: PlayerId) {
3000        self.remove_may_look_at(player);
3001    }
3002
3003    pub fn update_may_look(&mut self) {
3004        let mut seen = HashSet::new();
3005        self.may_look_at.retain(|p| seen.insert(*p));
3006    }
3007    pub fn update_may_play(&mut self) {
3008        let mut seen = HashSet::new();
3009        self.may_play.retain(|p| seen.insert(*p));
3010    }
3011
3012    pub fn may_play(&self, player: PlayerId) -> bool {
3013        self.may_play.contains(&player)
3014    }
3015
3016    pub fn remove_may_play(&mut self, player: PlayerId) {
3017        self.may_play.retain(|&p| p != player);
3018    }
3019
3020    pub fn reset_may_play_turn(&mut self) {
3021        self.may_play.clear();
3022    }
3023
3024    pub fn remove_attached_to(&mut self) {
3025        self.attached_to = None;
3026    }
3027
3028    pub fn attach_to_entity(&mut self, host: CardId) {
3029        self.attached_to = Some(host);
3030    }
3031
3032    pub fn add_attachment(&mut self, card_id: CardId) {
3033        if !self.attachments.contains(&card_id) {
3034            self.attachments.push(card_id);
3035        }
3036    }
3037
3038    pub fn remove_attachment(&mut self, card_id: CardId) {
3039        self.attachments.retain(|&id| id != card_id);
3040    }
3041
3042    pub fn unattach_from_entity(&mut self) {
3043        self.attached_to = None;
3044    }
3045
3046    pub fn clear_intrinsic_keywords(&mut self) {
3047        self.keywords.clear();
3048    }
3049
3050    pub fn clear_all_keyword_sets(&mut self) {
3051        self.keywords.clear();
3052        self.pump_keywords.clear();
3053        self.granted_keywords.clear();
3054    }
3055
3056    pub fn clear_subtypes(&mut self) {
3057        self.type_line.subtypes.clear();
3058    }
3059
3060    pub fn clear_changed_card_types(&mut self) {
3061        self.update_types();
3062    }
3063    pub fn clear_changed_card_colors(&mut self) {
3064        self.color = ColorSet::COLORLESS;
3065    }
3066    pub fn add_changed_card_types_by_text(&mut self) {
3067        self.update_types();
3068    }
3069    pub fn remove_changed_card_types_by_text(&mut self) {
3070        self.update_types();
3071    }
3072    pub fn add_changed_card_types(&mut self) {
3073        self.update_types();
3074    }
3075    pub fn remove_changed_card_types(&mut self) {
3076        self.update_types();
3077    }
3078    pub fn update_type_cache(&mut self) {
3079        self.type_line = CardTypeLine::parse(&self.type_line.to_string());
3080    }
3081    pub fn has_changed_card_colors(&self) -> bool {
3082        !self.color.is_colorless()
3083    }
3084    pub fn add_color_by_text(&mut self, color: ColorSet) {
3085        self.add_color(color);
3086    }
3087    pub fn remove_color_by_text(&mut self) {
3088        self.remove_color();
3089    }
3090    pub fn remove_color(&mut self) {
3091        self.color = ColorSet::COLORLESS;
3092    }
3093    pub fn add_clone_state(&mut self) {
3094        self.set_s_var("CloneState", "True");
3095    }
3096    pub fn remove_clone_state(&mut self) {
3097        self.remove_s_var("CloneState");
3098    }
3099    pub fn remove_clone_states(&mut self) {
3100        self.remove_s_var("CloneState");
3101    }
3102    pub fn add_new_pt_by_text(&mut self, p: i32, t: i32) {
3103        self.base_power = Some(p);
3104        self.base_toughness = Some(t);
3105    }
3106    pub fn remove_new_p_tby_text(&mut self) {
3107        self.clear_new_pt();
3108    }
3109    pub fn add_new_pt(&mut self, p: i32, t: i32) {
3110        self.base_power = Some(p);
3111        self.base_toughness = Some(t);
3112    }
3113    pub fn remove_new_pt(&mut self) {
3114        self.clear_new_pt();
3115    }
3116    pub fn clear_new_pt(&mut self) {
3117        self.base_power = None;
3118        self.base_toughness = None;
3119    }
3120    pub fn toughness_assigns_damage(&self) -> bool {
3121        self.has_keyword("CARDNAME assigns combat damage equal to its toughness")
3122    }
3123    pub fn assign_no_combat_damage(&self) -> bool {
3124        self.has_keyword("CARDNAME assigns no combat damage")
3125    }
3126    pub fn add_pt_boost(&mut self, p: i32, t: i32) {
3127        self.power_modifier += p;
3128        self.toughness_modifier += t;
3129    }
3130    pub fn remove_pt_boost(&mut self, p: i32, t: i32) {
3131        self.power_modifier -= p;
3132        self.toughness_modifier -= t;
3133    }
3134    pub fn add_draft_action(&mut self) {
3135        self.set_s_var("DraftAction", "True");
3136    }
3137    pub fn add_intensity(&mut self, v: i32) {
3138        self.intensity += v;
3139    }
3140    pub fn has_intensity(&self) -> bool {
3141        self.intensity > 0
3142    }
3143    pub fn has_perpetual(&self) -> bool {
3144        !self.perpetual.is_empty()
3145    }
3146    pub fn get_perpetual(&self) -> &[PerpetualRecord] {
3147        &self.perpetual
3148    }
3149    pub fn add_perpetual(&mut self, p: PerpetualRecord) {
3150        self.apply_perpetual_record(p, true);
3151    }
3152    pub fn remove_perpetual(&mut self, timestamp: i64) -> bool {
3153        if let Some(idx) = self
3154            .perpetual
3155            .iter()
3156            .position(|p| p.timestamp() == timestamp)
3157        {
3158            self.perpetual.remove(idx);
3159            true
3160        } else {
3161            false
3162        }
3163    }
3164    pub fn set_perpetual(&mut self, old_card: &Card, apply_effects: bool) {
3165        self.perpetual = old_card.perpetual.clone();
3166        if apply_effects {
3167            for p in self.perpetual.clone() {
3168                self.apply_perpetual_record(p, false);
3169            }
3170        }
3171    }
3172    pub fn set_perpetual_from(&mut self, old_card: &Card) {
3173        self.set_perpetual(old_card, true);
3174    }
3175    pub fn apply_perpetual_record(&mut self, p: PerpetualRecord, remember: bool) {
3176        if remember {
3177            self.perpetual.push(p.clone());
3178        }
3179        p.apply_effect(self);
3180    }
3181    pub fn add_trigger_for_static_ability(&mut self, trig: Trigger) {
3182        self.add_trigger(trig);
3183    }
3184    pub fn visit_keywords(&self) -> Vec<String> {
3185        self.keywords.as_string_list()
3186    }
3187    pub fn update_keywords(&mut self) {
3188        self.update_keywords_cache();
3189    }
3190    pub fn add_changed_card_keywords(&mut self, kw: &str) {
3191        self.add_intrinsic_keyword(kw);
3192    }
3193    pub fn add_keyword_for_static_ability(&mut self, kw: &str) {
3194        self.granted_keywords.add(kw);
3195    }
3196    pub fn add_changed_card_keywords_by_text(&mut self, kw: &str) {
3197        self.add_intrinsic_keyword(kw);
3198    }
3199    pub fn add_changed_card_keywords_internal(&mut self, kw: &str) {
3200        self.add_intrinsic_keyword(kw);
3201    }
3202    pub fn remove_changed_card_keywords(&mut self, kw: &str) {
3203        self.remove_intrinsic_keyword(kw);
3204    }
3205    pub fn remove_changed_card_keywords_by_text(&mut self, kw: &str) {
3206        self.remove_intrinsic_keyword(kw);
3207    }
3208    pub fn clear_changed_card_keywords(&mut self) {
3209        self.keywords.clear();
3210    }
3211    pub fn clear_static_changed_card_keywords(&mut self) {
3212        self.granted_keywords.clear();
3213    }
3214    pub fn add_hidden_extrinsic_keywords(&mut self, kw: &str) {
3215        self.granted_keywords.add(kw);
3216    }
3217    pub fn remove_hidden_extrinsic_keywords(&mut self, kw: &str) {
3218        self.granted_keywords.remove(kw);
3219    }
3220    pub fn remove_hidden_extrinsic_keyword(&mut self, kw: &str) {
3221        self.granted_keywords.remove(kw);
3222    }
3223    pub fn has_start_of_keyword(&self, prefix: &str) -> bool {
3224        self.keywords.iter_strings().any(|k| k.starts_with(prefix))
3225    }
3226    pub fn has_start_of_un_hidden_keyword(&self, prefix: &str) -> bool {
3227        self.has_start_of_keyword(prefix)
3228    }
3229    pub fn has_any_keyword(&self) -> bool {
3230        !self.keywords.as_string_list().is_empty()
3231            || !self.granted_keywords.as_string_list().is_empty()
3232            || !self.pump_keywords.as_string_list().is_empty()
3233    }
3234    pub fn add_cant_have_keyword(&mut self, kw: &str) {
3235        self.cant_have_keywords.insert(kw.to_ascii_lowercase());
3236    }
3237    pub fn remove_cant_have_keyword(&mut self, kw: &str) {
3238        self.cant_have_keywords.remove(&kw.to_ascii_lowercase());
3239    }
3240    pub fn add_changed_text_color_word(&mut self, from: &str, to: &str) {
3241        self.set_s_var(format!("TextColor:{from}"), to);
3242    }
3243    pub fn remove_changed_text_color_word(&mut self, from: &str) {
3244        self.remove_s_var(&format!("TextColor:{from}"));
3245    }
3246    pub fn add_changed_text_type_word(&mut self, from: &str, to: &str) {
3247        self.set_s_var(format!("TextType:{from}"), to);
3248    }
3249    pub fn remove_changed_text_type_word(&mut self, from: &str) {
3250        self.remove_s_var(&format!("TextType:{from}"));
3251    }
3252    pub fn copy_changed_text_from(&mut self, other: &Card) {
3253        for (k, v) in &other.svars {
3254            if k.starts_with("TextColor:") || k.starts_with("TextType:") {
3255                self.svars.insert(k.clone(), v.clone());
3256            }
3257        }
3258    }
3259    pub fn has_playable_land_face(&self) -> bool {
3260        self.is_land()
3261            || self
3262                .other_part
3263                .as_ref()
3264                .map(|p| p.type_line.is_land())
3265                .unwrap_or(false)
3266    }
3267    pub fn phase(&mut self) {
3268        self.phased_out = !self.phased_out;
3269    }
3270    pub fn associated_with_color(&self, game: &GameState, color: &str) -> bool {
3271        let mut colors = HashSet::new();
3272        colors.insert(color.to_string());
3273        forge_foundation::Color::from_name(&color.to_ascii_lowercase())
3274            .map(|parsed| self.color.has_any_color(parsed.mask()))
3275            .unwrap_or(false)
3276            || self.can_produce_color_mana(game, &colors)
3277    }
3278    pub fn has_no_name(&self) -> bool {
3279        self.card_name.trim().is_empty()
3280    }
3281    pub fn shares_name_with(&self, other: &Card) -> bool {
3282        self.card_name.eq_ignore_ascii_case(&other.card_name)
3283    }
3284    pub fn has_creature_type(&self, creature_type: &str) -> bool {
3285        if !self.is_creature() && !self.type_line.core_types.contains(&CoreType::Kindred) {
3286            return false;
3287        }
3288        if self.type_line.has_subtype(creature_type) {
3289            return true;
3290        }
3291        self.has_keyword("Changeling") && crate::game::TypeRegistry::is_creature_type(creature_type)
3292    }
3293    pub fn has_subtype(&self, subtype: &str) -> bool {
3294        self.type_line.has_subtype(subtype) || self.has_creature_type(subtype)
3295    }
3296    pub fn shares_color_with(&self, other: &Card) -> bool {
3297        (self.color.has_white() && other.color.has_white())
3298            || (self.color.has_blue() && other.color.has_blue())
3299            || (self.color.has_black() && other.color.has_black())
3300            || (self.color.has_red() && other.color.has_red())
3301            || (self.color.has_green() && other.color.has_green())
3302            || (self.color.is_colorless() && other.color.is_colorless())
3303    }
3304    pub fn shares_cmc_with(&self, other: &Card) -> bool {
3305        self.mana_value() == other.mana_value()
3306    }
3307    pub fn shares_creature_type_with(&self, other: &Card) -> bool {
3308        crate::game::TypeRegistry::creature_types()
3309            .iter()
3310            .any(|creature_type| {
3311                self.has_creature_type(creature_type) && other.has_creature_type(creature_type)
3312            })
3313    }
3314    pub fn shares_land_type_with(&self, other: &Card) -> bool {
3315        self.shares_creature_type_with(other) && self.is_land() && other.is_land()
3316    }
3317    pub fn shares_permanent_type_with(&self, other: &Card) -> bool {
3318        (self.is_creature() && other.is_creature())
3319            || (self.is_land() && other.is_land())
3320            || (self.type_line.is_artifact() && other.type_line.is_artifact())
3321            || (self.type_line.is_enchantment() && other.type_line.is_enchantment())
3322            || (self.type_line.is_planeswalker() && other.type_line.is_planeswalker())
3323    }
3324    pub fn shares_card_type_with(&self, other: &Card) -> bool {
3325        self.shares_permanent_type_with(other)
3326    }
3327    pub fn shares_all_card_types_with(&self, other: &Card) -> bool {
3328        self.type_line.core_types == other.type_line.core_types
3329    }
3330    pub fn shares_controller_with(&self, other: &Card) -> bool {
3331        self.controller == other.controller
3332    }
3333    pub fn has_a_basic_land_type(&self) -> bool {
3334        self.type_line.has_subtype("Plains")
3335            || self.type_line.has_subtype("Island")
3336            || self.type_line.has_subtype("Swamp")
3337            || self.type_line.has_subtype("Mountain")
3338            || self.type_line.has_subtype("Forest")
3339    }
3340    pub fn has_a_non_basic_land_type(&self) -> bool {
3341        self.is_land() && !self.has_a_basic_land_type()
3342    }
3343    pub fn has_dealt_damage_to_opponent_this_turn(&self) -> bool {
3344        self.total_damage_done_this_turn > 0
3345    }
3346    pub fn has_been_dealt_deathtouch_damage(&self) -> bool {
3347        self.has_deathtouch_damage
3348    }
3349    pub fn has_been_dealt_excess_damage_this_turn(&self) -> bool {
3350        self.damage > self.toughness()
3351    }
3352    pub fn log_excess_damage(&mut self) {
3353        self.set_s_var("ExcessDamageLogged", "True");
3354    }
3355    pub fn add_assigned_damage(&mut self, amount: i32) {
3356        self.assigned_damage += amount;
3357    }
3358    pub fn clear_assigned_damage(&mut self) {
3359        self.assigned_damage = 0;
3360    }
3361    pub fn can_damage_prevented(&self) -> bool {
3362        !self.has_keyword("Damage can't be prevented")
3363    }
3364    pub fn static_replace_damage(&self, amount: i32) -> i32 {
3365        amount
3366    }
3367    pub fn add_damage_after_prevention(&mut self, amount: i32) -> i32 {
3368        let dealt = if self.can_be_dealt_damage() {
3369            amount.max(0)
3370        } else {
3371            0
3372        };
3373        if dealt <= 0 {
3374            return 0;
3375        }
3376        if self.type_line.is_planeswalker() {
3377            self.remove_counter(&CounterType::Loyalty, dealt);
3378        }
3379        if self.type_line.core_types.contains(&CoreType::Battle) {
3380            self.remove_counter(&CounterType::Named("DEFENSE".to_string()), dealt);
3381        }
3382        if self.is_creature() {
3383            self.damage += dealt;
3384        }
3385        dealt
3386    }
3387    pub fn border_color(&self) -> &'static str {
3388        if self.color.is_colorless() {
3389            "Colorless"
3390        } else if self.color.has_white() {
3391            "White"
3392        } else if self.color.has_blue() {
3393            "Blue"
3394        } else if self.color.has_black() {
3395            "Black"
3396        } else if self.color.has_red() {
3397            "Red"
3398        } else {
3399            "Green"
3400        }
3401    }
3402    pub fn was_discarded(&self) -> bool {
3403        self.discarded
3404    }
3405    pub fn was_surveilled(&self) -> bool {
3406        self.surveilled
3407    }
3408    pub fn was_milled(&self) -> bool {
3409        self.milled
3410    }
3411    pub fn clear_ring_bearer(&mut self) {
3412        self.remove_s_var("RingBearer");
3413    }
3414    pub fn add_saddled_by_this_turn(&mut self, card: CardId) {
3415        self.set_s_var("SaddledBy", format!("{}", card.0));
3416    }
3417    pub fn reset_saddled(&mut self) {
3418        self.remove_s_var("SaddledBy");
3419    }
3420    pub fn can_specialize(&self) -> bool {
3421        self.has_keyword("Specialize")
3422    }
3423    pub fn can_crew(&self) -> bool {
3424        self.is_permanent()
3425    }
3426    pub fn reset_times_crewed_this_turn(&mut self) {
3427        self.times_crewed_this_turn = 0;
3428    }
3429    pub fn becomes_crewed(&mut self) {
3430        self.is_crewed = true;
3431        self.times_crewed_this_turn += 1;
3432    }
3433    pub fn reset_crewed(&mut self) {
3434        self.is_crewed = false;
3435    }
3436    pub fn add_crewed_by_this_turn(&mut self, _card: CardId) {
3437        self.times_crewed_this_turn += 1;
3438    }
3439    pub fn visit_attraction(&mut self) {
3440        self.visited_this_turn = true;
3441    }
3442    pub fn was_visited_this_turn(&self) -> bool {
3443        self.visited_this_turn
3444    }
3445    pub fn animate_bestow(&mut self) {
3446        self.is_bestowed = false;
3447    }
3448    pub fn unanimate_bestow(&mut self) {
3449        self.is_bestowed = true;
3450    }
3451    pub fn equals_with_game_timestamp(&self, other: &Card) -> bool {
3452        self.id == other.id && self.zone_timestamp == other.zone_timestamp
3453    }
3454    pub fn update_world_timestamp(&mut self) {
3455        self.zone_timestamp = self.zone_timestamp.saturating_add(1);
3456    }
3457    pub fn can_be_discarded_by(&self, _player: PlayerId) -> bool {
3458        true
3459    }
3460    pub fn can_be_destroyed(&self) -> bool {
3461        !self.has_indestructible()
3462    }
3463    pub fn can_be_targeted_by(&self, _player: PlayerId) -> bool {
3464        true
3465    }
3466    pub fn cant_be_attached_msg(&self) -> Option<String> {
3467        None
3468    }
3469    pub fn can_be_sacrificed_by(&self, _player: PlayerId) -> bool {
3470        true
3471    }
3472    pub fn can_exiled_by(&self, _player: PlayerId) -> bool {
3473        true
3474    }
3475    pub fn update_static_abilities(&mut self) {
3476        self.recompute_changed_card_traits();
3477    }
3478    pub fn update_triggers(&mut self) {
3479        self.recompute_changed_card_traits();
3480    }
3481    pub fn update_replacement_effects(&mut self) {
3482        self.recompute_changed_card_traits();
3483    }
3484    pub fn was_cast(&self) -> bool {
3485        // Mirrors Java `Card.wasCast()`: true iff `castFrom` was set during
3486        // cast resolution. Sneak Attack and other "put onto battlefield"
3487        // effects don't go through the cast pipeline and leave this `None`.
3488        self.cast_from.is_some()
3489    }
3490    pub fn on_end_of_combat(&mut self) {
3491        self.assigned_damage = 0;
3492    }
3493    pub fn on_cleanup_phase(&mut self) {
3494        self.became_target_this_turn = false;
3495        self.visited_this_turn = false;
3496        self.damage_prevention = 0;
3497    }
3498    pub fn has_etb_trigger(&self) -> bool {
3499        self.triggers.iter().any(|t| {
3500            t.kind == crate::trigger::TriggerType::ChangesZone
3501                && t.destination_zone() == Some(ZoneType::Battlefield)
3502        })
3503    }
3504    pub fn has_etb_replacement(&self) -> bool {
3505        self.has_replacement_effect()
3506    }
3507    pub fn can_move_to_command_zone(&self) -> bool {
3508        self.is_commander && self.move_to_command_zone
3509    }
3510    pub fn from_paper_card(&mut self) {
3511        self.is_token = false;
3512    }
3513    pub fn cleanup_copied_changes_from(&mut self) {
3514        self.clear_changed_card_traits();
3515    }
3516    pub fn activated_this_turn(&self) -> bool {
3517        self.ability_activated_this_turn > 0
3518    }
3519    pub fn add_ability_activated(&mut self) {
3520        self.ability_activated_this_turn += 1;
3521    }
3522    pub fn add_ability_activated_for(
3523        &mut self,
3524        ability: Option<&crate::spellability::SpellAbility>,
3525    ) {
3526        self.add_ability_activated_for_with_limit_increase(ability, false);
3527    }
3528    pub fn add_ability_activated_for_with_limit_increase(
3529        &mut self,
3530        ability: Option<&crate::spellability::SpellAbility>,
3531        loyalty_limit_increase: bool,
3532    ) {
3533        if let Some(ability) = ability {
3534            self.number_turn_activations.add(ability);
3535            self.number_game_activations.add(ability);
3536            if ability.ir.pw_ability {
3537                self.add_planeswalker_ability_activated(loyalty_limit_increase);
3538            }
3539        }
3540        self.add_ability_activated();
3541    }
3542    pub fn add_ability_resolved(&mut self) {
3543        self.ability_resolved_this_turn += 1;
3544    }
3545    pub fn add_ability_resolved_for(
3546        &mut self,
3547        ability: Option<&crate::spellability::SpellAbility>,
3548    ) {
3549        if let Some(ability) = ability {
3550            self.number_ability_resolved.add(ability);
3551        }
3552        self.add_ability_resolved();
3553    }
3554    pub fn get_ability_activated_this_turn(
3555        &self,
3556        ability: Option<&crate::spellability::SpellAbility>,
3557    ) -> u32 {
3558        ability
3559            .map(|ability| self.number_turn_activations.get(ability) as u32)
3560            .unwrap_or(0)
3561    }
3562    pub fn get_ability_activated_this_game(
3563        &self,
3564        ability: Option<&crate::spellability::SpellAbility>,
3565    ) -> u32 {
3566        ability
3567            .map(|ability| self.number_game_activations.get(ability) as u32)
3568            .unwrap_or(0)
3569    }
3570    pub fn get_ability_resolved_this_turn(
3571        &self,
3572        ability: Option<&crate::spellability::SpellAbility>,
3573    ) -> u32 {
3574        ability
3575            .map(|ability| self.number_ability_resolved.get(ability) as u32)
3576            .unwrap_or(0)
3577    }
3578    pub fn get_ability_resolved_this_turn_activators(
3579        &self,
3580        ability: Option<&crate::spellability::SpellAbility>,
3581    ) -> Vec<crate::ids::PlayerId> {
3582        ability
3583            .map(|ability| self.number_ability_resolved.get_activators(ability))
3584            .unwrap_or_default()
3585    }
3586    pub fn reset_ability_resolved_this_turn(&mut self) {
3587        self.ability_resolved_this_turn = 0;
3588        self.number_ability_resolved.clear();
3589    }
3590    pub fn add_chosen_modes(&mut self, modes: Vec<usize>, turn: u32) {
3591        self.chosen_modes = Some(modes);
3592        self.chosen_modes_turn = Some(turn);
3593    }
3594    pub fn reset_chosen_mode_turn(&mut self) {
3595        self.chosen_modes_turn = None;
3596        self.chosen_modes = None;
3597    }
3598    pub fn add_planeswalker_ability_activated(&mut self, loyalty_limit_increase: bool) {
3599        self.planeswalker_abilities_activated += 1;
3600        if self.planeswalker_abilities_activated == 2 && loyalty_limit_increase {
3601            self.planeswalker_activation_limit_used = true;
3602        }
3603    }
3604    pub fn planeswalker_activation_limit_used(&self) -> bool {
3605        self.planeswalker_activation_limit_used
3606    }
3607    pub fn reset_activations_per_turn(&mut self) {
3608        self.ability_activated_this_turn = 0;
3609        self.number_turn_activations.clear();
3610        self.planeswalker_abilities_activated = 0;
3611        self.planeswalker_activation_limit_used = false;
3612    }
3613    pub fn add_can_block_additional(&mut self, n: i32) {
3614        self.can_block_additional += n;
3615    }
3616    pub fn remove_can_block_additional(&mut self, n: i32) {
3617        self.can_block_additional = (self.can_block_additional - n).max(0);
3618    }
3619    pub fn can_block_additional(&self) -> i32 {
3620        self.can_block_additional
3621    }
3622    pub fn add_can_block_any(&mut self) {
3623        self.can_block_any = true;
3624    }
3625    pub fn remove_can_block_any(&mut self) {
3626        self.can_block_any = false;
3627    }
3628    pub fn can_block_any(&self) -> bool {
3629        self.can_block_any
3630    }
3631    pub fn ignore_legend_rule(&self) -> bool {
3632        self.ignore_legend_rule_flag
3633    }
3634    pub fn attack_vigilance(&self) -> bool {
3635        self.has_vigilance()
3636    }
3637    pub fn unlock_room(&mut self) {
3638        self.set_s_var("RoomLocked", "False");
3639    }
3640    pub fn lock_room(&mut self) {
3641        self.set_s_var("RoomLocked", "True");
3642    }
3643    pub fn update_rooms(&mut self) {
3644        if !self.has_s_var("RoomLocked") {
3645            self.set_s_var("RoomLocked", "False");
3646        }
3647    }
3648
3649    /// Transform this double-faced card to its other face.
3650    /// Swaps all face-dependent characteristics with `other_part`.
3651    /// No-op if `other_part` is `None`.
3652    /// Mirrors Java's `CardUtil.applyState(card, CardStateName.Backside)`.
3653    /// Mirror of `Card.isModal()`: true only for MDFC (modal) cards, whose back
3654    /// face may be played from hand. Transform / meld backs are not modal.
3655    pub fn is_modal(&self) -> bool {
3656        self.other_part.as_ref().is_some_and(|other| other.is_modal)
3657    }
3658
3659    pub fn transform(&mut self) {
3660        if let Some(other) = self.other_part.as_mut() {
3661            std::mem::swap(&mut self.card_name, &mut other.name);
3662            std::mem::swap(&mut self.oracle_text, &mut other.oracle_text);
3663            std::mem::swap(&mut self.type_line, &mut other.type_line);
3664            std::mem::swap(&mut self.mana_cost, &mut other.mana_cost);
3665            std::mem::swap(&mut self.color, &mut other.color);
3666            std::mem::swap(&mut self.base_power, &mut other.base_power);
3667            std::mem::swap(&mut self.base_toughness, &mut other.base_toughness);
3668            std::mem::swap(&mut self.keywords, &mut other.keywords);
3669            std::mem::swap(&mut self.abilities, &mut other.abilities);
3670            std::mem::swap(&mut self.triggers, &mut other.triggers);
3671            std::mem::swap(&mut self.static_abilities, &mut other.static_abilities);
3672            std::mem::swap(
3673                &mut self.replacement_effects,
3674                &mut other.replacement_effects,
3675            );
3676            std::mem::swap(&mut self.svars, &mut other.svars);
3677
3678            // Reset per-face transient state
3679            self.power_modifier = 0;
3680            self.toughness_modifier = 0;
3681            self.damage = 0;
3682            self.granted_keywords.clear();
3683
3684            // Re-parse activated abilities from new face's abilities
3685            self.activated_abilities = self
3686                .abilities
3687                .iter()
3688                .enumerate()
3689                .filter_map(|(i, raw)| {
3690                    parse_or_warn(parse_activated_ability(raw, i), "ActivatedAbility", raw)
3691                })
3692                .collect();
3693            self.base_ability_count = self.activated_abilities.len();
3694            self.base_trigger_count = self.triggers.len();
3695            self.parsed_svar_cache.clear();
3696            self.refresh_action_specs();
3697
3698            // Re-bind replacement hosts so SVar lookups hit the active face.
3699            let mut res = std::mem::take(&mut self.replacement_effects);
3700            for re in &mut res {
3701                re.set_host_card(self);
3702            }
3703            self.replacement_effects = res;
3704
3705            self.is_transformed = !self.is_transformed;
3706
3707            // Face characteristics changed; reset trait-change baseline and
3708            // re-apply active trait-change layers against the new face.
3709            self.reset_changed_card_traits_baseline();
3710            self.recompute_changed_card_traits();
3711        }
3712    }
3713
3714    fn activated_to_spell_abilities(&self, list: &[ActivatedAbility]) -> Vec<SpellAbility> {
3715        list.iter()
3716            .map(|ab| {
3717                let mut sa = crate::spellability::build_spell_ability_from_host_card(
3718                    self,
3719                    &ab.ability_text,
3720                    self.controller,
3721                );
3722                sa.is_activated = true;
3723                sa
3724            })
3725            .collect()
3726    }
3727
3728    fn spell_to_activated_abilities(list: &[SpellAbility]) -> Vec<ActivatedAbility> {
3729        list.iter()
3730            .enumerate()
3731            .filter_map(|(i, sa)| parse_activated_ability(&sa.ability_text, i))
3732            .collect()
3733    }
3734
3735    fn capture_changed_card_traits_baseline_if_needed(&mut self) {
3736        if self.trait_base_activated_abilities.is_none() {
3737            self.trait_base_activated_abilities = Some(self.activated_abilities.clone());
3738            self.trait_base_triggers = Some(self.triggers.clone());
3739            self.trait_base_replacement_effects = Some(self.replacement_effects.clone());
3740            self.trait_base_static_abilities = Some(self.static_abilities.clone());
3741            self.trait_base_keywords = Some(self.keywords.clone());
3742        }
3743    }
3744
3745    fn reset_changed_card_traits_baseline(&mut self) {
3746        self.trait_base_activated_abilities = Some(self.activated_abilities.clone());
3747        self.trait_base_triggers = Some(self.triggers.clone());
3748        self.trait_base_replacement_effects = Some(self.replacement_effects.clone());
3749        self.trait_base_static_abilities = Some(self.static_abilities.clone());
3750        self.trait_base_keywords = Some(self.keywords.clone());
3751    }
3752
3753    pub(crate) fn reset_changed_card_traits_baseline_to_current(&mut self) {
3754        self.reset_changed_card_traits_baseline();
3755        self.recompute_changed_card_traits();
3756    }
3757
3758    fn recompute_changed_card_traits(&mut self) {
3759        let Some(base_activated) = self.trait_base_activated_abilities.clone() else {
3760            return;
3761        };
3762        let Some(base_triggers) = self.trait_base_triggers.clone() else {
3763            return;
3764        };
3765        let Some(base_replacements) = self.trait_base_replacement_effects.clone() else {
3766            return;
3767        };
3768        let Some(base_static) = self.trait_base_static_abilities.clone() else {
3769            return;
3770        };
3771        let Some(base_keywords) = self.trait_base_keywords.clone() else {
3772            return;
3773        };
3774
3775        let mut spell_abilities = self.activated_to_spell_abilities(&base_activated);
3776        let mut triggers = base_triggers;
3777        let mut replacements = base_replacements;
3778        let mut static_abilities = base_static;
3779        let mut keywords = base_keywords;
3780
3781        for layer in self.changed_card_traits_by_text.values() {
3782            spell_abilities = crate::card::card_state::apply_spell_ability(layer, spell_abilities);
3783            triggers = crate::card::card_state::apply_trigger(layer, triggers);
3784            replacements = crate::card::card_state::apply_replacement_effect(layer, replacements);
3785            static_abilities =
3786                crate::card::card_state::apply_static_ability(layer, static_abilities);
3787            keywords = crate::card::card_state::apply_keywords(layer, keywords);
3788        }
3789        for layer in self.changed_card_traits.values() {
3790            spell_abilities = crate::card::card_state::apply_spell_ability(layer, spell_abilities);
3791            triggers = crate::card::card_state::apply_trigger(layer, triggers);
3792            replacements = crate::card::card_state::apply_replacement_effect(layer, replacements);
3793            static_abilities =
3794                crate::card::card_state::apply_static_ability(layer, static_abilities);
3795            keywords = crate::card::card_state::apply_keywords(layer, keywords);
3796        }
3797
3798        self.activated_abilities = Self::spell_to_activated_abilities(&spell_abilities);
3799        self.triggers = triggers;
3800        self.replacement_effects = replacements;
3801        self.static_abilities = static_abilities;
3802        self.keywords = keywords;
3803    }
3804
3805    /// Java parity: `addChangedCardTraits`.
3806    pub fn add_changed_card_traits(
3807        &mut self,
3808        layer: card_trait_changes::CardTraitChanges,
3809        timestamp: i64,
3810        static_id: i64,
3811    ) {
3812        self.capture_changed_card_traits_baseline_if_needed();
3813        self.changed_card_traits
3814            .insert((timestamp, static_id), layer);
3815        self.recompute_changed_card_traits();
3816    }
3817
3818    /// Java parity: `addChangedCardTraitsByText`.
3819    pub fn add_changed_card_traits_by_text(
3820        &mut self,
3821        layer: card_trait_changes::CardTraitChanges,
3822        timestamp: i64,
3823        static_id: i64,
3824    ) {
3825        self.capture_changed_card_traits_baseline_if_needed();
3826        self.changed_card_traits_by_text
3827            .insert((timestamp, static_id), layer);
3828        self.recompute_changed_card_traits();
3829    }
3830
3831    /// Java parity: `removeChangedCardTraits`.
3832    pub fn remove_changed_card_traits(&mut self, timestamp: i64, static_id: i64) -> bool {
3833        if self
3834            .changed_card_traits
3835            .remove(&(timestamp, static_id))
3836            .is_none()
3837        {
3838            return false;
3839        }
3840        if self.changed_card_traits.is_empty() && self.changed_card_traits_by_text.is_empty() {
3841            if let Some(v) = self.trait_base_activated_abilities.take() {
3842                self.activated_abilities = v;
3843            }
3844            if let Some(v) = self.trait_base_triggers.take() {
3845                self.triggers = v;
3846            }
3847            if let Some(v) = self.trait_base_replacement_effects.take() {
3848                self.replacement_effects = v;
3849            }
3850            if let Some(v) = self.trait_base_static_abilities.take() {
3851                self.static_abilities = v;
3852            }
3853            if let Some(v) = self.trait_base_keywords.take() {
3854                self.keywords = v;
3855            }
3856            return true;
3857        }
3858
3859        self.recompute_changed_card_traits();
3860        true
3861    }
3862
3863    /// Java parity: `removeChangedCardTraitsByText`.
3864    pub fn remove_changed_card_traits_by_text(&mut self, timestamp: i64, static_id: i64) -> bool {
3865        if self
3866            .changed_card_traits_by_text
3867            .remove(&(timestamp, static_id))
3868            .is_none()
3869        {
3870            return false;
3871        }
3872        if self.changed_card_traits.is_empty() && self.changed_card_traits_by_text.is_empty() {
3873            if let Some(v) = self.trait_base_activated_abilities.take() {
3874                self.activated_abilities = v;
3875            }
3876            if let Some(v) = self.trait_base_triggers.take() {
3877                self.triggers = v;
3878            }
3879            if let Some(v) = self.trait_base_replacement_effects.take() {
3880                self.replacement_effects = v;
3881            }
3882            if let Some(v) = self.trait_base_static_abilities.take() {
3883                self.static_abilities = v;
3884            }
3885            if let Some(v) = self.trait_base_keywords.take() {
3886                self.keywords = v;
3887            }
3888            return true;
3889        }
3890
3891        self.recompute_changed_card_traits();
3892        true
3893    }
3894
3895    /// Java parity: `clearChangedCardTraits`.
3896    pub fn clear_changed_card_traits(&mut self) {
3897        self.changed_card_traits.clear();
3898        self.changed_card_traits_by_text.clear();
3899        if let Some(v) = self.trait_base_activated_abilities.take() {
3900            self.activated_abilities = v;
3901        }
3902        if let Some(v) = self.trait_base_triggers.take() {
3903            self.triggers = v;
3904        }
3905        if let Some(v) = self.trait_base_replacement_effects.take() {
3906            self.replacement_effects = v;
3907        }
3908        if let Some(v) = self.trait_base_static_abilities.take() {
3909            self.static_abilities = v;
3910        }
3911        if let Some(v) = self.trait_base_keywords.take() {
3912            self.keywords = v;
3913        }
3914    }
3915
3916    /// Clear continuous static-ability trait changes from the previous layer pass.
3917    ///
3918    /// Static layer effects use negative static IDs so they can be recomputed
3919    /// each pass without disturbing perpetual/card-state trait changes.
3920    pub fn clear_static_layer_changed_card_traits(&mut self) {
3921        let before = self.changed_card_traits.len();
3922        self.changed_card_traits
3923            .retain(|(_, static_id), _| *static_id >= 0);
3924        if self.changed_card_traits.len() == before {
3925            return;
3926        }
3927        if self.changed_card_traits.is_empty() && self.changed_card_traits_by_text.is_empty() {
3928            if let Some(v) = self.trait_base_activated_abilities.take() {
3929                self.activated_abilities = v;
3930            }
3931            if let Some(v) = self.trait_base_triggers.take() {
3932                self.triggers = v;
3933            }
3934            if let Some(v) = self.trait_base_replacement_effects.take() {
3935                self.replacement_effects = v;
3936            }
3937            if let Some(v) = self.trait_base_static_abilities.take() {
3938                self.static_abilities = v;
3939            }
3940            if let Some(v) = self.trait_base_keywords.take() {
3941                self.keywords = v;
3942            }
3943            return;
3944        }
3945
3946        self.recompute_changed_card_traits();
3947    }
3948
3949    pub fn remove_changed_state(&mut self) {
3950        self.clear_changed_card_traits();
3951    }
3952}
3953
3954impl HasSVars for Card {
3955    fn get_svar(&self, name: &str) -> Option<&str> {
3956        self.get_s_var(name)
3957    }
3958
3959    fn set_svar(&mut self, name: String, value: String) {
3960        self.set_s_var(name, value);
3961    }
3962
3963    fn set_svars(&mut self, new_svars: std::collections::HashMap<String, String>) {
3964        self.set_svars_map(new_svars.into_iter().collect());
3965    }
3966
3967    fn get_svars(&self) -> &std::collections::HashMap<String, String> {
3968        panic!("Card::get_svars is not supported yet; use get_s_var/has_s_var parity accessors");
3969    }
3970
3971    fn remove_svar(&mut self, var: &str) {
3972        self.remove_s_var(var);
3973    }
3974}
3975
3976#[cfg(test)]
3977mod tests {
3978    use super::*;
3979    use std::collections::HashSet;
3980
3981    use forge_carddb::parse_card_script;
3982    use forge_foundation::ManaCost;
3983
3984    #[test]
3985    fn card_power_toughness() {
3986        let mut card = Card::new(
3987            CardId(0),
3988            "Test".to_string(),
3989            PlayerId(0),
3990            CardTypeLine::parse("Creature Bear"),
3991            ManaCost::parse("1 G"),
3992            ColorSet::GREEN,
3993            Some(2),
3994            Some(2),
3995            vec![],
3996            vec![],
3997        );
3998        assert_eq!(card.power(), 2);
3999        assert_eq!(card.toughness(), 2);
4000
4001        card.add_counter(&CounterType::P1P1, 1);
4002        assert_eq!(card.power(), 3);
4003        assert_eq!(card.toughness(), 3);
4004    }
4005
4006    #[test]
4007    fn can_attack() {
4008        let mut card = Card::new(
4009            CardId(0),
4010            "Test".to_string(),
4011            PlayerId(0),
4012            CardTypeLine::parse("Creature Bear"),
4013            ManaCost::parse("1 G"),
4014            ColorSet::GREEN,
4015            Some(2),
4016            Some(2),
4017            vec![],
4018            vec![],
4019        );
4020        card.zone = ZoneType::Battlefield;
4021        assert!(!card.can_attack()); // summoning sick
4022
4023        card.summoning_sick = false;
4024        assert!(card.can_attack());
4025
4026        card.tapped = true;
4027        assert!(!card.can_attack()); // tapped
4028    }
4029
4030    #[test]
4031    fn haste_bypasses_summoning_sickness() {
4032        let mut card = Card::new(
4033            CardId(0),
4034            "Test".to_string(),
4035            PlayerId(0),
4036            CardTypeLine::parse("Creature Bear"),
4037            ManaCost::parse("1 G"),
4038            ColorSet::GREEN,
4039            Some(2),
4040            Some(2),
4041            vec!["Haste".to_string()],
4042            vec![],
4043        );
4044        card.zone = ZoneType::Battlefield;
4045        assert!(card.can_attack()); // haste means no summoning sickness check
4046    }
4047
4048    #[test]
4049    fn keyword_helpers() {
4050        let card = Card::new(
4051            CardId(0),
4052            "Test".to_string(),
4053            PlayerId(0),
4054            CardTypeLine::parse("Creature Bear"),
4055            ManaCost::parse("1 G"),
4056            ColorSet::GREEN,
4057            Some(2),
4058            Some(2),
4059            vec![
4060                "Hexproof".to_string(),
4061                "Menace".to_string(),
4062                "Indestructible".to_string(),
4063            ],
4064            vec![],
4065        );
4066        assert!(card.has_hexproof());
4067        assert!(card.has_menace());
4068        assert!(card.has_indestructible());
4069        assert!(!card.has_shroud());
4070        assert!(!card.has_fear());
4071        assert!(!card.has_shadow());
4072    }
4073
4074    #[test]
4075    fn protection_from_color() {
4076        let knight = Card::new(
4077            CardId(0),
4078            "White Knight".to_string(),
4079            PlayerId(0),
4080            CardTypeLine::parse("Creature Knight"),
4081            ManaCost::parse("W W"),
4082            ColorSet::WHITE,
4083            Some(2),
4084            Some(2),
4085            vec!["Protection from black".to_string()],
4086            vec![],
4087        );
4088        let black_source = Card::new(
4089            CardId(1),
4090            "Doom Blade".to_string(),
4091            PlayerId(1),
4092            CardTypeLine::parse("Instant"),
4093            ManaCost::parse("1 B"),
4094            ColorSet::BLACK,
4095            None,
4096            None,
4097            vec![],
4098            vec![],
4099        );
4100        let green_source = Card::new(
4101            CardId(2),
4102            "Giant Growth".to_string(),
4103            PlayerId(1),
4104            CardTypeLine::parse("Instant"),
4105            ManaCost::parse("G"),
4106            ColorSet::GREEN,
4107            None,
4108            None,
4109            vec![],
4110            vec![],
4111        );
4112        assert!(knight.is_protected_from(&black_source));
4113        assert!(!knight.is_protected_from(&green_source));
4114        assert!(knight.has_protection_from("black"));
4115        assert!(!knight.has_protection_from("red"));
4116    }
4117
4118    #[test]
4119    fn ward_and_toxic_parsing() {
4120        let ward_card = Card::new(
4121            CardId(0),
4122            "Ward Bear".to_string(),
4123            PlayerId(0),
4124            CardTypeLine::parse("Creature Bear"),
4125            ManaCost::parse("1 U"),
4126            ColorSet::BLUE,
4127            Some(2),
4128            Some(2),
4129            vec!["Ward:2".to_string()],
4130            vec![],
4131        );
4132        assert_eq!(ward_card.get_ward_cost(), Some("2".to_string()));
4133
4134        let toxic_card = Card::new(
4135            CardId(1),
4136            "Toxic Elf".to_string(),
4137            PlayerId(0),
4138            CardTypeLine::parse("Creature Elf"),
4139            ManaCost::parse("G"),
4140            ColorSet::GREEN,
4141            Some(1),
4142            Some(1),
4143            vec!["Toxic:1".to_string()],
4144            vec![],
4145        );
4146        assert_eq!(toxic_card.get_toxic_count(), Some(1));
4147
4148        // No ward/toxic
4149        let plain = Card::new(
4150            CardId(2),
4151            "Bear".to_string(),
4152            PlayerId(0),
4153            CardTypeLine::parse("Creature Bear"),
4154            ManaCost::parse("1 G"),
4155            ColorSet::GREEN,
4156            Some(2),
4157            Some(2),
4158            vec![],
4159            vec![],
4160        );
4161        assert_eq!(plain.get_ward_cost(), None);
4162        assert_eq!(plain.get_toxic_count(), None);
4163    }
4164
4165    #[test]
4166    fn from_rules_copies_attraction_lights() {
4167        let rules = parse_card_script(
4168            "Name:Balloon Stand\nTypes:Artifact Attraction\nLights: 2 4 6\nOracle:Test.",
4169        )
4170        .expect("card script should parse");
4171        let card = Card::from_rules(&rules, PlayerId(0));
4172        assert_eq!(card.attraction_lights, vec![2, 4, 6]);
4173        assert!(card.has_attraction_light(4));
4174        assert!(!card.has_attraction_light(3));
4175    }
4176
4177    #[test]
4178    fn can_produce_color_mana_uses_mana_abilities_and_reflection() {
4179        let mut game = GameState::new(&["Alice", "Bob"], 20);
4180        let p0 = PlayerId(0);
4181
4182        let white_land = Card::new(
4183            CardId(0),
4184            "White Source".to_string(),
4185            p0,
4186            CardTypeLine::parse("Land"),
4187            ManaCost::parse(""),
4188            ColorSet::COLORLESS,
4189            None,
4190            None,
4191            vec![],
4192            vec!["AB$ Mana | Cost$ T | Produced$ W | SpellDescription$ Add {W}.".to_string()],
4193        );
4194        let reflecting_pool = Card::new(
4195            CardId(1),
4196            "Reflecting Pool".to_string(),
4197            p0,
4198            CardTypeLine::parse("Land"),
4199            ManaCost::parse(""),
4200            ColorSet::COLORLESS,
4201            None,
4202            None,
4203            vec![],
4204            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()],
4205        );
4206
4207        let white_id = game.create_card(white_land);
4208        let pool_id = game.create_card(reflecting_pool);
4209        game.move_card(white_id, ZoneType::Battlefield, p0);
4210        game.move_card(pool_id, ZoneType::Battlefield, p0);
4211
4212        let mut white = HashSet::new();
4213        white.insert("white".to_string());
4214        assert!(game.card(white_id).can_produce_color_mana(&game, &white));
4215        assert!(game.card(pool_id).can_produce_color_mana(&game, &white));
4216    }
4217
4218    #[test]
4219    fn can_produce_same_mana_type_with_uses_mana_ability_overlap() {
4220        let mut game = GameState::new(&["Alice", "Bob"], 20);
4221        let p0 = PlayerId(0);
4222
4223        let island = Card::new(
4224            CardId(0),
4225            "Island Source".to_string(),
4226            p0,
4227            CardTypeLine::parse("Land"),
4228            ManaCost::parse(""),
4229            ColorSet::COLORLESS,
4230            None,
4231            None,
4232            vec![],
4233            vec!["AB$ Mana | Cost$ T | Produced$ U | SpellDescription$ Add {U}.".to_string()],
4234        );
4235        let prism = Card::new(
4236            CardId(1),
4237            "Prism".to_string(),
4238            p0,
4239            CardTypeLine::parse("Artifact"),
4240            ManaCost::parse("2"),
4241            ColorSet::COLORLESS,
4242            None,
4243            None,
4244            vec![],
4245            vec!["AB$ Mana | Cost$ T | Produced$ U | SpellDescription$ Add {U}.".to_string()],
4246        );
4247
4248        let island_id = game.create_card(island);
4249        let prism_id = game.create_card(prism);
4250        game.move_card(island_id, ZoneType::Battlefield, p0);
4251        game.move_card(prism_id, ZoneType::Battlefield, p0);
4252
4253        assert!(game
4254            .card(prism_id)
4255            .can_produce_same_mana_type_with(&game, game.card(island_id)));
4256    }
4257}