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