Skip to main content

manabrew_engine/event/
mod.rs

1use forge_foundation::{PhaseType, ZoneType};
2use serde::{Deserialize, Serialize};
3use std::collections::{BTreeMap, HashMap};
4
5use crate::ability::AbilityKey;
6use crate::agent::GameEntity;
7use crate::card::card_damage_map::CardDamageMap;
8use crate::card::card_zone_table::CardZoneTable;
9use crate::ids::{CardId, PlayerId};
10use strum_macros::Display;
11
12// `TriggerType` was moved to `crate::trigger::trigger_type`. Nothing in this
13// module references it directly — callers must use `crate::trigger::TriggerType`.
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct ZoneChangeRecord {
17    pub origin: ZoneType,
18    pub destination: ZoneType,
19    pub card: CardId,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct CounterTableEntry {
24    pub source: Option<PlayerId>,
25    pub object_card: Option<CardId>,
26    pub object_player: Option<PlayerId>,
27    pub counters: BTreeMap<String, i32>,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize, Display)]
31#[allow(clippy::large_enum_variant)]
32pub enum AbilityValue {
33    Card(CardId),
34    Player(PlayerId),
35    Cards(Vec<CardId>),
36    Players(Vec<PlayerId>),
37    GameEntities(Vec<GameEntity>),
38    VoteMap(Vec<(String, Vec<PlayerId>)>),
39    SpellAbility(crate::spellability::SpellAbility),
40    CardZoneTable(CardZoneTable),
41    DamageMap(CardDamageMap),
42    CounterMap(BTreeMap<String, i32>),
43    String(String),
44    Int(i32),
45    Bool(bool),
46    Zone(ZoneType),
47    Phase(PhaseType),
48}
49
50impl Default for AbilityValue {
51    fn default() -> Self {
52        AbilityValue::String(String::new())
53    }
54}
55
56impl AbilityValue {
57    pub fn as_str(&self) -> &str {
58        match self {
59            AbilityValue::String(value) => value.as_str(),
60            _ => "",
61        }
62    }
63}
64
65impl std::ops::Deref for AbilityValue {
66    type Target = str;
67
68    fn deref(&self) -> &Self::Target {
69        self.as_str()
70    }
71}
72
73impl From<CardId> for AbilityValue {
74    fn from(value: CardId) -> Self {
75        AbilityValue::Card(value)
76    }
77}
78
79impl From<PlayerId> for AbilityValue {
80    fn from(value: PlayerId) -> Self {
81        AbilityValue::Player(value)
82    }
83}
84
85impl From<Vec<CardId>> for AbilityValue {
86    fn from(value: Vec<CardId>) -> Self {
87        AbilityValue::Cards(value)
88    }
89}
90
91impl From<Vec<PlayerId>> for AbilityValue {
92    fn from(value: Vec<PlayerId>) -> Self {
93        AbilityValue::Players(value)
94    }
95}
96
97impl From<Vec<(String, Vec<PlayerId>)>> for AbilityValue {
98    fn from(value: Vec<(String, Vec<PlayerId>)>) -> Self {
99        AbilityValue::VoteMap(value)
100    }
101}
102
103impl From<crate::spellability::SpellAbility> for AbilityValue {
104    fn from(value: crate::spellability::SpellAbility) -> Self {
105        AbilityValue::SpellAbility(value)
106    }
107}
108
109impl From<CardZoneTable> for AbilityValue {
110    fn from(value: CardZoneTable) -> Self {
111        AbilityValue::CardZoneTable(value)
112    }
113}
114
115impl From<CardDamageMap> for AbilityValue {
116    fn from(value: CardDamageMap) -> Self {
117        AbilityValue::DamageMap(value)
118    }
119}
120
121impl From<BTreeMap<String, i32>> for AbilityValue {
122    fn from(value: BTreeMap<String, i32>) -> Self {
123        AbilityValue::CounterMap(value)
124    }
125}
126
127impl From<String> for AbilityValue {
128    fn from(value: String) -> Self {
129        AbilityValue::String(value)
130    }
131}
132
133impl From<&str> for AbilityValue {
134    fn from(value: &str) -> Self {
135        AbilityValue::String(value.to_string())
136    }
137}
138
139impl From<&String> for AbilityValue {
140    fn from(value: &String) -> Self {
141        AbilityValue::String(value.clone())
142    }
143}
144
145impl From<i32> for AbilityValue {
146    fn from(value: i32) -> Self {
147        AbilityValue::Int(value)
148    }
149}
150
151impl From<bool> for AbilityValue {
152    fn from(value: bool) -> Self {
153        AbilityValue::Bool(value)
154    }
155}
156
157impl From<ZoneType> for AbilityValue {
158    fn from(value: ZoneType) -> Self {
159        AbilityValue::Zone(value)
160    }
161}
162
163impl From<PhaseType> for AbilityValue {
164    fn from(value: PhaseType) -> Self {
165        AbilityValue::Phase(value)
166    }
167}
168
169/// Typed event parameter keys — mirrors Java AbilityKey enum.
170/// In Java this is Map<AbilityKey, Object>. In Rust we use a struct
171/// because Rust has no Object type (justified deviation).
172#[derive(Debug, Clone, Default, Serialize, Deserialize)]
173pub struct RunParams {
174    pub card: Option<CardId>,
175    pub card_lki: Option<CardId>,
176    /// Additional card collection payload used by many Java triggers (AbilityKey.Cards).
177    pub cards: Option<Vec<CardId>>,
178    /// Batched zone-change payload used by Java's CardZoneTable triggers.
179    pub zone_changes: Option<Vec<ZoneChangeRecord>>,
180    /// Java-style `CardZoneTable` object payload for batch zone-change triggers.
181    pub change_zone_table: Option<CardZoneTable>,
182    pub origin: Option<ZoneType>,
183    pub destination: Option<ZoneType>,
184    /// CSV destination payload used by TriggerAbilityTriggered for batch triggers.
185    pub destinations: Option<String>,
186    /// Java AbilityKey.Activator.
187    pub activator: Option<PlayerId>,
188    pub cause_player: Option<PlayerId>,
189    pub player: Option<PlayerId>,
190    pub phase: Option<PhaseType>,
191    pub damage_source: Option<CardId>,
192    pub damage_target_player: Option<PlayerId>,
193    pub damage_target_card: Option<CardId>,
194    /// Java AbilityKey.Target payload split by target type.
195    pub target_player: Option<PlayerId>,
196    pub target_card: Option<CardId>,
197    pub damage_amount: Option<i32>,
198    pub is_combat_damage: Option<bool>,
199    /// Java AbilityKey.FirstTime marker.
200    pub first_time: Option<bool>,
201    /// Java AbilityKey.Fizzle marker.
202    pub fizzle: Option<bool>,
203    /// Java AbilityKey.Valiant marker.
204    pub valiant: Option<bool>,
205    pub attacker: Option<CardId>,
206    /// Java AbilityKey.Attacked split by entity type.
207    pub attacked_player: Option<PlayerId>,
208    pub attacked_card: Option<CardId>,
209    /// Java AbilityKey.OtherAttackers.
210    pub other_attacker_ids: Option<Vec<CardId>>,
211    /// Java AbilityKey.Defenders split by entity type.
212    pub defenders_player_ids: Option<Vec<PlayerId>>,
213    pub defenders_card_ids: Option<Vec<CardId>>,
214    /// Java AbilityKey.AttackingPlayer.
215    pub attacking_player: Option<PlayerId>,
216    pub defending_player: Option<PlayerId>,
217    pub spell_card: Option<CardId>,
218    pub spell_controller: Option<PlayerId>,
219    /// Second card involved (e.g. second creature in a Fight trigger).
220    pub card2: Option<CardId>,
221    /// Java AbilityKey.Explored.
222    pub explored: Option<CardId>,
223    /// SpellAbility that was countered
224    pub spell_ability: Option<crate::spellability::SpellAbility>,
225    /// Java AbilityKey.SourceSA.
226    pub source_sa: Option<crate::spellability::SpellAbility>,
227    /// Java AbilityKey.AbilityMana.
228    pub ability_mana: Option<crate::spellability::SpellAbility>,
229    /// Cause of the event (e.g. counterspell)
230    pub cause: Option<crate::spellability::SpellAbility>,
231    /// Java AbilityKey.Causer payload.
232    pub causer: Option<CardId>,
233    /// Java AbilityKey.Produced.
234    pub produced: Option<String>,
235    /// Java AbilityKey.Mode.
236    pub mode: Option<String>,
237    /// Java AbilityKey.Num.
238    pub num: Option<i32>,
239    /// Java AbilityKey.Number.
240    pub number: Option<i32>,
241    // ── New fields (issue #19) ──
242    /// Blocking creature (for Blocks trigger).
243    pub blocker: Option<CardId>,
244    /// Attacker being blocked (for Blocks trigger).
245    pub blocked_attacker: Option<CardId>,
246    /// Life amount gained or lost (for LifeGained/LifeLost triggers).
247    pub life_amount: Option<i32>,
248    /// Counter type name (for CounterAdded/CounterRemoved triggers).
249    pub counter_type: Option<String>,
250    /// Number of counters added/removed.
251    pub counter_amount: Option<i32>,
252    pub new_counter_amount: Option<i32>,
253    // ── New fields (issue #54) ──
254    /// Batch of attacker IDs (for AttackersDeclared).
255    pub attacker_ids: Option<Vec<CardId>>,
256    /// Batch of blocker IDs (for BlockersDeclared).
257    pub blocker_ids: Option<Vec<CardId>>,
258    /// Original controller before a control change.
259    pub original_controller: Option<PlayerId>,
260    /// Cumulative mana expend amount (for ManaExpend trigger).
261    pub mana_expend_amount: Option<i32>,
262    /// Enlisted card (for TriggerType::Enlisted).
263    pub enlisted: Option<CardId>,
264    /// The spell/ability card that caused the event (for BecomesTarget — the targeting spell).
265    pub cause_card: Option<CardId>,
266    /// Coin-flip outcome (true = win/heads).
267    pub coin_flip_won: Option<bool>,
268    /// Rolled die result (modified).
269    pub die_result: Option<i32>,
270    /// Batch of rolled die results (for RolledDieOnce aggregate triggers).
271    pub die_results: Option<Vec<i32>>,
272    /// Rolled die natural result before modifiers.
273    pub natural_result: Option<i32>,
274    /// Number of sides on the rolled die.
275    pub die_sides: Option<i32>,
276    /// Number of attackers declared this combat (for Exalted `Alone$ True` check).
277    pub num_attackers: Option<usize>,
278    /// The creature that was exploited (for Exploited trigger).
279    pub exploited_card: Option<CardId>,
280    /// LKI +1/+1 counter count on a card that just left the battlefield.
281    /// Used by Modular triggers to know how many counters to move.
282    pub lki_p1p1_counters: Option<i32>,
283    /// LKI power on a card that just left the battlefield.
284    /// Used for TriggeredCard$CardPower without depending on mutable card state.
285    pub lki_power: Option<i32>,
286    /// LKI toughness on a card that just left the battlefield.
287    /// Used for TriggeredCard$CardToughness without depending on mutable card state.
288    pub lki_toughness: Option<i32>,
289    /// Whether cumulative upkeep was paid (for PayCumulativeUpkeep trigger).
290    pub cumulative_upkeep_paid: Option<bool>,
291    /// Whether echo was paid (for PayEcho trigger).
292    pub echo_paid: Option<bool>,
293    /// Gained class level value.
294    pub class_level: Option<i32>,
295    /// Room name payload for room-enter triggers.
296    pub room_name: Option<String>,
297    /// Cards that crewed/saddled another card.
298    pub crew_cards: Option<Vec<CardId>>,
299    /// Championed card payload.
300    pub championed_card: Option<CardId>,
301    /// Generic source card payload for triggers like Mentored.
302    pub source_card: Option<CardId>,
303    /// Generic source player payload for triggers like CounterPlayerAddedAll.
304    pub source_player: Option<PlayerId>,
305    /// Generic object card payload for triggers like CounterTypeAddedAll.
306    pub object_card: Option<CardId>,
307    /// Generic object player payload for triggers like CounterTypeAddedAll.
308    pub object_player: Option<PlayerId>,
309    /// Counter type -> amount map payload.
310    pub counter_map: Option<BTreeMap<String, i32>>,
311    pub counter_table: Option<Vec<CounterTableEntry>>,
312    /// Java AbilityKey.DamageMap.
313    pub damage_map: Option<CardDamageMap>,
314    /// Clash outcome.
315    pub clash_won: Option<bool>,
316    /// Card state name payload (for door/room state specific checks).
317    pub card_state_name: Option<String>,
318    /// Snapshot of drawn_this_turn at the time a Drawn event fires.
319    /// Used by `Number$ N` triggers to compare against the exact draw count
320    /// at fire time (not at deferred match time).
321    pub drawn_this_turn_snapshot: Option<i32>,
322    /// Players for whom this was the first relevant event this turn.
323    pub first_time_players: Option<Vec<PlayerId>>,
324    /// Java AbilityKey.AllVotes.
325    pub all_votes: Option<Vec<(String, Vec<PlayerId>)>>,
326    /// Java AbilityKey.DiscardedBefore.
327    pub discarded_before: Option<Vec<CardId>>,
328    /// Java AbilityKey.RolledToVisitAttractions.
329    pub rolled_to_visit_attractions: Option<bool>,
330}
331
332impl RunParams {
333    pub fn add_common_trigger_objects(&self, sa: &mut crate::spellability::SpellAbility) {
334        if let Some(card_id) = self.card {
335            sa.set_triggering_object(crate::ability::AbilityKey::Card, card_id.0.to_string());
336            sa.set_triggering_object(crate::ability::AbilityKey::NewCard, card_id.0.to_string());
337        }
338        if let Some(card_id) = self.card_lki {
339            sa.set_triggering_object(crate::ability::AbilityKey::CardLKI, card_id.0.to_string());
340        }
341        if let Some(player_id) = self.activator.or(self.cause_player) {
342            sa.set_triggering_object(
343                crate::ability::AbilityKey::Activator,
344                player_id.0.to_string(),
345            );
346        }
347        if let Some(player_id) = self.player {
348            sa.set_triggering_object(crate::ability::AbilityKey::Player, player_id.0.to_string());
349        }
350        if let Some(player_id) = self.attacking_player {
351            sa.set_triggering_object(
352                crate::ability::AbilityKey::AttackingPlayer,
353                player_id.0.to_string(),
354            );
355        }
356        if let Some(player_id) = self.defending_player {
357            sa.set_triggering_object(
358                crate::ability::AbilityKey::DefendingPlayer,
359                player_id.0.to_string(),
360            );
361        }
362        if let Some(card_id) = self.causer.or(self.cause_card) {
363            sa.set_triggering_object(crate::ability::AbilityKey::Causer, card_id.0.to_string());
364        }
365        if let Some(card_id) = self.source_card.or(self.spell_card) {
366            sa.set_triggering_object(crate::ability::AbilityKey::Source, card_id.0.to_string());
367        }
368        if let Some(card_id) = self.attacker {
369            sa.set_triggering_object(crate::ability::AbilityKey::Attacker, card_id.0.to_string());
370        }
371        if let Some(card_id) = self.blocker {
372            sa.set_triggering_object(crate::ability::AbilityKey::Blocker, card_id.0.to_string());
373        }
374        if let Some(card_id) = self.attacked_card {
375            sa.set_triggering_object(crate::ability::AbilityKey::Attacked, card_id.0.to_string());
376        }
377        if let Some(player_id) = self.attacked_player {
378            sa.set_triggering_object(
379                crate::ability::AbilityKey::AttackedTarget,
380                player_id.0.to_string(),
381            );
382        }
383        if let Some(card_id) = self.target_card {
384            let value = card_id.0.to_string();
385            sa.set_triggering_object(crate::ability::AbilityKey::Target, &value);
386            sa.set_triggering_object(crate::ability::AbilityKey::TargetCard, &value);
387        }
388        if let Some(player_id) = self.target_player {
389            let value = player_id.0.to_string();
390            sa.set_triggering_object(crate::ability::AbilityKey::Target, &value);
391            sa.set_triggering_object(crate::ability::AbilityKey::TargetPlayer, &value);
392        }
393        if self.target_player.is_none() {
394            if let Some(player_id) = self.damage_target_player {
395                let value = player_id.0.to_string();
396                sa.set_triggering_object(crate::ability::AbilityKey::Target, &value);
397                sa.set_triggering_object(crate::ability::AbilityKey::TargetPlayer, &value);
398            }
399        }
400        if self.target_card.is_none() {
401            if let Some(card_id) = self.damage_target_card {
402                let value = card_id.0.to_string();
403                sa.set_triggering_object(crate::ability::AbilityKey::Target, &value);
404                sa.set_triggering_object(crate::ability::AbilityKey::TargetCard, &value);
405            }
406        }
407        if let Some(card_id) = self.explored {
408            sa.set_triggering_object(crate::ability::AbilityKey::Explored, card_id.0.to_string());
409        }
410        if let Some(cards) = self.cards.as_deref() {
411            let csv = cards
412                .iter()
413                .map(|card_id| card_id.0.to_string())
414                .collect::<Vec<_>>()
415                .join(",");
416            if !csv.is_empty() {
417                sa.set_triggering_object(crate::ability::AbilityKey::Cards, &csv);
418            }
419        }
420        if let Some(cards) = self.attacker_ids.as_deref() {
421            let csv = cards
422                .iter()
423                .map(|card_id| card_id.0.to_string())
424                .collect::<Vec<_>>()
425                .join(",");
426            if !csv.is_empty() {
427                sa.set_triggering_object(crate::ability::AbilityKey::Attackers, &csv);
428            }
429        }
430        if let Some(value) = self.life_amount {
431            sa.set_triggering_object(crate::ability::AbilityKey::LifeAmount, value.to_string());
432        }
433        if let Some(value) = self.natural_result {
434            sa.set_triggering_object(crate::ability::AbilityKey::NaturalResult, value.to_string());
435        }
436        if let Some(value) = self.card_state_name.as_deref() {
437            sa.set_triggering_object(crate::ability::AbilityKey::CardState, value);
438        }
439        if let Some(value) = self.room_name.as_deref() {
440            sa.set_triggering_object(crate::ability::AbilityKey::RoomName, value);
441        }
442        if let Some(value) = self.spell_ability.as_ref() {
443            sa.set_triggering_spell_ability("SpellAbility", value.clone());
444        }
445        if let Some(value) = self.source_sa.as_ref() {
446            sa.set_triggering_spell_ability("SourceSA", value.clone());
447        }
448        if let Some(value) = self.ability_mana.as_ref() {
449            sa.set_triggering_spell_ability("AbilityMana", value.clone());
450        }
451        if let Some(value) = self.cause.as_ref() {
452            sa.set_triggering_spell_ability("Cause", value.clone());
453        }
454        if let Some(results) = self.die_results.as_deref() {
455            let csv = results
456                .iter()
457                .map(i32::to_string)
458                .collect::<Vec<_>>()
459                .join(",");
460            if !csv.is_empty() {
461                sa.set_triggering_object(crate::ability::AbilityKey::Result, &csv);
462            }
463        } else if let Some(value) = self.die_result {
464            sa.set_triggering_object(crate::ability::AbilityKey::Result, value.to_string());
465        }
466        if let Some(value) = self.die_sides {
467            sa.set_triggering_object(crate::ability::AbilityKey::Sides, value.to_string());
468        }
469        if let Some(value) = self.number {
470            sa.set_triggering_object(crate::ability::AbilityKey::Number, value.to_string());
471        }
472    }
473
474    pub fn get_value(&self, key: AbilityKey) -> Option<AbilityValue> {
475        use AbilityKey::*;
476        match key {
477            AbilityMana => self.ability_mana.clone().map(AbilityValue::SpellAbility),
478            AllVotes => self.all_votes.clone().map(AbilityValue::VoteMap),
479            Activator => self
480                .activator
481                .or(self.cause_player)
482                .map(AbilityValue::Player),
483            Amount => self
484                .cards
485                .as_ref()
486                .map(|cards| AbilityValue::Int(cards.len() as i32))
487                .or_else(|| self.counter_amount.map(AbilityValue::Int))
488                .or_else(|| self.damage_amount.map(AbilityValue::Int))
489                .or_else(|| self.life_amount.map(AbilityValue::Int)),
490            Attacked => self
491                .attacked_card
492                .map(AbilityValue::Card)
493                .or_else(|| self.attacked_player.map(AbilityValue::Player)),
494            Attacker => self.attacker.map(AbilityValue::Card),
495            Attackers => self.attacker_ids.clone().map(AbilityValue::Cards),
496            AttackingPlayer => self
497                .attacking_player
498                .or(self.spell_controller)
499                .map(AbilityValue::Player),
500            Blocker => self.blocker.map(AbilityValue::Card),
501            Blockers => self.blocker_ids.clone().map(AbilityValue::Cards),
502            Card => self.card.map(AbilityValue::Card),
503            CardState => self.card_state_name.clone().map(AbilityValue::String),
504            Cards => self
505                .change_zone_table
506                .clone()
507                .map(AbilityValue::CardZoneTable)
508                .or_else(|| self.cards.clone().map(AbilityValue::Cards)),
509            CardLKI => self.card_lki.map(AbilityValue::Card),
510            Causer => self
511                .causer
512                .map(AbilityValue::Card)
513                .or_else(|| self.cause_card.map(AbilityValue::Card))
514                .or_else(|| {
515                    self.cause
516                        .as_ref()
517                        .and_then(|sa| sa.source)
518                        .map(AbilityValue::Card)
519                }),
520            Cause => self
521                .cause
522                .clone()
523                .map(AbilityValue::SpellAbility)
524                .or_else(|| self.cause_card.map(AbilityValue::Card))
525                .or_else(|| self.cards.clone().map(AbilityValue::Cards)),
526            Championed => self.championed_card.map(AbilityValue::Card),
527            ClassLevel => self.class_level.map(AbilityValue::Int),
528            CounterAmount | CounterNum | NewCounterAmount => {
529                self.counter_amount.map(AbilityValue::Int)
530            }
531            CounterMap => self.counter_map.clone().map(AbilityValue::CounterMap),
532            CounterType => self.counter_type.clone().map(AbilityValue::String),
533            Crew => self.crew_cards.clone().map(AbilityValue::Cards),
534            CumulativeUpkeepPaid => self.cumulative_upkeep_paid.map(AbilityValue::Bool),
535            DamageAmount | LifeGained | LifeAmount | Num | Number | PreventedAmount => self
536                .damage_amount
537                .or(self.life_amount)
538                .or(self.num)
539                .or(self.number)
540                .or(self.drawn_this_turn_snapshot)
541                .map(AbilityValue::Int),
542            DamageMap => self.damage_map.clone().map(AbilityValue::DamageMap),
543            DamageSource => self.damage_source.map(AbilityValue::Card),
544            DamageTarget | Target => self
545                .damage_target_card
546                .map(AbilityValue::Card)
547                .or_else(|| self.damage_target_player.map(AbilityValue::Player))
548                .or_else(|| self.target_card.map(AbilityValue::Card))
549                .or_else(|| self.target_player.map(AbilityValue::Player)),
550            Defenders => self
551                .defenders_card_ids
552                .clone()
553                .map(AbilityValue::Cards)
554                .or_else(|| self.defenders_player_ids.clone().map(AbilityValue::Players)),
555            DefendingPlayer => self.defending_player.map(AbilityValue::Player),
556            Destination => self
557                .destinations
558                .clone()
559                .map(AbilityValue::String)
560                .or_else(|| self.destination.map(AbilityValue::Zone)),
561            EchoPaid => self.echo_paid.map(AbilityValue::Bool),
562            Enlisted => self.enlisted.map(AbilityValue::Card),
563            Exploited => self.exploited_card.map(AbilityValue::Card),
564            Explored => self.explored.map(AbilityValue::Card),
565            Explorer => self.card.map(AbilityValue::Card),
566            FirstTime => self
567                .first_time_players
568                .clone()
569                .map(AbilityValue::Players)
570                .or_else(|| self.first_time.map(AbilityValue::Bool)),
571            Fizzle => self.fizzle.map(AbilityValue::Bool),
572            IsCombat | IsCombatDamage => self.is_combat_damage.map(AbilityValue::Bool),
573            LastStateBattlefield => self
574                .change_zone_table
575                .as_ref()
576                .map(|table| AbilityValue::Cards(table.last_state_battlefield().to_vec())),
577            LastStateGraveyard => self
578                .change_zone_table
579                .as_ref()
580                .map(|table| AbilityValue::Cards(table.last_state_graveyard().to_vec())),
581            Mana | Produced => self.produced.clone().map(AbilityValue::String),
582            Mode => self.mode.clone().map(AbilityValue::String),
583            NewCard => self.card2.map(AbilityValue::Card),
584            Object => self
585                .object_card
586                .map(AbilityValue::Card)
587                .or_else(|| self.object_player.map(AbilityValue::Player))
588                .or_else(|| self.card.map(AbilityValue::Card)),
589            OtherAttackers => self.other_attacker_ids.clone().map(AbilityValue::Cards),
590            Origin => self.origin.map(AbilityValue::Zone),
591            OriginalController => self.original_controller.map(AbilityValue::Player),
592            Phase => self.phase.map(AbilityValue::Phase),
593            Player => self.player.map(AbilityValue::Player),
594            Result | Won => self
595                .coin_flip_won
596                .map(AbilityValue::Bool)
597                .or_else(|| self.clash_won.map(AbilityValue::Bool))
598                .or_else(|| self.mode.clone().map(AbilityValue::String))
599                .or_else(|| self.die_result.map(AbilityValue::Int)),
600            NaturalResult => self.natural_result.map(AbilityValue::Int),
601            RoomName => self.room_name.clone().map(AbilityValue::String),
602            RolledToVisitAttractions => self.rolled_to_visit_attractions.map(AbilityValue::Bool),
603            Scheme => self.card.map(AbilityValue::Card),
604            Sides => self.die_sides.map(AbilityValue::Int),
605            Source => self
606                .source_card
607                .map(AbilityValue::Card)
608                .or_else(|| self.source_player.map(AbilityValue::Player))
609                .or_else(|| self.spell_card.map(AbilityValue::Card)),
610            SourceSA | SpellAbility | StackSa => self
611                .source_sa
612                .clone()
613                .or_else(|| self.spell_ability.clone())
614                .map(AbilityValue::SpellAbility),
615            Valiant => self.valiant.map(AbilityValue::Bool),
616            InternalTriggerTable => self
617                .change_zone_table
618                .clone()
619                .map(AbilityValue::CardZoneTable),
620            _ => None,
621        }
622    }
623
624    pub fn as_ability_map(&self) -> HashMap<AbilityKey, AbilityValue> {
625        crate::ability::ability_key::all_ability_keys()
626            .iter()
627            .filter_map(|key| self.get_value(*key).map(|value| (*key, value)))
628            .collect()
629    }
630
631    /// Java-parity alias for `Map<AbilityKey, Object>.get(...)`.
632    pub fn get(&self, key: AbilityKey) -> Option<AbilityValue> {
633        self.get_value(key)
634    }
635
636    /// Get a card ID from run-params by AbilityKey.
637    /// Provides a generic accessor so code can use `AbilityKey` enum values
638    /// to pull data from the typed struct.
639    pub fn get_card(&self, key: crate::ability::AbilityKey) -> Option<CardId> {
640        match self.get_value(key) {
641            Some(AbilityValue::Card(card)) => Some(card),
642            _ => None,
643        }
644    }
645
646    /// Get a player ID from run-params by AbilityKey.
647    pub fn get_player(&self, key: crate::ability::AbilityKey) -> Option<PlayerId> {
648        match self.get_value(key) {
649            Some(AbilityValue::Player(player)) => Some(player),
650            _ => None,
651        }
652    }
653
654    /// Get an integer amount from run-params by AbilityKey.
655    pub fn get_amount(&self, key: crate::ability::AbilityKey) -> Option<i32> {
656        match self.get_value(key) {
657            Some(AbilityValue::Int(value)) => Some(value),
658            _ => None,
659        }
660    }
661
662    /// Get a bool marker by AbilityKey.
663    pub fn get_bool(&self, key: crate::ability::AbilityKey) -> Option<bool> {
664        use crate::ability::AbilityKey;
665        match key {
666            AbilityKey::IsCombatDamage => self.is_combat_damage,
667            AbilityKey::FirstTime => self.first_time,
668            AbilityKey::Valiant => self.valiant,
669            _ => None,
670        }
671    }
672
673    /// Get a SpellAbility by AbilityKey.
674    pub fn get_spell_ability(
675        &self,
676        key: crate::ability::AbilityKey,
677    ) -> Option<&crate::spellability::SpellAbility> {
678        use crate::ability::AbilityKey;
679        match key {
680            AbilityKey::SpellAbility => self.spell_ability.as_ref(),
681            AbilityKey::SourceSA => self.source_sa.as_ref(),
682            AbilityKey::AbilityMana => self.ability_mana.as_ref(),
683            AbilityKey::Cause => self.cause.as_ref(),
684            _ => None,
685        }
686    }
687
688    /// Get a card list by AbilityKey.
689    pub fn get_cards(&self, key: crate::ability::AbilityKey) -> Option<&[CardId]> {
690        use crate::ability::AbilityKey;
691        match key {
692            AbilityKey::Cards => self.cards.as_deref(),
693            AbilityKey::DamageTargets => self.cards.as_deref(),
694            AbilityKey::Attackers => self.attacker_ids.as_deref(),
695            AbilityKey::Blockers => self.blocker_ids.as_deref(),
696            AbilityKey::OtherAttackers => self.other_attacker_ids.as_deref(),
697            AbilityKey::Defenders => self.defenders_card_ids.as_deref(),
698            _ => None,
699        }
700    }
701
702    /// Get a string payload by AbilityKey.
703    pub fn get_string(&self, key: crate::ability::AbilityKey) -> Option<&str> {
704        use crate::ability::AbilityKey;
705        match key {
706            AbilityKey::Produced => self.produced.as_deref(),
707            AbilityKey::Mode => self.mode.as_deref(),
708            _ => None,
709        }
710    }
711}