Skip to main content

manabrew_engine/
action.rs

1use forge_foundation::ZoneType;
2
3use crate::agent::PlayerAgent;
4use crate::card::{Card, CounterType};
5use crate::event::RunParams;
6use crate::game::GameState;
7use crate::ids::{CardId, PlayerId};
8use crate::replacement::replacement_handler::{
9    apply_replacements, apply_replacements_with_agents, ReplacementEvent, ReplacementRuntime,
10};
11use crate::replacement::GameLossReason;
12use crate::replacement::ReplacementResult;
13use crate::staticability::layer::{apply_continuous_effects, apply_etb_tapped_with_agents};
14use crate::trigger::handler::TriggerHandler;
15use crate::trigger::TriggerType;
16
17/// Game state mutation methods — moving cards, dealing damage, state-based actions.
18impl GameState {
19    pub fn record_player_damage_assignment(
20        &mut self,
21        source: Option<CardId>,
22        target_player: Option<PlayerId>,
23        amount: i32,
24        is_combat: bool,
25    ) {
26        self.player_record_damage_assignment(source, target_player, amount, is_combat);
27    }
28
29    /// Move a card from its current zone to a new zone.
30    /// Move a card to a new zone. For Graveyard destinations, checks for zone-redirect
31    /// replacement effects (Rest in Peace, Leyline of the Void) and redirects to the
32    /// correct zone. Use `move_card_final` to skip the replacement check.
33    pub fn move_card(&mut self, card_id: CardId, dest_zone: ZoneType, dest_owner: PlayerId) {
34        self.move_card_internal(card_id, dest_zone, dest_owner, None, None, true, false);
35    }
36
37    pub fn move_card_with_agents(
38        &mut self,
39        card_id: CardId,
40        dest_zone: ZoneType,
41        dest_owner: PlayerId,
42        agents: &mut [Box<dyn PlayerAgent>],
43    ) {
44        self.move_card_internal(
45            card_id,
46            dest_zone,
47            dest_owner,
48            Some(agents),
49            None,
50            true,
51            false,
52        );
53    }
54
55    pub fn move_card_with_agents_and_replacement_runtime(
56        &mut self,
57        card_id: CardId,
58        dest_zone: ZoneType,
59        dest_owner: PlayerId,
60        agents: &mut [Box<dyn PlayerAgent>],
61        runtime: &mut ReplacementRuntime<'_>,
62    ) {
63        self.move_card_internal(
64            card_id,
65            dest_zone,
66            dest_owner,
67            Some(agents),
68            Some(runtime.trigger_handler),
69            true,
70            false,
71        );
72    }
73
74    fn move_card_without_replacement(
75        &mut self,
76        card_id: CardId,
77        dest_zone: ZoneType,
78        dest_owner: PlayerId,
79    ) {
80        self.move_card_internal(card_id, dest_zone, dest_owner, None, None, false, false);
81    }
82
83    /// Discard a card. Mirrors Java's `Player.discard()`.
84    ///
85    /// Records the discard, marks the card, and moves it to graveyard through
86    /// the normal zone-change machinery (which runs replacement effects like
87    /// Madness automatically). Fires Discarded triggers afterwards.
88    pub fn discard_card(
89        &mut self,
90        card_id: CardId,
91        discard_player: PlayerId,
92        sa: Option<&crate::spellability::SpellAbility>,
93        agents: Option<&mut [Box<dyn PlayerAgent>]>,
94        trigger_handler: &mut TriggerHandler,
95    ) {
96        let owner = self.card(card_id).owner;
97        self.player_record_discard(discard_player, 1);
98        self.card_mut(card_id).set_discarded(true);
99
100        // Move to graveyard through normal zone-change with is_discard=true.
101        // Replacement effects (e.g. Madness → Exile) are handled generically.
102        self.move_card_internal(
103            card_id,
104            ZoneType::Graveyard,
105            owner,
106            agents,
107            Some(trigger_handler),
108            true,
109            true, // is_discard
110        );
111
112        // RememberDiscarded
113        if let Some(sa) = sa {
114            if sa.ir.remember_discarded {
115                if let Some(source_id) = sa.source {
116                    self.card_mut(source_id).add_remembered_card(card_id);
117                }
118            }
119        }
120
121        // Register active triggers on the card in its new zone.
122        trigger_handler.register_active_trigger(self, card_id);
123
124        // Emit zone-change trigger for Hand → actual destination.
125        let dest_zone = self.card(card_id).zone;
126        crate::ability::effects::zone_triggers::emit_zone_trigger(
127            trigger_handler,
128            card_id,
129            ZoneType::Hand,
130            dest_zone,
131        );
132
133        // Fire Discarded trigger.
134        trigger_handler.run_trigger(
135            TriggerType::Discarded,
136            RunParams {
137                card: Some(card_id),
138                player: Some(discard_player),
139                ..Default::default()
140            },
141            false,
142        );
143        trigger_handler.run_trigger(
144            TriggerType::DiscardedAll,
145            RunParams {
146                card: Some(card_id),
147                cards: Some(vec![card_id]),
148                player: Some(discard_player),
149                ..Default::default()
150            },
151            false,
152        );
153    }
154
155    fn move_card_internal(
156        &mut self,
157        card_id: CardId,
158        dest_zone: ZoneType,
159        dest_owner: PlayerId,
160        mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
161        mut trigger_handler: Option<&mut TriggerHandler>,
162        apply_move_replacement: bool,
163        is_discard: bool,
164    ) {
165        let (src_zone, src_owner, was_permanent, was_land, is_token) = {
166            let card = &self.cards[card_id.index()];
167            (
168                card.zone,
169                card.controller,
170                card.type_line.is_permanent(),
171                card.is_land(),
172                card.is_token,
173            )
174        };
175        if let Ok(filter) = std::env::var("FORGE_CARD_TRACE") {
176            if !filter.is_empty()
177                && self.cards[card_id.index()]
178                    .card_name
179                    .eq_ignore_ascii_case(&filter)
180            {
181                eprintln!(
182                    "[card-trace] move {} {:?} {:?} -> {:?} (owner={:?} sick={} cast_from={:?})",
183                    self.cards[card_id.index()].card_name,
184                    card_id,
185                    src_zone,
186                    dest_zone,
187                    dest_owner,
188                    self.cards[card_id.index()].summoning_sick,
189                    self.cards[card_id.index()].cast_from,
190                );
191            }
192        }
193        if dest_zone == ZoneType::Battlefield
194            && src_zone != ZoneType::Battlefield
195            && self.card(card_id).is_room()
196            && self.card(card_id).cast_sa.is_none()
197        {
198            self.card_mut(card_id)
199                .set_room_state(forge_foundation::CardStateName::EmptyRoom);
200        }
201        let mut etb_counters = std::collections::BTreeMap::new();
202        if dest_zone == ZoneType::Battlefield {
203            for keyword in self.cards[card_id.index()].keywords.as_string_list() {
204                let mut parts = keyword.split(':');
205                if !parts
206                    .next()
207                    .is_some_and(|head| head.eq_ignore_ascii_case("etbCounter"))
208                {
209                    continue;
210                }
211                let counter_type =
212                    crate::ability::effects::parse_counter_type(parts.next().unwrap_or_default());
213                let amount_text = parts.next().unwrap_or_default();
214                let amount = amount_text.parse::<i32>().unwrap_or_else(|_| {
215                    let card = &self.cards[card_id.index()];
216                    card.svars
217                        .get(amount_text)
218                        .map(|expression| {
219                            if matches!(expression.as_str(), "Count$xPaid" | "Count$XPaid") {
220                                card.svars
221                                    .get("XPaid")
222                                    .and_then(|value| value.parse().ok())
223                                    .unwrap_or(0)
224                            } else {
225                                expression.parse().unwrap_or_else(|_| {
226                                    crate::svar::resolve_count_svar(
227                                        expression, self, card_id, dest_owner,
228                                    )
229                                })
230                            }
231                        })
232                        .unwrap_or(0)
233                });
234                *etb_counters.entry(counter_type).or_default() += amount.max(0);
235            }
236            let card = &self.cards[card_id.index()];
237            if card.type_line.has_subtype("Saga") && card.has_chapter() {
238                let amount = if card.has_keyword("Read ahead") {
239                    agents
240                        .as_deref_mut()
241                        .and_then(|agents| {
242                            agents[dest_owner.index()].choose_number(
243                                dest_owner,
244                                Some(card_id),
245                                "How many lore counters?",
246                                Some("Choose a chapter and start with that many lore counters."),
247                                1,
248                                card.get_final_chapter_nr(),
249                            )
250                        })
251                        .unwrap_or(1)
252                        .clamp(1, card.get_final_chapter_nr())
253                } else {
254                    1
255                };
256                *etb_counters.entry(CounterType::Lore).or_default() += amount;
257            }
258            if card.type_line.is_planeswalker() {
259                let loyalty = card
260                    .initial_loyalty
261                    .as_deref()
262                    .and_then(|value| value.parse::<i32>().ok())
263                    .unwrap_or(0);
264                *etb_counters
265                    .entry(crate::card::CounterType::Loyalty)
266                    .or_default() += loyalty.max(0);
267            }
268            *etb_counters
269                .entry(crate::card::CounterType::P1P1)
270                .or_default() += card.etb_counters_p1p1.max(0);
271            let sunburst = card.sunburst_count();
272            if sunburst > 0 && card.has_keyword("Sunburst") {
273                let counter_type = if card.is_creature() {
274                    crate::card::CounterType::P1P1
275                } else {
276                    crate::card::CounterType::Charge
277                };
278                *etb_counters.entry(counter_type).or_default() += sunburst;
279            }
280            etb_counters.retain(|_, amount| *amount > 0);
281        }
282        let counter_cause = self.cards[card_id.index()].cast_sa.clone();
283        let counter_map = (!etb_counters.is_empty()).then(|| {
284            vec![crate::replacement::replacement_handler::CounterMapValue {
285                source: Some(dest_owner),
286                counters: etb_counters,
287            }]
288        });
289        let mut moved_event = ReplacementEvent::Moved {
290            card: card_id,
291            origin: src_zone,
292            destination: dest_zone,
293            is_discard,
294            counter_map,
295            counter_cause,
296            counter_is_effect: dest_zone == ZoneType::Battlefield,
297            after_replacement_static_abilities: Vec::new(),
298        };
299        let tapped_before_replacement = self.card(card_id).tapped;
300        if apply_move_replacement {
301            if let Some(agents) = agents.as_deref_mut() {
302                apply_replacements_with_agents(self, agents, &mut moved_event);
303            } else {
304                apply_replacements(self, &mut moved_event);
305            }
306        }
307        let (dest_zone, etb_counter_map, counter_cause, after_replacement_static_abilities) =
308            match moved_event {
309                ReplacementEvent::Moved {
310                    destination,
311                    counter_map,
312                    counter_cause,
313                    after_replacement_static_abilities,
314                    ..
315                } => (
316                    destination,
317                    counter_map,
318                    counter_cause,
319                    after_replacement_static_abilities,
320                ),
321                _ => (dest_zone, None, None, Vec::new()),
322            };
323        let adventure_exile = src_zone == ZoneType::Stack
324            && dest_zone == ZoneType::Exile
325            && self.card(card_id).on_adventure;
326        let replacement_marked_etb_tapped = dest_zone == ZoneType::Battlefield
327            && self.card(card_id).tapped
328            && !tapped_before_replacement;
329        let dest_owner = if dest_zone == ZoneType::Command {
330            self.card(card_id).owner
331        } else {
332            dest_owner
333        };
334        let host_left_battlefield =
335            src_zone == ZoneType::Battlefield && dest_zone != ZoneType::Battlefield;
336        if host_left_battlefield && was_permanent {
337            self.player_record_permanent_left_battlefield(src_owner);
338        }
339        if host_left_battlefield {
340            if self.card(card_id).is_room() {
341                self.update_lki_snapshot(card_id);
342            }
343            // `ControlGain$ LoseControl$ LeavesPlay` — drop the scheduled
344            // revert since the card is no longer on the battlefield.
345            crate::ability::effects::control_gain_effect::leaves_play_hook(self, card_id);
346        }
347        if src_zone != dest_zone
348            && (host_left_battlefield
349                || !matches!(dest_zone, ZoneType::Stack | ZoneType::Battlefield))
350        {
351            self.card_mut(card_id).cast_sa = None;
352        }
353        if dest_zone == ZoneType::Graveyard && was_permanent && !is_token {
354            self.player_record_permanent_put_into_graveyard(self.card(card_id).owner);
355        }
356        let forget_effects: Vec<CardId> = self
357            .cards
358            .iter()
359            .filter(|c| {
360                c.zone == ZoneType::Command
361                    && c.forget_on_moved_origin == Some(src_zone)
362                    && c.remembered_cards.contains(&card_id)
363            })
364            .map(|c| c.id)
365            .collect();
366
367        // Tokens and copy-tokens cease to exist when leaving the battlefield (CR 110.5g).
368        // Set zone to None (limbo) and remove from source zone without adding to destination.
369        if (is_token && dest_zone != ZoneType::Battlefield)
370            || (self.card(card_id).copied_spell
371                && !matches!(dest_zone, ZoneType::Stack | ZoneType::Battlefield))
372        {
373            if let Some(table) = self.pending_change_zone_table.as_mut() {
374                table.put(Some(src_zone), Some(ZoneType::None), card_id);
375            }
376            let mut exile_effects = Vec::new();
377            for eff_id in forget_effects.iter().copied() {
378                let eff = &mut self.cards[eff_id.index()];
379                eff.remembered_cards.retain(|&rid| rid != card_id);
380                if eff.exile_when_no_remembered && eff.remembered_cards.is_empty() {
381                    exile_effects.push(eff_id);
382                }
383            }
384            self.expire_until_lose_control_keyword_changes(card_id);
385            self.cards[card_id.index()].clear_changed_card_keyword_layers();
386            self.cards[card_id.index()].zone = ZoneType::None;
387            if src_zone != ZoneType::None {
388                self.remove_card_from_zone(src_zone, src_owner, card_id);
389            }
390            // Effect cards with ForgetOnMoved should be removed from the game
391            // entirely (zone = None), not moved to Exile. Moving them to Exile
392            // creates phantom cards that diverge from Java parity.
393            for eff_id in exile_effects {
394                let controller = self.card(eff_id).controller;
395                self.remove_card_from_zone(ZoneType::Command, controller, eff_id);
396                self.cards[eff_id.index()].zone = ZoneType::None;
397            }
398            apply_continuous_effects(self);
399            debug_assert!(self.card_zone_location_matches_card(card_id));
400            return;
401        }
402
403        // Remove from source zone
404        if src_zone != ZoneType::None {
405            self.remove_card_from_zone(src_zone, src_owner, card_id);
406        }
407
408        if src_zone == ZoneType::Exile && dest_zone != ZoneType::Exile {
409            self.cards[card_id.index()]
410                .keywords
411                .retain(|kw| !kw.starts_with(crate::card::KEYWORD_PLOTTED_PREFIX));
412        }
413
414        // Update card's zone
415        self.cards[card_id.index()].zone = dest_zone;
416        if src_zone != dest_zone {
417            self.cards[card_id.index()].turn_in_zone = self.turn.turn_number;
418        }
419        if src_zone != dest_zone && self.card(card_id).room_faces.is_some() {
420            self.card_mut(card_id).unlocked_doors.clear();
421            if dest_zone != ZoneType::Battlefield || self.card(card_id).cast_sa.is_none() {
422                self.card_mut(card_id).update_rooms();
423            }
424        }
425
426        if let Some(table) = self.pending_change_zone_table.as_mut() {
427            table.put(Some(src_zone), Some(dest_zone), card_id);
428        }
429
430        // Assign a zone timestamp so same-player triggers are ordered by
431        // zone entry order (matching Java's Zone.cardList insertion order).
432        if dest_zone != ZoneType::Stack {
433            self.assign_zone_timestamp(card_id);
434        }
435
436        // Track LKI: record which zone this card came from on the destination zone.
437        self.save_zone_lki(dest_zone, dest_owner, card_id, src_zone);
438        if src_zone != dest_zone {
439            self.card_mut(card_id).set_solved(false);
440            if !(src_zone == ZoneType::Stack && dest_zone == ZoneType::Battlefield) {
441                self.expire_until_lose_control_keyword_changes(card_id);
442                let card = self.card_mut(card_id);
443                card.clear_changed_card_keyword_layers();
444            }
445        }
446
447        // Reset state on zone change
448        match dest_zone {
449            ZoneType::Battlefield => {
450                // A permanent enters under the destination player's control.
451                // This must be updated before ETB-trigger registration so
452                // triggered abilities inherit the correct controller.
453                if self.cards[card_id.index()].controller != dest_owner {
454                    self.expire_until_lose_control_keyword_changes(card_id);
455                }
456                self.cards[card_id.index()].set_controller(dest_owner);
457                self.cards[card_id.index()].enter_battlefield();
458                if replacement_marked_etb_tapped {
459                    self.cards[card_id.index()].set_tapped(true);
460                }
461                // Add to destination zone first so the card is "on the
462                // battlefield" when ETB-tapped checks run against it.
463                self.add_card_to_zone(dest_zone, dest_owner, card_id);
464                if src_zone != ZoneType::Battlefield && self.card(card_id).is_room() {
465                    let cast_door = self.card(card_id).cast_sa.as_ref().map(|sa| {
466                        (
467                            sa.activating_player,
468                            sa.ir
469                                .card_state_name
470                                .as_deref()
471                                .and_then(forge_foundation::CardStateName::from_str_compat)
472                                .unwrap_or(forge_foundation::CardStateName::LeftSplit),
473                        )
474                    });
475                    if let Some((player, door)) = cast_door {
476                        if let Some(handler) = trigger_handler.as_deref_mut() {
477                            crate::ability::effects::unlock_door_effect::unlock_room(
478                                self, handler, card_id, player, door,
479                            );
480                        } else {
481                            self.card_mut(card_id).unlock_room(door);
482                        }
483                    }
484                }
485                if was_land {
486                    self.player_record_landfall(dest_owner);
487                }
488                // Apply ETB-tapped effects (intrinsic + extrinsic). When the
489                // replacement chain already tapped this card it also already
490                // prompted the affected player to choose the applied effect,
491                // so neither the prompt nor the apply pass should fire again
492                // here — Java's flow runs the choose-and-apply step exactly
493                // once via the replacement chain.
494                if !replacement_marked_etb_tapped {
495                    apply_etb_tapped_with_agents(self, card_id, agents);
496                }
497                if let Some(handler) = trigger_handler.as_deref_mut() {
498                    handler.register_active_trigger(self, card_id);
499                }
500                if let Some(counter_map) = etb_counter_map {
501                    let table =
502                        crate::game_entity_counter_table::GameEntityCounterTable::from_counter_map(
503                            crate::agent::GameEntity::Card(card_id),
504                            counter_map,
505                        );
506                    table.apply_replaced_counter_effect(
507                        self,
508                        trigger_handler.as_deref_mut(),
509                        counter_cause.as_deref(),
510                        RunParams::default(),
511                    );
512                    for (source, static_abilities) in after_replacement_static_abilities {
513                        crate::replacement::replace_add_counter::apply_after_replacement_static_abilities(
514                            self,
515                            source,
516                            static_abilities,
517                        );
518                    }
519                }
520                self.cards[card_id.index()].etb_counters_p1p1 = 0;
521                // Update LKI snapshot: card just entered the battlefield.
522                // Ensures it's available for later TriggeredCard$CardPower lookups
523                // even if it dies within the same resolution chain.
524                self.update_lki_snapshot(card_id);
525                apply_continuous_effects(self);
526                debug_assert!(self.card_zone_location_matches_card(card_id));
527                return;
528            }
529            ZoneType::Graveyard | ZoneType::Hand | ZoneType::Exile | ZoneType::Library => {
530                // Detach any attachments before resetting state.
531                let attachments: Vec<CardId> = self.cards[card_id.index()].attachments.clone();
532                for aura_id in attachments {
533                    self.cards[aura_id.index()].attached_to = None;
534                    // Bestow: when host leaves, revert aura to creature
535                    self.cards[aura_id.index()].is_bestowed = false;
536                }
537                self.cards[card_id.index()].attachments.clear();
538                // Also detach this card from its host if it was an Aura/Equipment.
539                self.detach(card_id);
540
541                // Save last-known information before resetting.
542                // Mirrors Java's LKI system for trigger SVars like TriggeredCard$CardPower.
543                if src_zone == ZoneType::Battlefield {
544                    let card = &self.cards[card_id.index()];
545                    let lki_p = card.power();
546                    let lki_t = card.toughness();
547                    let card = &mut self.cards[card_id.index()];
548                    card.lki_power = Some(lki_p);
549                    card.lki_toughness = Some(lki_t);
550                }
551
552                // Reset battlefield state when leaving (including static modifiers).
553                let keep_counters =
554                    crate::staticability::static_ability_counters_remain::counters_remain(
555                        &self.cards,
556                        &self.cards[card_id.index()],
557                        dest_zone,
558                    );
559                let card = &mut self.cards[card_id.index()];
560                card.tapped = false;
561                card.damage = 0;
562                card.power_modifier = 0;
563                card.toughness_modifier = 0;
564                card.static_power_modifier = 0;
565                card.static_toughness_modifier = 0;
566                card.static_set_power = None;
567                card.static_set_toughness = None;
568                card.granted_keywords.clear();
569                if let Some(type_line) = card.static_type_line_base.take() {
570                    card.set_type_line(type_line);
571                }
572                card.static_added_subtypes.clear();
573                card.restore_changed_characteristics_baseline();
574                card.cant_attack_static = false;
575                card.cant_block_static = false;
576                card.summoning_sick = true;
577                card.monstrous = false;
578                card.controller = card.owner;
579                card.face_down = false;
580                card.is_bestowed = false;
581                // CR 400.7: a permanent that changes zones becomes a new
582                // object with no cast history. Mirrors Java's
583                // changeZone-creates-new-Card behaviour.
584                card.cast_from = None;
585                card.reset_crewed();
586                if !keep_counters {
587                    card.counters.clear();
588                }
589                // Clear temporary triggers added by Animate effects (e.g.
590                // Supernatural Stamina's "when this creature dies, return it").
591                // Per CR 400.7 a permanent that changes zones becomes a new
592                // object; it must not retain one-shot death-return triggers.
593                // Without this, a creature that dies-and-returns would still
594                // carry the trigger, making it "immortal" for the rest of the
595                // turn.
596                card.clear_pump_triggers();
597                card.clear_pump_keywords();
598                // Restore intrinsic keywords from the animate snapshot so
599                // Animate-granted keywords (e.g. Sneak Attack's `Keywords$
600                // Haste`) do not persist into the new object the card
601                // becomes when it changes zones (CR 400.7).
602                if let Some(state) = card.animate_state.take() {
603                    if let Some(orig_kws) = state.original_keywords {
604                        card.keywords = orig_kws;
605                        card.update_keywords();
606                    }
607                }
608                if let Some(state) = card.clone_state.take() {
609                    card.restore_clone_snapshot(state);
610                } else {
611                    card.remove_clone_states();
612                }
613            }
614            ZoneType::Command => {
615                // Detach any attachments before resetting state.
616                let attachments: Vec<CardId> = self.cards[card_id.index()].attachments.clone();
617                for aura_id in attachments {
618                    self.cards[aura_id.index()].attached_to = None;
619                }
620                self.cards[card_id.index()].attachments.clear();
621                self.detach(card_id);
622
623                // Commander returning to command zone: reset battlefield state.
624                let keep_counters =
625                    crate::staticability::static_ability_counters_remain::counters_remain(
626                        &self.cards,
627                        &self.cards[card_id.index()],
628                        dest_zone,
629                    );
630                let card = &mut self.cards[card_id.index()];
631                card.tapped = false;
632                card.damage = 0;
633                card.power_modifier = 0;
634                card.toughness_modifier = 0;
635                card.static_power_modifier = 0;
636                card.static_toughness_modifier = 0;
637                card.static_set_power = None;
638                card.static_set_toughness = None;
639                card.granted_keywords.clear();
640                if let Some(type_line) = card.static_type_line_base.take() {
641                    card.set_type_line(type_line);
642                }
643                card.static_added_subtypes.clear();
644                card.restore_changed_characteristics_baseline();
645                card.cant_attack_static = false;
646                card.cant_block_static = false;
647                card.summoning_sick = true;
648                card.monstrous = false;
649                card.controller = card.owner;
650                card.cast_from = None;
651                if !keep_counters {
652                    card.counters.clear();
653                }
654                if let Some(state) = card.clone_state.take() {
655                    card.restore_clone_snapshot(state);
656                } else {
657                    card.remove_clone_states();
658                }
659            }
660            _ => {}
661        }
662        if src_zone != dest_zone {
663            let card = &mut self.cards[card_id.index()];
664            card.on_adventure = adventure_exile;
665            if dest_zone != ZoneType::Stack {
666                card.set_adventure_state(false);
667                if !(src_zone == ZoneType::Stack && dest_zone == ZoneType::Battlefield) {
668                    card.reset_prototype();
669                }
670            }
671        }
672
673        // Add to destination zone
674        self.add_card_to_zone(dest_zone, dest_owner, card_id);
675
676        // Commander 903.9a tracking: once a commander enters graveyard or exile,
677        // SBA may offer moving it to the command zone exactly once.
678        let commander_entered_gy_or_exile = self.card(card_id).is_commander
679            && matches!(dest_zone, ZoneType::Graveyard | ZoneType::Exile);
680        self.cards[card_id.index()].move_to_command_zone = commander_entered_gy_or_exile;
681
682        // Forget remembered objects for command effects with ForgetOnMoved.
683        let mut exile_effects = Vec::new();
684        for eff_id in forget_effects {
685            let eff = &mut self.cards[eff_id.index()];
686            eff.remembered_cards.retain(|&rid| rid != card_id);
687            if eff.exile_when_no_remembered && eff.remembered_cards.is_empty() {
688                exile_effects.push(eff_id);
689            }
690        }
691        // Effect cards with ForgetOnMoved should be removed from the game
692        // entirely (zone = None), not moved to Exile.
693        for eff_id in exile_effects {
694            let controller = self.card(eff_id).controller;
695            self.remove_card_from_zone(ZoneType::Command, controller, eff_id);
696            self.cards[eff_id.index()].zone = ZoneType::None;
697        }
698
699        // Expire temporary effect cards linked to this host leaving play
700        // (Duration$ UntilHostLeavesPlay / UntilHostLeavesPlayOrEOT).
701        if host_left_battlefield {
702            let linked_effects: Vec<CardId> = self
703                .cards
704                .iter()
705                .filter(|c| c.zone == ZoneType::Command && c.temp_effect_host == Some(card_id))
706                .map(|c| c.id)
707                .collect();
708            for eff_id in linked_effects {
709                let controller = self.card(eff_id).controller;
710                self.remove_card_from_zone(ZoneType::Command, controller, eff_id);
711                self.cards[eff_id.index()].zone = ZoneType::None;
712            }
713
714            // Return cards exiled by this host via ChangeZoneAll Duration$ UntilHostLeavesPlay
715            // (e.g. Deputy of Detention: exiled permanents return when it leaves).
716            let exiled_by_host: Vec<(CardId, PlayerId)> = self
717                .cards
718                .iter()
719                .filter(|c| c.zone == ZoneType::Exile && c.exiled_by == Some(card_id))
720                .map(|c| (c.id, c.owner))
721                .collect();
722            for (exiled_id, owner) in exiled_by_host {
723                self.cards[exiled_id.index()].exiled_by = None;
724                self.move_card(exiled_id, ZoneType::Battlefield, owner);
725                if let Some(handler) = trigger_handler.as_deref_mut() {
726                    let returned_zone = self.card(exiled_id).zone;
727                    handler.register_active_trigger(self, exiled_id);
728                    crate::ability::effects::zone_triggers::emit_zone_trigger(
729                        handler,
730                        exiled_id,
731                        ZoneType::Exile,
732                        returned_zone,
733                    );
734                }
735            }
736        }
737
738        apply_continuous_effects(self);
739        debug_assert!(self.card_zone_location_matches_card(card_id));
740    }
741
742    /// Deal damage to a card (creature).
743    ///
744    /// Runs replacement effects (e.g. damage prevention) before applying.
745    /// Mirrors Java `GameAction.addDamage()` calling `ReplacementHandler.run()`.
746    pub fn deal_damage_to_card(&mut self, target: CardId, amount: i32) {
747        self.deal_damage_to_card_from(target, amount, None, false);
748    }
749
750    /// Deal damage to a card with source tracking for replacement effects.
751    pub fn deal_damage_to_card_from(
752        &mut self,
753        target: CardId,
754        amount: i32,
755        source: Option<CardId>,
756        is_combat: bool,
757    ) {
758        self.deal_damage_to_card_from_with_agents(target, amount, source, is_combat, None);
759    }
760
761    /// Deal damage to a card with source tracking and optional agents for RNG parity.
762    pub fn deal_damage_to_card_from_with_agents(
763        &mut self,
764        target: CardId,
765        amount: i32,
766        source: Option<CardId>,
767        is_combat: bool,
768        agents: Option<&mut [Box<dyn crate::agent::PlayerAgent>]>,
769    ) {
770        if amount <= 0 {
771            return;
772        }
773        if !self.card(target).can_be_dealt_damage() {
774            return;
775        }
776        let mut event = ReplacementEvent::DamageToCard {
777            target,
778            amount,
779            source,
780            is_combat,
781        };
782        if let Some(agents) = agents {
783            apply_replacements_with_agents(self, agents, &mut event);
784        } else {
785            apply_replacements(self, &mut event);
786        }
787        if let ReplacementEvent::DamageToCard {
788            amount: mut final_amount,
789            ..
790        } = event
791        {
792            // Consume PreventDamage shields. Each shield prevents 1 damage and
793            // is removed. Mirrors Java's per-shield ReplaceDamage effect cards
794            // in the Command zone, but using the legacy `damage_prevention`
795            // counter pending the proper Command-zone effect-card port.
796            let shields = self.cards[target.index()].damage_prevention;
797            if shields > 0 && final_amount > 0 {
798                let consumed = shields.min(final_amount);
799                self.cards[target.index()].damage_prevention -= consumed;
800                final_amount -= consumed;
801            }
802            if final_amount > 0 {
803                let dealt = self.cards[target.index()].add_damage_after_prevention(final_amount);
804                // Fire DealtDamage replacement event after damage is applied.
805                let mut dealt_event = ReplacementEvent::DealtDamage {
806                    target,
807                    amount: dealt,
808                    source,
809                };
810                if dealt > 0 {
811                    apply_replacements(self, &mut dealt_event);
812                }
813            }
814        }
815    }
816
817    /// Deal damage to a player.
818    ///
819    /// Runs replacement effects (e.g. damage prevention) before applying.
820    /// Mirrors Java `GameAction.addDamage()` calling `ReplacementHandler.run()`.
821    pub fn deal_damage_to_player(&mut self, target: PlayerId, amount: i32) -> i32 {
822        self.deal_damage_to_player_from(target, amount, None, false)
823    }
824
825    /// Deal damage to a player with source tracking for replacement effects.
826    pub fn deal_damage_to_player_from(
827        &mut self,
828        target: PlayerId,
829        amount: i32,
830        source: Option<CardId>,
831        is_combat: bool,
832    ) -> i32 {
833        self.deal_damage_to_player_from_with_agents(target, amount, source, is_combat, None)
834    }
835
836    /// Deal damage to a player with source tracking and optional agents for RNG parity.
837    /// Used by combat damage and spell damage to pass the source card and
838    /// combat flag so replacement effects like Torbran and Furnace of Rath
839    /// can check ValidSource$ and IsCombat$.
840    pub fn deal_damage_to_player_from_with_agents(
841        &mut self,
842        target: PlayerId,
843        amount: i32,
844        source: Option<CardId>,
845        is_combat: bool,
846        agents: Option<&mut [Box<dyn crate::agent::PlayerAgent>]>,
847    ) -> i32 {
848        if amount <= 0 {
849            return 0;
850        }
851        if crate::staticability::static_ability_cant_gain_lose_pay_life::cant_lose_life(
852            self, target,
853        ) {
854            return 0;
855        }
856        if crate::player::has_keyword(self, target, "Protection from everything") {
857            return 0;
858        }
859        let mut event = ReplacementEvent::DamageToPlayer {
860            target,
861            amount,
862            source,
863            is_combat,
864        };
865        if let Some(agents) = agents {
866            apply_replacements_with_agents(self, agents, &mut event);
867        } else {
868            apply_replacements(self, &mut event);
869        }
870        if let ReplacementEvent::DamageToPlayer {
871            amount: final_amount,
872            ..
873        } = event
874        {
875            if final_amount > 0 {
876                return self.player_deal_damage(target, final_amount);
877            }
878        }
879        0
880    }
881
882    /// Check and apply state-based actions. Returns true if any were applied.
883    pub fn check_state_based_actions(&mut self) -> bool {
884        self.check_state_based_actions_with_triggers(None, None)
885    }
886
887    /// Check and apply state-based actions. Returns true if any were applied.
888    /// If provided, emits ChangesZone triggers for SBA zone moves.
889    /// `legend_keep_fn` — optional callback for legend rule: given (player, duplicates),
890    /// returns the CardId to keep.  Mirrors Java's `chooseSingleEntityForEffect`.
891    pub fn check_state_based_actions_with_triggers(
892        &mut self,
893        trigger_handler: Option<&mut TriggerHandler>,
894        legend_keep_fn: Option<&mut dyn FnMut(PlayerId, &[CardId]) -> CardId>,
895    ) -> bool {
896        self.check_state_based_actions_impl(trigger_handler, legend_keep_fn, None)
897    }
898
899    pub fn check_state_based_actions_with_trigger_agents(
900        &mut self,
901        trigger_handler: Option<&mut TriggerHandler>,
902        agents: &mut [Box<dyn PlayerAgent>],
903    ) -> bool {
904        self.check_state_based_actions_impl(trigger_handler, None, Some(agents))
905    }
906
907    fn state_based_action_saga(
908        &self,
909        cid: CardId,
910        trigger_handler: Option<&TriggerHandler>,
911        sacrifice_list: &mut Vec<CardId>,
912    ) -> bool {
913        let card = self.card(cid);
914        if !card.type_line.has_subtype("Saga") || !card.has_chapter() {
915            return false;
916        }
917        if crate::staticability::static_ability_cant_sacrifice::cant_sacrifice(
918            &self.cards,
919            card,
920            None,
921            true,
922        ) {
923            return false;
924        }
925        if card.counter_count(&CounterType::Lore) < card.get_final_chapter_nr() {
926            return false;
927        }
928        if self.stack.has_source_chapter_on_stack(self, cid)
929            || trigger_handler.is_some_and(|handler| handler.has_source_chapter_pending(self, cid))
930        {
931            return false;
932        }
933        sacrifice_list.push(cid);
934        true
935    }
936
937    fn on_player_lost(
938        &mut self,
939        player: PlayerId,
940        trigger_handler: &mut Option<&mut TriggerHandler>,
941    ) {
942        self.player_mut(player).left_game = true;
943        let is_multiplayer = self.player_order.len() > 2;
944        let all_cards: Vec<CardId> = (0..self.cards.len()).map(|i| CardId(i as u32)).collect();
945
946        if !is_multiplayer {
947            // CR 707.9: at the end of the game every face-down card is revealed.
948            for &cid in &all_cards {
949                self.cards[cid.index()].force_turn_face_up();
950            }
951            return;
952        }
953
954        // CR 724.4 / CR 725.4. Reassigned before the sweep so the old effect
955        if self.monarch == Some(player) {
956            let heir = if self.turn.active_player == player {
957                self.next_player(player)
958            } else {
959                self.turn.active_player
960            };
961            self.player_set_monarch(heir, trigger_handler.as_deref_mut());
962        }
963        if self.initiative_holder == Some(player) {
964            let heir = if self.turn.active_player == player {
965                self.next_player(player)
966            } else {
967                self.turn.active_player
968            };
969            self.player_take_initiative(heir, trigger_handler.as_deref_mut());
970        }
971
972        let next = self.next_player(player);
973        for &cid in &all_cards {
974            let (zone, owner, controller) = {
975                let card = &self.cards[cid.index()];
976                (card.zone, card.owner, card.controller)
977            };
978            if zone == ZoneType::None {
979                continue;
980            }
981            if owner != player {
982                // CR 800.4c: nothing stays enchanting the leaving player.
983                if self.cards[cid.index()].attached_to_player == Some(player) {
984                    self.cards[cid.index()].attached_to_player = None;
985                }
986                continue;
987            }
988            if self.cards[cid.index()].effect_source.is_some() && zone == ZoneType::Command {
989                // Mirrors Java: lingering effects move to the next player so
990                // they continue to work.
991                self.remove_card_from_zone(ZoneType::Command, controller, cid);
992                self.cards[cid.index()].controller = next;
993                self.add_card_to_zone(ZoneType::Command, next, cid);
994                continue;
995            }
996            // CR 800.4a: objects owned by the leaving player leave the game.
997            for &other in &all_cards {
998                if other == cid {
999                    continue;
1000                }
1001                let other_card = &mut self.cards[other.index()];
1002                other_card.imprinted_cards.retain(|&r| r != cid);
1003                other_card.remembered_cards.retain(|&r| r != cid);
1004                other_card.attachments.retain(|&r| r != cid);
1005                other_card.gain_control_targets.retain(|&r| r != cid);
1006                if other_card.attached_to == Some(cid) {
1007                    other_card.attached_to = None;
1008                }
1009            }
1010            if let Some(handler) = trigger_handler.as_deref_mut() {
1011                crate::ability::effects::emit_zone_trigger(handler, cid, zone, ZoneType::None);
1012            }
1013            self.remove_card_from_zone(zone, controller, cid);
1014            self.cards[cid.index()].zone = ZoneType::None;
1015        }
1016
1017        apply_continuous_effects(self);
1018
1019        // CR 800.4d as Java implements it: permanents the leaving player
1020        for &cid in &all_cards {
1021            let (zone, owner, controller) = {
1022                let card = &self.cards[cid.index()];
1023                (card.zone, card.owner, card.controller)
1024            };
1025            if zone == ZoneType::Battlefield && controller == player && owner != player {
1026                if let Some(handler) = trigger_handler.as_deref_mut() {
1027                    crate::ability::effects::emit_zone_trigger(
1028                        handler,
1029                        cid,
1030                        ZoneType::Battlefield,
1031                        ZoneType::Exile,
1032                    );
1033                }
1034                self.move_card_without_replacement(cid, ZoneType::Exile, owner);
1035            }
1036        }
1037    }
1038
1039    fn move_battlefield_card_to_graveyard_for_sba(
1040        &mut self,
1041        cid: CardId,
1042        trigger_handler: &mut Option<&mut TriggerHandler>,
1043        agents: &mut Option<&mut [Box<dyn PlayerAgent>]>,
1044    ) {
1045        let owner = self.card(cid).owner;
1046        let mut moved_event = ReplacementEvent::Moved {
1047            card: cid,
1048            origin: ZoneType::Battlefield,
1049            destination: ZoneType::Graveyard,
1050            is_discard: false,
1051            counter_map: None,
1052            counter_cause: None,
1053            counter_is_effect: false,
1054            after_replacement_static_abilities: Vec::new(),
1055        };
1056        if let Some(agents) = agents.as_deref_mut() {
1057            apply_replacements_with_agents(self, agents, &mut moved_event);
1058        } else {
1059            apply_replacements(self, &mut moved_event);
1060        }
1061        let final_dest = if let ReplacementEvent::Moved { destination, .. } = moved_event {
1062            destination
1063        } else {
1064            ZoneType::Graveyard
1065        };
1066        let old_zone = self.card(cid).zone;
1067        // Emit trigger BEFORE move_card so LKI state is still available for
1068        // trigger matching. Persist/Undying and Modular inspect the dying card.
1069        if let Some(handler) = trigger_handler.as_deref_mut() {
1070            let lki_p1p1 = *self
1071                .card(cid)
1072                .counters
1073                .get(&CounterType::P1P1)
1074                .unwrap_or(&0);
1075            let lki_power = self.card(cid).power();
1076            let lki_toughness = self.card(cid).toughness();
1077            let lki_counters = self.card(cid).counters.clone();
1078            self.card_mut(cid).lki_counters = Some(lki_counters);
1079            self.card_mut(cid)
1080                .set_lki_power_toughness(Some(lki_power), Some(lki_toughness));
1081            crate::ability::effects::emit_zone_trigger_with_lki_counters(
1082                handler,
1083                cid,
1084                old_zone,
1085                final_dest,
1086                lki_p1p1,
1087                lki_power,
1088                lki_toughness,
1089            );
1090            handler.flush_waiting_triggers(self);
1091        }
1092        self.move_card_without_replacement(cid, final_dest, owner);
1093    }
1094
1095    fn check_state_based_actions_impl(
1096        &mut self,
1097        mut trigger_handler: Option<&mut TriggerHandler>,
1098        mut legend_keep_fn: Option<&mut dyn FnMut(PlayerId, &[CardId]) -> CardId>,
1099        mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
1100    ) -> bool {
1101        // Capture battlefield state before SBA processing. Used by DisableTriggers
1102        // (Hushbringer) to check LKI — if a creature with DisableTriggers dies in
1103        // the same SBA batch as another creature, it still suppresses death triggers.
1104        // Mirrors Java's LastStateBattlefield passed through RunParams.
1105        self.pre_sba_battlefield = self
1106            .cards
1107            .iter()
1108            .filter(|c| c.zone == ZoneType::Battlefield)
1109            .map(|c| c.id)
1110            .collect();
1111
1112        let mut any_changes = false;
1113        let mut newly_lost_players: Vec<PlayerId> = Vec::new();
1114        let mut sacrifice_list: Vec<CardId> = Vec::new();
1115
1116        // Check players with 0 or less life
1117        for pid in self.player_order.clone() {
1118            if self.player(pid).tried_to_draw_from_empty_library && self.player(pid).is_alive() {
1119                self.player_mut(pid).tried_to_draw_from_empty_library = false;
1120                let mut event = ReplacementEvent::GameLoss {
1121                    player: pid,
1122                    reason: GameLossReason::Milled,
1123                };
1124                let result = apply_replacements(self, &mut event);
1125                if result != ReplacementResult::Replaced && !self.player(pid).has_lost {
1126                    self.player_mark_lost(pid, GameLossReason::Milled);
1127                    newly_lost_players.push(pid);
1128                    any_changes = true;
1129                }
1130            }
1131            if self.player(pid).life <= 0 && self.player(pid).is_alive() {
1132                let mut event = ReplacementEvent::GameLoss {
1133                    player: pid,
1134                    reason: GameLossReason::LifeReachedZero,
1135                };
1136                let result = apply_replacements(self, &mut event);
1137                if result != ReplacementResult::Replaced && !self.player(pid).has_lost {
1138                    self.player_mark_lost(pid, GameLossReason::LifeReachedZero);
1139                    newly_lost_players.push(pid);
1140                    any_changes = true;
1141                }
1142            }
1143            // Check poison counters (10+ = lose)
1144            if self.player(pid).poison_counters >= 10 && self.player(pid).is_alive() {
1145                let mut event = ReplacementEvent::GameLoss {
1146                    player: pid,
1147                    reason: GameLossReason::Poisoned,
1148                };
1149                let result = apply_replacements(self, &mut event);
1150                if result != ReplacementResult::Replaced {
1151                    if !self.player(pid).has_lost {
1152                        self.player_mark_lost(pid, GameLossReason::Poisoned);
1153                        newly_lost_players.push(pid);
1154                    }
1155                    any_changes = true;
1156                }
1157            }
1158            // Check commander damage (21+ from a single commander source = lose)
1159            if self.player(pid).commander_damage_enabled {
1160                let commander_dmg_entries: Vec<(u32, i32)> = self
1161                    .player(pid)
1162                    .commander_damage_received
1163                    .iter()
1164                    .map(|(&k, &v)| (k, v))
1165                    .collect();
1166                for (_card_raw_id, dmg) in commander_dmg_entries {
1167                    if dmg >= 21 && self.player(pid).is_alive() && !self.player(pid).has_lost {
1168                        self.player_mark_lost(pid, GameLossReason::CommanderDamage);
1169                        newly_lost_players.push(pid);
1170                        any_changes = true;
1171                    }
1172                }
1173            }
1174
1175            // CR 704.5z: If a player controls a permanent with Start your
1176            // engines! and that player has no speed, their speed becomes 1.
1177            if self.player(pid).speed == 0
1178                && self
1179                    .cards_in_zone(ZoneType::Battlefield, pid)
1180                    .iter()
1181                    .any(|&cid| self.card(cid).has_keyword("Start your engines"))
1182            {
1183                self.increase_player_speed(pid, None);
1184                any_changes = true;
1185            }
1186        }
1187
1188        for pid in self.player_order.clone() {
1189            if !self.player(pid).is_alive()
1190                && !self.player(pid).left_game
1191                && !newly_lost_players.contains(&pid)
1192            {
1193                newly_lost_players.push(pid);
1194                any_changes = true;
1195            }
1196        }
1197
1198        if !newly_lost_players.is_empty() {
1199            for pid in &newly_lost_players {
1200                self.on_player_lost(*pid, &mut trigger_handler);
1201                self.stack.remove_instances_controlled_by(*pid);
1202            }
1203            if let Some(handler) = trigger_handler.as_deref_mut() {
1204                for pid in &newly_lost_players {
1205                    handler.run_trigger(
1206                        TriggerType::LosesGame,
1207                        RunParams {
1208                            player: Some(*pid),
1209                            ..Default::default()
1210                        },
1211                        false,
1212                    );
1213                    handler.on_player_lost(*pid);
1214                }
1215            }
1216        }
1217
1218        // Check creatures with lethal damage or 0 toughness
1219        let battlefield_cards: Vec<CardId> = self
1220            .player_order
1221            .clone()
1222            .iter()
1223            .flat_map(|&pid| self.cards_in_zone(ZoneType::Battlefield, pid).to_vec())
1224            .collect();
1225
1226        for cid in battlefield_cards {
1227            let (is_creature, zero_toughness, lethal, should_die) = {
1228                let card = &self.cards[cid.index()];
1229                let is_creature = card.is_creature();
1230                let zero_toughness = card.toughness() <= 0;
1231                let lethal = card.lethal_damage() || card.has_deathtouch_damage;
1232                let should_die = zero_toughness || lethal;
1233                (is_creature, zero_toughness, lethal, should_die)
1234            };
1235            if is_creature && should_die {
1236                // Clear deathtouch flag regardless of outcome (mirrors Java
1237                // GameAction.java line 1491: c.setHasBeenDealtDeathtouchDamage(false)).
1238                self.cards[cid.index()].has_deathtouch_damage = false;
1239                // CR 702.12: Indestructible prevents death from lethal damage and
1240                // "destroy" effects, but NOT from toughness ≤ 0 (CR 704.5f vs 704.5g).
1241                // This covers K:Indestructible from Forge card scripts (e.g. Darksteel Myr).
1242                if lethal
1243                    && !zero_toughness
1244                    && self.cards[cid.index()].has_keyword("Indestructible")
1245                {
1246                    continue;
1247                }
1248                // CR 702.89: Umbra armor (Totem Armor) — if enchanted creature
1249                // would be destroyed, instead remove all damage and destroy the aura.
1250                let has_umbra = self.cards[cid.index()].attachments.iter().any(|&aid| {
1251                    aid.index() < self.cards.len()
1252                        && self.cards[aid.index()].zone == ZoneType::Battlefield
1253                        && (self.cards[aid.index()].has_keyword("Umbra armor")
1254                            || self.cards[aid.index()].has_keyword("Totem armor"))
1255                });
1256                if has_umbra && !zero_toughness {
1257                    // Find the first umbra armor aura and destroy it instead
1258                    let umbra_id =
1259                        self.cards[cid.index()]
1260                            .attachments
1261                            .iter()
1262                            .copied()
1263                            .find(|&aid| {
1264                                aid.index() < self.cards.len()
1265                                    && self.cards[aid.index()].zone == ZoneType::Battlefield
1266                                    && (self.cards[aid.index()].has_keyword("Umbra armor")
1267                                        || self.cards[aid.index()].has_keyword("Totem armor"))
1268                            });
1269                    if let Some(umbra_id) = umbra_id {
1270                        // Remove all damage from the creature
1271                        self.cards[cid.index()].damage = 0;
1272                        self.cards[cid.index()].has_deathtouch_damage = false;
1273                        // Destroy the aura instead
1274                        let umbra_owner = self.cards[umbra_id.index()].owner;
1275                        let old_zone = self.cards[umbra_id.index()].zone;
1276                        self.move_card(umbra_id, ZoneType::Graveyard, umbra_owner);
1277                        if let Some(handler) = trigger_handler.as_deref_mut() {
1278                            crate::ability::effects::emit_zone_trigger(
1279                                handler,
1280                                umbra_id,
1281                                old_zone,
1282                                ZoneType::Graveyard,
1283                            );
1284                        }
1285                        any_changes = true;
1286                        continue; // Creature survives
1287                    }
1288                }
1289
1290                if zero_toughness {
1291                    self.move_battlefield_card_to_graveyard_for_sba(
1292                        cid,
1293                        &mut trigger_handler,
1294                        &mut agents,
1295                    );
1296                    any_changes = true;
1297                    continue;
1298                }
1299
1300                // Run Destroy replacement effects (R$-based indestructible, etc.).
1301                // Mirrors Java GameAction.destroy() → ReplacementHandler.run(Destroy, …).
1302                let mut destroy_event = ReplacementEvent::Destroy { target: cid };
1303                let result = apply_replacements(self, &mut destroy_event);
1304                if result != ReplacementResult::Replaced {
1305                    self.move_battlefield_card_to_graveyard_for_sba(
1306                        cid,
1307                        &mut trigger_handler,
1308                        &mut agents,
1309                    );
1310                    // Same-SBA-batch LTB lookback is derived per-event from
1311                    // `pre_sba_battlefield` in `TriggerHandler::ltb_trigger_refs_for_event`.
1312                    // No global registration needed.
1313                    any_changes = true;
1314                } else {
1315                    // Indestructible — destruction was replaced; creature stays.
1316                    // Damage is still marked but the creature does not die.
1317                }
1318            }
1319        }
1320
1321        let battlefield_cards: Vec<CardId> = self
1322            .player_order
1323            .clone()
1324            .iter()
1325            .flat_map(|&pid| self.cards_in_zone(ZoneType::Battlefield, pid).to_vec())
1326            .collect();
1327
1328        for cid in battlefield_cards {
1329            let should_put_in_graveyard = {
1330                let card = self.card(cid);
1331                card.type_line.is_planeswalker() && card.counter_count(&CounterType::Loyalty) <= 0
1332            };
1333            if !should_put_in_graveyard {
1334                continue;
1335            }
1336
1337            self.move_battlefield_card_to_graveyard_for_sba(cid, &mut trigger_handler, &mut agents);
1338            any_changes = true;
1339        }
1340
1341        let saga_cards: Vec<CardId> = self
1342            .player_order
1343            .clone()
1344            .iter()
1345            .flat_map(|&pid| self.cards_in_zone(ZoneType::Battlefield, pid).to_vec())
1346            .collect();
1347        for cid in saga_cards {
1348            any_changes |=
1349                self.state_based_action_saga(cid, trigger_handler.as_deref(), &mut sacrifice_list);
1350        }
1351
1352        if !sacrifice_list.is_empty() {
1353            if let (Some(handler), Some(agents)) =
1354                (trigger_handler.as_deref_mut(), agents.as_deref_mut())
1355            {
1356                if !crate::game_loop::perform_sacrifice(self, handler, agents, &sacrifice_list)
1357                    .is_empty()
1358                {
1359                    any_changes = true;
1360                }
1361            } else {
1362                for cid in sacrifice_list.drain(..) {
1363                    let owner = self.card(cid).owner;
1364                    self.move_card_without_replacement(cid, ZoneType::Graveyard, owner);
1365                }
1366                any_changes = true;
1367            }
1368        }
1369
1370        // CR 704.5q: +1/+1 and -1/-1 counter cancellation
1371        for &pid in &self.player_order.clone() {
1372            let battlefield = self.cards_in_zone(ZoneType::Battlefield, pid).to_vec();
1373            for cid in battlefield {
1374                let p1 = self.card(cid).counter_count(&CounterType::P1P1);
1375                let m1 = self.card(cid).counter_count(&CounterType::M1M1);
1376                if p1 > 0 && m1 > 0 {
1377                    let cancel = p1.min(m1);
1378                    self.card_mut(cid)
1379                        .remove_counter(&CounterType::P1P1, cancel);
1380                    self.card_mut(cid)
1381                        .remove_counter(&CounterType::M1M1, cancel);
1382                    any_changes = true;
1383                }
1384            }
1385        }
1386
1387        // CR 903.9a: a commander in graveyard or exile may move to command zone.
1388        for &pid in &self.player_order.clone() {
1389            let mut commander_candidates = self.cards_in_zone(ZoneType::Graveyard, pid).to_vec();
1390            commander_candidates.extend(self.cards_in_zone(ZoneType::Exile, pid).iter().copied());
1391            for cid in commander_candidates {
1392                if !self.card(cid).can_move_to_command_zone() {
1393                    continue;
1394                }
1395                self.card_mut(cid).move_to_command_zone = false;
1396                let accepted = if let Some(agents) = agents.as_deref_mut() {
1397                    let name = self.card(cid).card_name.clone();
1398                    let message = format!(
1399                        "{name}: If a commander is in a graveyard or in exile and that card was put into that zone since the last time state-based actions were checked, its owner may put it into the command zone."
1400                    );
1401                    agents[pid.index()].confirm_action(
1402                        pid,
1403                        Some("ChangeZoneToAltDestination"),
1404                        &message,
1405                        &[],
1406                        Some(cid),
1407                        None,
1408                    )
1409                } else {
1410                    false
1411                };
1412                if accepted {
1413                    self.move_card_without_replacement(cid, ZoneType::Command, pid);
1414                    any_changes = true;
1415                }
1416            }
1417        }
1418
1419        // Legend rule: for each player, if they control multiple legendary
1420        // permanents with the same name, keep one and move the rest to graveyard.
1421        // IgnoreLegendRule statics exempt matching cards.
1422        for &pid in &self.player_order.clone() {
1423            let battlefield = self.cards_in_zone(ZoneType::Battlefield, pid).to_vec();
1424            let mut by_name: std::collections::BTreeMap<String, Vec<CardId>> =
1425                std::collections::BTreeMap::new();
1426            for cid in battlefield {
1427                let c = self.card(cid);
1428                if !c.type_line.is_legendary() {
1429                    continue;
1430                }
1431                if crate::staticability::static_ability_ignore_legend_rule::ignore_legend_rule(
1432                    &self.cards,
1433                    c,
1434                ) {
1435                    continue;
1436                }
1437                by_name.entry(c.card_name.clone()).or_default().push(cid);
1438            }
1439            for (_name, ids) in by_name {
1440                if ids.len() <= 1 {
1441                    continue;
1442                }
1443                // Choose which to keep: delegate to callback (mirrors Java's
1444                // chooseSingleEntityForEffect), or default to first in zone order.
1445                let keep = if let Some(ref mut chooser) = legend_keep_fn {
1446                    chooser(pid, &ids)
1447                } else if let Some(agents) = agents.as_deref_mut() {
1448                    agents[pid.index()].choose_legend_keep(pid, &ids)
1449                } else {
1450                    ids[0]
1451                };
1452                for cid in ids {
1453                    if cid == keep {
1454                        continue;
1455                    }
1456                    let owner = self.card(cid).owner;
1457                    let old_zone = self.card(cid).zone;
1458                    if let Some(agents) = agents.as_deref_mut() {
1459                        self.move_card_with_agents(cid, ZoneType::Graveyard, owner, agents);
1460                    } else {
1461                        self.move_card(cid, ZoneType::Graveyard, owner);
1462                    }
1463                    if let Some(handler) = trigger_handler.as_deref_mut() {
1464                        crate::ability::effects::emit_zone_trigger(
1465                            handler,
1466                            cid,
1467                            old_zone,
1468                            ZoneType::Graveyard,
1469                        );
1470                    }
1471                    any_changes = true;
1472                }
1473            }
1474        }
1475
1476        // CR 704.5n: Aura SBA — an Aura on the battlefield that is not attached
1477        // to a legal permanent (or whose host left the battlefield) is put into
1478        // its owner's graveyard.
1479        {
1480            let aura_ids: Vec<CardId> = self
1481                .cards
1482                .iter()
1483                .filter(|c| {
1484                    c.zone == ZoneType::Battlefield
1485                        && c.type_line.has_subtype("Aura")
1486                        && !c.type_line.is_creature() // Bestowed auras that became creatures stay
1487                })
1488                .filter(|c| {
1489                    match (c.attached_to, c.attached_to_player) {
1490                        (None, None) => true, // Not attached to anything — orphaned
1491                        (None, Some(player_id)) => {
1492                            if player_id.index() >= self.players.len() {
1493                                return true;
1494                            }
1495                            let player = &self.players[player_id.index()];
1496                            let enchant_type = c
1497                                .keywords
1498                                .iter_strings()
1499                                .find_map(|kw| {
1500                                    crate::keyword::extract_keyword_cost_str(kw, "Enchant")
1501                                })
1502                                .unwrap_or_default();
1503                            player.has_lost || !enchant_type.eq_ignore_ascii_case("Player")
1504                        }
1505                        (Some(host_id), _) => {
1506                            if host_id.index() >= self.cards.len() {
1507                                return true; // Invalid host ID
1508                            }
1509                            let host = &self.cards[host_id.index()];
1510                            // CR 704.5n: check if the enchant restriction is still met.
1511                            // E.g. "Enchant creature" requires a battlefield creature, while
1512                            // Animate Dead's "Enchant creature card in a graveyard" remains legal
1513                            // while attached to a creature card in a graveyard.
1514                            let enchant_type = c
1515                                .keywords
1516                                .iter_strings()
1517                                .find_map(|kw| {
1518                                    crate::keyword::extract_keyword_cost_str(kw, "Enchant")
1519                                })
1520                                .unwrap_or_default();
1521                            !crate::parsing::enchant_type_matches_card(enchant_type, host, Some(c))
1522                                || !can_attachment_remain_attached(&self.cards, c, host, true)
1523                        }
1524                    }
1525                })
1526                .map(|c| c.id)
1527                .collect();
1528
1529            for aura_id in aura_ids {
1530                let owner = self.card(aura_id).owner;
1531                let old_zone = self.card(aura_id).zone;
1532                self.move_card(aura_id, ZoneType::Graveyard, owner);
1533                if let Some(handler) = trigger_handler.as_deref_mut() {
1534                    crate::ability::effects::emit_zone_trigger(
1535                        handler,
1536                        aura_id,
1537                        old_zone,
1538                        ZoneType::Graveyard,
1539                    );
1540                }
1541                any_changes = true;
1542            }
1543        }
1544
1545        // Check game over
1546        let alive = self.alive_players();
1547        if alive.len() <= 1 {
1548            self.game_over = true;
1549            if alive.len() == 1 {
1550                self.winner = Some(alive[0]);
1551            }
1552        }
1553
1554        any_changes
1555    }
1556
1557    /// Untap all permanents controlled by a player.
1558    /// Runs Untap replacement effects for each permanent.
1559    pub fn untap_all(&mut self, player: PlayerId) {
1560        let cards: Vec<CardId> = self.cards_in_zone(ZoneType::Battlefield, player).to_vec();
1561        for cid in cards {
1562            // Use untap() which runs replacement effects
1563            self.untap_during_untap_step(cid, player);
1564        }
1565    }
1566
1567    /// Draw a card for a player. Returns the drawn card ID, or None if the draw
1568    /// was skipped or the library is empty.
1569    ///
1570    /// Runs Draw replacement effects before drawing.  If the draw is replaced
1571    /// (e.g. "skip your draw step"), returns `None`.
1572    ///
1573    /// Mirrors Java `GameAction.draw()` calling `ReplacementHandler.run(Draw, …)`.
1574    pub fn draw_card(&mut self, player: PlayerId) -> Option<CardId> {
1575        self.player_draw_one(player)
1576    }
1577
1578    /// Draw a card with agent access for Optional replacement effects (Dredge).
1579    pub fn draw_card_with_agents(
1580        &mut self,
1581        player: PlayerId,
1582        agents: &mut [Box<dyn crate::agent::PlayerAgent>],
1583    ) -> Option<CardId> {
1584        self.player_draw_one_internal(player, false, Some(agents))
1585    }
1586
1587    /// Draw N cards for a player. Returns drawn card IDs.
1588    pub fn draw_cards(&mut self, player: PlayerId, n: usize) -> Vec<CardId> {
1589        self.player_draw_cards(player, n)
1590    }
1591
1592    /// Shuffle a player's library using the provided RNG.
1593    pub fn shuffle_library(&mut self, player: PlayerId, rng: &mut impl rand::Rng) {
1594        self.shuffle_zone_cards_with_rand(ZoneType::Library, player, rng);
1595    }
1596
1597    /// Reset per-turn state for all cards and players of a given player.
1598    pub fn new_turn_for_player(&mut self, player: PlayerId) {
1599        self.player_new_turn(player);
1600        // Reset turn-scoped player stats for ALL non-active players too.
1601        // These counters are "this turn" in the global turn sense, not "that
1602        // player's own turn". Without this, effects like Resplendent Angel can
1603        // incorrectly carry life gained from the previous player's turn.
1604        for pid in &self.player_order.clone() {
1605            if *pid != player {
1606                self.player_reset_drawn_this_turn(*pid);
1607                let p = self.player_mut(*pid);
1608                p.life_started_this_turn_with = p.life;
1609                p.life_gained_this_turn = 0;
1610                p.life_gained_by_team_this_turn = 0;
1611                p.life_gained_times_this_turn = 0;
1612                p.life_lost_last_turn = p.life_lost_this_turn;
1613                p.life_lost_this_turn = 0;
1614            }
1615        }
1616
1617        let all_card_ids: Vec<CardId> = (0..self.cards.len()).map(|i| CardId(i as u32)).collect();
1618        for cid in all_card_ids {
1619            if self.cards[cid.index()].zone == ZoneType::Battlefield {
1620                self.cards[cid.index()].started_turn_tapped = self.cards[cid.index()].tapped;
1621            }
1622            if self.cards[cid.index()].controller == player {
1623                self.cards[cid.index()].new_turn();
1624            } else {
1625                self.cards[cid.index()].clear_global_turn_state();
1626            }
1627        }
1628    }
1629
1630    /// Tap a card. Returns true if it was untapped.
1631    /// Runs Tap replacement effects before tapping.
1632    pub fn tap(&mut self, card_id: CardId) -> bool {
1633        let card = &self.cards[card_id.index()];
1634        if card.tapped {
1635            return false;
1636        }
1637        // Run Tap replacement effects.
1638        let mut event = ReplacementEvent::Tap { card: card_id };
1639        let result = apply_replacements(self, &mut event);
1640        if result == ReplacementResult::Skipped || result == ReplacementResult::Replaced {
1641            return false; // Tap was prevented
1642        }
1643        self.cards[card_id.index()].tapped = true;
1644        true
1645    }
1646
1647    /// Untap a card. Returns true if it was tapped.
1648    /// Runs Untap replacement effects before untapping.
1649    pub fn untap(&mut self, card_id: CardId) -> bool {
1650        self.untap_internal(card_id, None)
1651    }
1652
1653    pub fn untap_during_untap_step(&mut self, card_id: CardId, player: PlayerId) -> bool {
1654        self.untap_internal(card_id, Some(player))
1655    }
1656
1657    fn untap_internal(&mut self, card_id: CardId, player: Option<PlayerId>) -> bool {
1658        let card = &self.cards[card_id.index()];
1659        if !card.tapped {
1660            return false;
1661        }
1662        let stun = CounterType::Named("STUN".to_string());
1663        if card.counter_count(&stun) > 0 && card.can_remove_counters(&stun) {
1664            // Stun counters replace the untap event: remove one counter and keep the
1665            // permanent tapped. This mirrors Java's built-in stun untap replacement.
1666            self.cards[card_id.index()].remove_counter(&stun, 1);
1667            return false;
1668        }
1669        // Run Untap replacement effects.
1670        let mut event = ReplacementEvent::Untap {
1671            card: card_id,
1672            player,
1673        };
1674        let result = apply_replacements(self, &mut event);
1675        if result == ReplacementResult::Skipped || result == ReplacementResult::Replaced {
1676            return false; // Untap was prevented
1677        }
1678        self.cards[card_id.index()].tapped = false;
1679        // `ControlGain$ LoseControl$ Untap` — revert scheduled steal now.
1680        crate::ability::effects::control_gain_effect::untap_hook(self, card_id);
1681        true
1682    }
1683
1684    /// Change the controller of a permanent to `new_controller`.
1685    /// Mirrors Java's `GameAction.controllerChangeZoneCorrection()` — moves the
1686    /// card between per-player zone lists and updates the controller field.
1687    pub fn change_controller(&mut self, card_id: CardId, new_controller: PlayerId) {
1688        let card = &self.cards[card_id.index()];
1689        if card.controller == new_controller {
1690            return;
1691        }
1692        let old_controller = card.controller;
1693        let zone = card.zone;
1694
1695        self.expire_until_lose_control_keyword_changes(card_id);
1696        // Move between zone lists
1697        if zone != ZoneType::None {
1698            self.remove_card_from_zone(zone, old_controller, card_id);
1699            self.add_card_to_zone(zone, new_controller, card_id);
1700        }
1701        self.cards[card_id.index()].set_controller(new_controller);
1702    }
1703
1704    fn expire_until_lose_control_keyword_changes(&mut self, host: CardId) {
1705        let changes =
1706            std::mem::take(&mut self.cards[host.index()].until_lose_control_keyword_changes);
1707        for (target, timestamp) in changes {
1708            self.cards[target.index()].remove_changed_card_keywords_at(timestamp, 0);
1709        }
1710    }
1711
1712    /// Attach `aura_id` to `target_id`.
1713    /// If `aura_id` was already attached elsewhere, detach it first.
1714    /// Mirrors Java's `Card.enchantEntity()` / `Card.equip()`.
1715    pub fn attach_to(&mut self, aura_id: CardId, target_id: CardId) {
1716        // Detach from previous host if any
1717        self.detach(aura_id);
1718        self.cards[aura_id.index()].attached_to = Some(target_id);
1719        self.cards[aura_id.index()].attached_to_player = None;
1720        self.cards[aura_id.index()].attached_this_turn = true;
1721        self.cards[target_id.index()].attachments.push(aura_id);
1722    }
1723
1724    pub fn attach_to_player(&mut self, aura_id: CardId, player_id: PlayerId) {
1725        self.detach(aura_id);
1726        self.cards[aura_id.index()].attached_to = None;
1727        self.cards[aura_id.index()].attached_to_player = Some(player_id);
1728        self.cards[aura_id.index()].attached_this_turn = true;
1729    }
1730
1731    /// Detach `aura_id` from whatever it is currently attached to.
1732    /// Mirrors Java's `Card.unattachFromEntity()`.
1733    pub fn detach(&mut self, aura_id: CardId) {
1734        if let Some(host_id) = self.cards[aura_id.index()].attached_to.take() {
1735            self.cards[host_id.index()]
1736                .attachments
1737                .retain(|&a| a != aura_id);
1738            // Bestow: when unattached, revert to a creature
1739            self.cards[aura_id.index()].is_bestowed = false;
1740        }
1741        self.cards[aura_id.index()].attached_to_player = None;
1742    }
1743
1744    /// Move a card from its current zone to the bottom of a player's library.
1745    /// Unlike `move_card`, this places the card at the bottom rather than the top.
1746    pub fn put_on_bottom_of_library(&mut self, card_id: CardId, owner: PlayerId) {
1747        let card = &self.cards[card_id.index()];
1748        let src_zone = card.zone;
1749        let src_owner = card.controller;
1750
1751        self.expire_until_lose_control_keyword_changes(card_id);
1752        self.cards[card_id.index()].clear_changed_card_keyword_layers();
1753        if src_zone != ZoneType::None {
1754            self.remove_card_from_zone(src_zone, src_owner, card_id);
1755        }
1756
1757        self.cards[card_id.index()].zone = ZoneType::Library;
1758        self.assign_zone_timestamp(card_id);
1759        self.add_card_to_zone_bottom(ZoneType::Library, owner, card_id);
1760    }
1761
1762    /// Remove a spell from the stack by its entry ID (used by Counter).
1763    /// Mirrors Java's `Game.getStack().remove(sa)`.
1764    pub fn remove_from_stack(&mut self, entry_id: u32) -> bool {
1765        self.stack.remove_by_id(entry_id).is_some()
1766    }
1767}
1768
1769fn can_attachment_remain_attached(
1770    cards: &[Card],
1771    attachment: &Card,
1772    target: &Card,
1773    check_sba: bool,
1774) -> bool {
1775    if target.zone != ZoneType::Battlefield {
1776        return true;
1777    }
1778    if crate::staticability::static_ability_cant_attach::cant_attach(
1779        cards, attachment, target, check_sba,
1780    ) {
1781        return false;
1782    }
1783    !crate::staticability::static_ability_colorless_damage_source::target_is_protected_from_source(
1784        cards, target, attachment,
1785    )
1786}
1787
1788#[cfg(test)]
1789mod tests {
1790    use super::*;
1791    use crate::card::Card;
1792    use crate::player::RegisteredPlayer;
1793    use forge_foundation::{CardTypeLine, ColorSet, ManaCost};
1794
1795    fn make_creature(game: &mut GameState, name: &str, owner: PlayerId, p: i32, t: i32) -> CardId {
1796        let card = Card::new(
1797            CardId(0),
1798            name.to_string(),
1799            owner,
1800            CardTypeLine::parse("Creature Bear"),
1801            ManaCost::parse("1 G"),
1802            ColorSet::GREEN,
1803            Some(p),
1804            Some(t),
1805            vec![],
1806            vec![],
1807        );
1808        game.create_card(card)
1809    }
1810
1811    #[test]
1812    fn move_card_to_battlefield() {
1813        let mut game = GameState::new(&["Alice", "Bob"], 20);
1814        let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
1815        game.move_card(cid, ZoneType::Hand, PlayerId(0));
1816        assert_eq!(game.zone(ZoneType::Hand, PlayerId(0)).len(), 1);
1817
1818        game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
1819        assert_eq!(game.zone(ZoneType::Hand, PlayerId(0)).len(), 0);
1820        assert_eq!(game.zone(ZoneType::Battlefield, PlayerId(0)).len(), 1);
1821        assert_eq!(game.card(cid).zone, ZoneType::Battlefield);
1822    }
1823
1824    #[test]
1825    fn state_based_actions_lethal_damage() {
1826        let mut game = GameState::new(&["Alice", "Bob"], 20);
1827        let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
1828        game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
1829
1830        game.deal_damage_to_card(cid, 2);
1831        assert!(game.check_state_based_actions());
1832        assert_eq!(game.zone(ZoneType::Graveyard, PlayerId(0)).len(), 1);
1833    }
1834
1835    #[test]
1836    fn state_based_actions_zero_life() {
1837        let mut game = GameState::new(&["Alice", "Bob"], 20);
1838        game.deal_damage_to_player(PlayerId(0), 20);
1839        game.check_state_based_actions();
1840        assert!(game.player(PlayerId(0)).has_lost);
1841        assert!(game.game_over);
1842        assert_eq!(game.winner, Some(PlayerId(1)));
1843    }
1844
1845    #[test]
1846    fn draw_card() {
1847        let mut game = GameState::new(&["Alice", "Bob"], 20);
1848        let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
1849        game.move_card(cid, ZoneType::Library, PlayerId(0));
1850
1851        let drawn = game.draw_card(PlayerId(0));
1852        assert_eq!(drawn, Some(cid));
1853        assert_eq!(game.card(cid).zone, ZoneType::Hand);
1854    }
1855
1856    #[test]
1857    fn tap_untap() {
1858        let mut game = GameState::new(&["Alice", "Bob"], 20);
1859        let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
1860        game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
1861
1862        assert!(game.tap(cid));
1863        assert!(game.card(cid).tapped);
1864        assert!(!game.tap(cid)); // already tapped
1865        assert!(game.untap(cid));
1866        assert!(!game.card(cid).tapped);
1867    }
1868
1869    #[test]
1870    fn stun_counter_replaces_untap() {
1871        let mut game = GameState::new(&["Alice", "Bob"], 20);
1872        let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
1873        game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
1874        game.tap(cid);
1875        game.card_mut(cid)
1876            .add_counter(&CounterType::Named("STUN".to_string()), 1);
1877
1878        assert!(!game.untap(cid));
1879        assert!(game.card(cid).tapped);
1880        assert_eq!(
1881            game.card(cid)
1882                .counter_count(&CounterType::Named("STUN".to_string())),
1883            0
1884        );
1885    }
1886}