Skip to main content

manabrew_engine/ability/effects/
play_effect.rs

1use forge_foundation::ZoneType;
2
3use super::EffectContext;
4use crate::agent::{GameEntity, GameLogEvent};
5use crate::event::RunParams;
6use crate::ids::CardId;
7use crate::spellability::{SpellAbility, StackEntry};
8use crate::trigger::TriggerType;
9
10/// Struct form of this effect so it can participate in the
11/// `SpellAbilityEffect` trait hierarchy
12#[manabrew_engine_macros::spell_effect(PlayEffect)]
13fn resolve(ctx: &mut EffectContext, sa: &crate::spellability::SpellAbility) {
14    let mut candidates = resolve_target_cards(ctx, sa);
15    candidates.retain(|&cid| ctx.game.card(cid).zone != ZoneType::Stack);
16    if candidates.is_empty() {
17        return;
18    }
19
20    let controller = sa.activating_player;
21    let without_mana_cost = sa.ir.without_mana_cost;
22    let play_cost = sa.ir.play_cost_text.clone();
23    let remember = sa.ir.remember_played;
24    let optional = sa.ir.optional;
25    let is_madness = sa.ir.play_cost_text.is_some()
26        && sa
27            .source
28            .is_some_and(|src| ctx.game.card(src).has_keyword("Madness"));
29
30    // ── Step 1: Choose card
31    // For single-card + optional: isOptional=false (auto-pick), then confirmAction below.
32    let single_option = candidates.len() == 1 && optional;
33    let tgt_cards: Vec<_> = candidates.iter().copied().map(GameEntity::Card).collect();
34    let chosen = ctx.agents[controller.index()].choose_single_entity_for_effect(
35        controller,
36        &tgt_cards,
37        !single_option && optional,
38    );
39    let card_id = match chosen {
40        Some(GameEntity::Card(cid)) => cid,
41        None => return,
42        Some(GameEntity::Player(_)) => return,
43    };
44
45    // ── Step 2: Optional confirm — Java only asks the outer "Do you want
46    // to play X?" prompt in the single-option case (`PlayEffect.java:250`).
47    // For multi-option, the chooser at Step 1 already lets the player decline
48    // by returning `None`. The non-mandatory-cost confirm below is separate.
49    if single_option {
50        let card_name = ctx.game.card(card_id).card_name.clone();
51        let accepted = ctx.agents[controller.index()].confirm_action(
52            controller,
53            None,
54            &format!("Do you want to play {card_name}?"),
55            &[],
56            Some(card_id),
57            Some(crate::ability::api_type::ApiType::Play),
58        );
59        if !accepted {
60            return;
61        }
62    }
63
64    // ── Step 3: Get ability to play
65    let spell_sa_base =
66        crate::spellability::build_spell_ability_for_card_cast(ctx.game, card_id, controller);
67    let abilities = vec![spell_sa_base];
68    let sa_idx = ctx.agents[controller.index()].get_ability_to_play(controller, &abilities);
69    let mut spell_sa = match sa_idx {
70        Some(idx) => abilities.into_iter().nth(idx).unwrap(),
71        None => return,
72    };
73
74    // ── Step 3: Cost replacement ────────────────────────────────────
75    if without_mana_cost {
76        if let Some(ref mut cost) = spell_sa.pay_costs {
77            cost.parts
78                .retain(|part| !matches!(part, crate::cost::CostPart::Mana { .. }));
79        }
80    } else if let Some(ref cost_str) = play_cost {
81        let alt_mc = forge_foundation::ManaCost::parse(cost_str);
82        if let Some(ref existing) = spell_sa.pay_costs {
83            spell_sa.pay_costs = Some(existing.copy_with_defined_mana(alt_mc));
84        }
85    }
86
87    // ── Step 4: Alt-cost flags ──────────────────────────────────────
88    if is_madness {
89        spell_sa.alt_cost = Some(crate::spellability::AlternativeCost::Madness);
90    }
91
92    if let Some(ref mut cost) = spell_sa.pay_costs {
93        cost.mandatory = true;
94    }
95
96    // Remove zone restriction — allow casting from exile/library/etc.
97    spell_sa.ir.cast_from_play_effect = true;
98    spell_sa.ir.without_mana_cost = without_mana_cost;
99    let restriction_host =
100        crate::staticability::static_ability_cant_be_cast::restriction_host(ctx.game.card(card_id));
101    if crate::staticability::static_ability_cant_be_cast::cant_be_cast_ability_in_context(
102        &ctx.game.cards,
103        &spell_sa,
104        &restriction_host,
105        controller,
106        Some(ctx.game),
107    ) {
108        return;
109    }
110
111    if !spell_sa.setup_targets(ctx.game, ctx.agents, ctx.mana_pools) {
112        return;
113    }
114
115    let mut cost = spell_sa
116        .pay_costs
117        .take()
118        .unwrap_or_else(|| crate::cost::parse_cost(""));
119    let base_mana = if without_mana_cost {
120        forge_foundation::ManaCost::parse("0")
121    } else if let Some(cost) = play_cost.as_deref() {
122        forge_foundation::ManaCost::parse(cost)
123    } else {
124        ctx.game.card(card_id).mana_cost.clone()
125    };
126    let targets: Vec<_> = spell_sa.target_chosen.target_card.into_iter().collect();
127    let card = ctx.game.card(card_id);
128    let adjustment = crate::cost::cost_adjustment::compute_cost_adjustment_for_payment(
129        ctx.game, card, controller, card.zone, &targets,
130    );
131    if let Some(raise_cost) = crate::cost::cost_adjustment::compute_raise_cost_parts_with_targets(
132        ctx.game, card, controller, card.zone, &targets,
133    ) {
134        cost.parts.extend(
135            raise_cost
136                .parts
137                .into_iter()
138                .filter(|part| !matches!(part, crate::cost::CostPart::Mana { .. })),
139        );
140    }
141    let cost = cost.copy_with_defined_mana(adjustment.apply(&base_mana));
142    if !super::cost_payment::try_pay_unless_cost(ctx, &spell_sa, card_id, controller, &cost) {
143        return;
144    }
145    spell_sa.pay_costs = Some(cost);
146
147    // `ReplaceGraveyard$ <Zone>` — install a one-shot replacement that
148    // reroutes the played card if it would be put into the graveyard
149    // (e.g. Diviner of Mist exiles the spell on resolve).
150    if let Some(zone) = sa.ir.replace_graveyard.clone() {
151        let host_card = sa.source.unwrap_or(card_id);
152        add_replace_graveyard_effect(ctx, card_id, host_card, sa, &zone);
153    }
154
155    // ── Step 7: Push to stack ───────────────────────────────────────
156    let label = if is_madness {
157        "Madness"
158    } else if without_mana_cost {
159        "Rebound"
160    } else {
161        "Play"
162    };
163    push_spell_to_stack(ctx, card_id, spell_sa, label);
164
165    // ── Step 8: RememberPlayed ──────────────────────────────────────
166    if remember {
167        if let Some(source_id) = sa.source {
168            ctx.game.card_mut(source_id).remembered_cards.push(card_id);
169        }
170    }
171}
172
173// ── Helpers ───────────────────────────────────────────────────────────
174
175/// Resolve the target cards from `Valid$` or `Defined$` parameters.
176fn resolve_target_cards(ctx: &EffectContext, sa: &SpellAbility) -> Vec<CardId> {
177    if let Some(valid) = crate::parsing::raw_get(&sa.ability_text, crate::parsing::keys::VALID) {
178        let zones = crate::parsing::raw_get(&sa.ability_text, crate::parsing::keys::VALID_ZONE)
179            .map(|raw| {
180                raw.split(',')
181                    .filter_map(|part| crate::zone::zone_type::smart_value_of(part.trim()))
182                    .collect::<Vec<_>>()
183            })
184            .filter(|zones| !zones.is_empty())
185            .unwrap_or_else(|| vec![ZoneType::Hand]);
186        let Some(source_id) = sa.source else {
187            return Vec::new();
188        };
189        let source = ctx.game.card(source_id);
190        let selector = crate::parsing::cached_compiled_selector(valid);
191        let valid_sa = crate::parsing::raw_get(&sa.ability_text, crate::parsing::keys::VALID_SA);
192        return ctx
193            .game
194            .cards
195            .iter()
196            .filter(|card| zones.contains(&card.zone))
197            .filter(|card| {
198                crate::card::valid_filter::matches_valid_card_selector_in_game(
199                    &selector, card, source, ctx.game,
200                )
201            })
202            .filter(|card| {
203                if valid_sa.is_some_and(|v| v.eq_ignore_ascii_case("Spell")) {
204                    !card.is_land()
205                } else {
206                    true
207                }
208            })
209            .map(|card| card.id)
210            .collect();
211    }
212
213    let defined = sa.ir.defined_text.clone().unwrap_or_default();
214    if let Some(uid_str) = defined.strip_prefix("CardUID_") {
215        uid_str
216            .parse::<u32>()
217            .ok()
218            .map(CardId)
219            .into_iter()
220            .collect()
221    } else {
222        let defined = if defined.is_empty() {
223            "Self"
224        } else {
225            defined.as_str()
226        };
227        crate::ability::ability_utils::get_defined_cards(
228            ctx.game,
229            sa.source,
230            defined,
231            Some(sa.activating_player),
232        )
233    }
234}
235
236/// Push the spell onto the stack and fire SpellCast trigger.
237fn push_spell_to_stack(
238    ctx: &mut EffectContext,
239    card_id: CardId,
240    spell_sa: SpellAbility,
241    label: &str,
242) {
243    let controller = spell_sa.activating_player;
244    let is_creature = ctx.game.card(card_id).is_creature();
245    let is_permanent = ctx.game.card(card_id).is_permanent();
246    let cast_zone = Some(ctx.game.card(card_id).zone);
247    let card_name = ctx.game.card(card_id).card_name.clone();
248    let chosen_target = spell_sa.target_chosen.target_card;
249
250    let entry = StackEntry {
251        id: 0,
252        spell_ability: spell_sa,
253        is_pending_cast: false,
254        is_creature_spell: is_creature,
255        is_permanent_spell: is_permanent,
256        cast_from_zone: cast_zone,
257        optional_trigger_decider: None,
258        optional_trigger_description: None,
259        optional_trigger_source_name: None,
260    };
261    let trigger_sa = entry.spell_ability.clone();
262
263    ctx.game.card_mut(card_id).cast_sa = Some(Box::new(trigger_sa.clone()));
264    ctx.game.card_mut(card_id).cast_from = cast_zone;
265    ctx.game.stack.push(entry);
266    ctx.move_card(card_id, ZoneType::Stack, controller);
267    ctx.game.player_record_spell_cast(controller, card_id);
268
269    ctx.trigger_handler.run_trigger(
270        TriggerType::SpellCast,
271        RunParams {
272            spell_card: Some(card_id),
273            spell_controller: Some(controller),
274            source_sa: Some(trigger_sa.clone()),
275            ..Default::default()
276        },
277        false,
278    );
279    super::emit_targeting_triggers(ctx, card_id, &trigger_sa);
280
281    let mut event = GameLogEvent::stack(format!("{label}: cast {card_name}"))
282        .with_player(controller)
283        .with_source_card(card_id);
284    if let Some(target_id) = chosen_target {
285        event = event.with_target_card(target_id);
286    }
287    crate::agent::notify_all_agents(ctx.agents, event);
288}
289
290/// Create a one-shot replacement effect on a Command-zone effect card that
291/// reroutes `card_id` to `dest_zone` if it would be put into the graveyard
292/// from the stack (e.g. Diviner of Mist's `ReplaceGraveyard$ Exile`).
293pub fn add_replace_graveyard_effect(
294    ctx: &mut EffectContext,
295    card_id: CardId,
296    _host_card: CardId,
297    sa: &SpellAbility,
298    zone: &str,
299) {
300    let controller = sa.activating_player;
301    let dest_zone = if zone.is_empty() { "Exile" } else { zone };
302
303    let mut effect = crate::player::player_factory_util::new_player_effect_card(
304        controller,
305        "ReplaceGraveyard Effect",
306        None,
307    );
308    effect.remembered_cards.push(card_id);
309    let raw = format!(
310        "R$ Event$ Moved | ValidCard$ Card.IsRemembered | Origin$ Stack | Destination$ Graveyard | NewDestination$ {dest_zone} | ForgetOnMoved$ Origin | Description$ If that card would be put into your graveyard this turn, put it into {dest_zone} instead."
311    );
312    crate::player::player_factory_util::add_replacement_effect(&mut effect, &raw);
313    effect.exile_when_no_remembered = true;
314    effect.forget_on_moved_origin = Some(ZoneType::Stack);
315
316    let effect_id = ctx.game.create_card(effect);
317    ctx.game.move_card(effect_id, ZoneType::Command, controller);
318}