1use std::collections::BTreeMap;
36
37use forge_foundation::{CardTypeLine, CoreType, Supertype, ZoneType};
38
39use crate::agent::PlayerAgent;
40use crate::game::GameState;
41use crate::ids::{CardId, PlayerId};
42use crate::replacement::replacement_effect::ReplacementType;
43use crate::staticability::{CardFilter, Layer, StaticAbility, StaticMode};
44
45struct PendingEffect {
49 layer: Layer,
51 target: CardId,
53 kind: EffectKind,
55}
56
57enum EffectKind {
58 SetController {
59 controller: PlayerId,
60 },
61 AddPT {
62 power: i32,
63 toughness: i32,
64 },
65 SetPT {
66 power: Option<i32>,
67 toughness: Option<i32>,
68 },
69 RemoveAllCardTraits {
70 timestamp: i64,
71 static_id: i64,
72 },
73 GrantKeyword {
74 keyword: String,
75 timestamp: i64,
76 static_id: i64,
77 },
78 GrantAbility {
80 text: String,
81 svars: BTreeMap<String, String>,
82 },
83 AddType(String),
85 GrantTrigger {
87 text: String,
88 svars: BTreeMap<String, String>,
89 },
90}
91
92pub fn classify_static_layers(sa: &StaticAbility) -> Vec<Layer> {
100 if !sa.check_mode(&StaticMode::Continuous) {
101 return Vec::new();
102 }
103
104 let ir = &sa.ir;
105 let mut layers = Vec::new();
106
107 push_layer(&mut layers, ir.gain_control_param, Layer::Control);
108 push_layer(&mut layers, ir.has_text_layer_key, Layer::Text);
109 push_layer(&mut layers, ir.has_type_layer_key, Layer::Type);
110 push_layer(&mut layers, ir.has_color_layer_key, Layer::Color);
111 push_layer(&mut layers, ir.has_ability_layer_key, Layer::Ability);
112
113 if ir.set_power || ir.set_toughness {
114 if ir.characteristic_defining {
115 push_unique_layer(&mut layers, Layer::Characteristic);
116 } else {
117 push_unique_layer(&mut layers, Layer::SetPT);
118 }
119 }
120
121 push_layer(
122 &mut layers,
123 ir.add_power || ir.add_toughness,
124 Layer::ModifyPT,
125 );
126 push_layer(&mut layers, ir.has_rules_layer_key, Layer::Rules);
127
128 if layers.is_empty() {
129 layers.push(Layer::Rules);
130 }
131
132 layers
133}
134
135fn push_layer(layers: &mut Vec<Layer>, condition: bool, layer: Layer) {
136 if condition {
137 push_unique_layer(layers, layer);
138 }
139}
140
141fn static_layer_trait_id(source_id: CardId, sa_idx: usize) -> i64 {
142 -(((source_id.index() as i64) + 1) * 10_000 + sa_idx as i64 + 1)
143}
144
145fn push_unique_layer(layers: &mut Vec<Layer>, layer: Layer) {
146 if !layers.contains(&layer) {
147 layers.push(layer);
148 }
149}
150
151fn type_line_has_token(type_line: &CardTypeLine, token: &str) -> bool {
152 if let Some(st) = Supertype::from_name(token) {
153 return type_line.supertypes.contains(&st);
154 }
155 if let Some(ct) = CoreType::from_name(token) {
156 return type_line.core_types.contains(&ct);
157 }
158 type_line
159 .subtypes
160 .iter()
161 .any(|subtype| subtype.eq_ignore_ascii_case(token))
162}
163
164pub fn apply_continuous_effects(game: &mut GameState) {
176 let _perf_timer = crate::perf::ScopeTimer::start(
177 crate::perf::Metric::ContinuousEffectsCalls,
178 crate::perf::Metric::ContinuousEffectsNs,
179 );
180 let _params_lookup_scope =
181 crate::perf::ParamsLookupScopeGuard::enter(crate::perf::ParamsLookupScope::Continuous);
182 for card in game.cards.iter_mut() {
184 card.clear_static_layer_changed_card_traits();
185 if card.activated_abilities.len() > card.base_ability_count {
188 card.activated_abilities.truncate(card.base_ability_count);
189 }
190 for (ability_idx, ability) in card.activated_abilities.iter_mut().enumerate() {
191 ability.ability_index = ability_idx;
192 }
193 let intrinsic_trigger_count = card.base_trigger_count + card.pump_trigger_count;
194 if card.triggers.len() > intrinsic_trigger_count {
195 card.triggers.truncate(intrinsic_trigger_count);
196 }
197 card.static_power_modifier = 0;
198 card.static_toughness_modifier = 0;
199 if !card.face_down {
201 card.static_set_power = None;
202 card.static_set_toughness = None;
203 }
204 card.granted_keywords.clear();
205 card.granted_svars.clear();
206 if let Some(type_line) = card.static_type_line_base.take() {
208 card.set_type_line(type_line);
209 }
210 card.static_added_subtypes.clear();
211 card.cant_attack_static = false;
212 card.cant_block_static = false;
213 }
214 for player in game.players.iter_mut() {
215 player.max_land_plays_per_turn = 1;
216 player.unlimited_land_plays = false;
217 }
218
219 for card in game.cards.iter_mut() {
222 if card.zone == ZoneType::Battlefield
223 && card.has_keyword("Unleash")
224 && card.counter_count(&crate::card::CounterType::P1P1) > 0
225 {
226 card.cant_block_static = true;
227 }
228 }
229
230 for player_idx in 0..game.player_order.len() {
231 let pid = game.player_order[player_idx];
232 let player = game.player_mut(pid);
233 player.max_hand_size = 7;
234 player.unlimited_hand_size = false;
235 }
236 let player_ids: Vec<PlayerId> = game.player_order.clone();
237 for &pid in &player_ids {
238 let battlefield_cards: Vec<CardId> =
239 game.cards_in_zone(ZoneType::Battlefield, pid).to_vec();
240 for source_id in battlefield_cards {
241 let static_ability_count = game.card(source_id).static_abilities.len();
242 for sa_idx in 0..static_ability_count {
243 let card = game.card(source_id);
244 let sa = &card.static_abilities[sa_idx];
245 if !sa.check_conditions(card, game) {
246 continue;
247 }
248 if !sa.check_mode(&StaticMode::Continuous) {
249 continue;
250 }
251 let affected = sa.ir.affected_text.as_deref().unwrap_or("");
252 if !affected.eq_ignore_ascii_case("You") {
253 continue;
254 }
255 let controller = card.controller;
256 let set_value = sa.ir.set_max_hand_size.clone();
257 let raise_value = sa.ir.raise_max_hand_size.clone();
258 if let Some(value) = set_value {
259 let player = game.player_mut(controller);
260 if value.eq_ignore_ascii_case("Unlimited") {
261 player.unlimited_hand_size = true;
262 } else if let Ok(n) = value.parse::<i32>() {
263 player.max_hand_size = n;
264 }
265 }
266 if let Some(value) = raise_value {
267 if let Ok(n) = value.parse::<i32>() {
268 let player = game.player_mut(controller);
269 player.max_hand_size = player.max_hand_size.saturating_add(n);
270 }
271 }
272 }
273 }
274 }
275
276 let mut pending: Vec<PendingEffect> = Vec::new();
278 let mut cant_attack_targets: Vec<CardId> = Vec::new();
279 let mut cant_block_targets: Vec<CardId> = Vec::new();
280 let mut granted_player_rules: Vec<(CardId, StaticAbility)> = Vec::new();
281
282 let source_ids: Vec<CardId> = game.cards.iter().map(|card| card.id).collect();
283 for source_id in source_ids {
284 let static_ability_count = game.card(source_id).static_abilities.len();
285
286 for sa_idx in 0..static_ability_count {
287 let source_card = game.card(source_id).clone();
288 let sa = game.card(source_id).static_abilities[sa_idx].clone();
289
290 if !sa.check_conditions(&source_card, game) {
293 continue;
294 }
295
296 if sa.check_mode(&StaticMode::Continuous) {
297 apply_player_rules_effects(game, source_id, &sa);
298 }
299
300 let is_cda = sa.ir.characteristic_defining;
303
304 let affected_str = sa
306 .ir
307 .affected_text
308 .as_deref()
309 .or(sa.ir.valid_cards_text.as_deref())
310 .or(sa.ir.valid_card_text.as_deref())
311 .unwrap_or("Creature.YouControl");
312
313 let mut apply_to_target = |target: CardId| {
314 if sa.check_mode(&StaticMode::Continuous) {
315 if let Some(gain_control) = sa.ir.gain_control_text.as_deref() {
316 let new_controller = match gain_control {
317 "You" | "YouCtrl" => Some(source_card.controller),
318 "Opponent" => Some(game.opponent_of(source_card.controller)),
319 _ => None,
320 };
321 if let Some(controller) = new_controller {
322 pending.push(PendingEffect {
323 layer: Layer::Control,
324 target,
325 kind: EffectKind::SetController { controller },
326 });
327 }
328 }
329
330 let add_power = sa.ir.add_power_text.as_deref();
331 let add_toughness = sa.ir.add_toughness_text.as_deref();
332 if add_power.is_some() || add_toughness.is_some() {
333 let p = resolve_add_pt_value(game, source_id, add_power);
334 let t = resolve_add_pt_value(game, source_id, add_toughness);
335 pending.push(PendingEffect {
336 layer: Layer::ModifyPT,
337 target,
338 kind: EffectKind::AddPT {
339 power: p,
340 toughness: t,
341 },
342 });
343 }
344
345 let add_type = sa.ir.add_type_text.as_deref();
346 let source = game.card(source_id);
347 for added_type in resolve_added_types(source, add_type) {
348 pending.push(PendingEffect {
349 layer: Layer::Type,
350 target,
351 kind: EffectKind::AddType(added_type),
352 });
353 }
354
355 let set_power = sa.ir.set_power_text.as_deref();
356 let set_toughness = sa.ir.set_toughness_text.as_deref();
357 if set_power.is_some() || set_toughness.is_some() {
358 let sp = resolve_set_pt_value(game, source_id, set_power);
359 let st = resolve_set_pt_value(game, source_id, set_toughness);
360 let layer = if is_cda {
363 Layer::Characteristic
364 } else {
365 Layer::SetPT
366 };
367 pending.push(PendingEffect {
368 layer,
369 target,
370 kind: EffectKind::SetPT {
371 power: sp,
372 toughness: st,
373 },
374 });
375 }
376
377 if let Some(kws) = sa.ir.add_keyword_text.as_deref() {
378 for kw in kws.split('&').map(str::trim).filter(|s| !s.is_empty()) {
380 pending.push(PendingEffect {
381 layer: Layer::Ability,
382 target,
383 kind: EffectKind::GrantKeyword {
384 keyword: kw.to_string(),
385 timestamp: source_card.zone_timestamp as i64,
386 static_id: static_layer_trait_id(source_id, sa_idx),
387 },
388 });
389 }
390 }
391
392 if sa.ir.remove_all_abilities {
393 pending.push(PendingEffect {
394 layer: Layer::Ability,
395 target,
396 kind: EffectKind::RemoveAllCardTraits {
397 timestamp: source_card.zone_timestamp as i64,
398 static_id: static_layer_trait_id(source_id, sa_idx),
399 },
400 });
401 }
402
403 if let Some(svar_name) = sa.ir.add_ability_text.as_deref() {
408 if let Some(ab_text) = source_card.svars.get(svar_name).cloned() {
409 pending.push(PendingEffect {
410 layer: Layer::Ability,
411 target,
412 kind: EffectKind::GrantAbility {
413 text: ab_text,
414 svars: source_card.svars.clone(),
415 },
416 });
417 }
418 }
419
420 if let Some(add_trigger) = sa.ir.add_trigger_text.as_deref() {
421 for svar_name in add_trigger
422 .split(" & ")
423 .map(str::trim)
424 .filter(|s| !s.is_empty())
425 {
426 if let Some(trig_text) = source_card.svars.get(svar_name).cloned() {
427 pending.push(PendingEffect {
428 layer: Layer::Ability,
429 target,
430 kind: EffectKind::GrantTrigger {
431 text: trig_text,
432 svars: source_card.svars.clone(),
433 },
434 });
435 }
436 }
437 }
438
439 if let Some(add_static) = sa.ir.add_static_ability_text.as_deref() {
440 for svar_name in add_static
441 .split(" & ")
442 .map(str::trim)
443 .filter(|s| !s.is_empty())
444 {
445 if let Some(static_text) = source_card.svars.get(svar_name).cloned() {
446 if let Some(granted) =
447 crate::staticability::parse_static_ability(&static_text)
448 {
449 granted_player_rules.push((target, granted));
450 }
451 }
452 }
453 }
454
455 for subtype in resolve_added_basic_land_types(&source_card, add_type) {
456 if let Some(ab_text) = basic_land_mana_ability_text(&subtype) {
457 pending.push(PendingEffect {
458 layer: Layer::Ability,
459 target,
460 kind: EffectKind::GrantAbility {
461 text: ab_text.to_string(),
462 svars: BTreeMap::new(),
463 },
464 });
465 }
466 }
467 }
468
469 if sa.check_mode(&StaticMode::CantAttack) {
470 cant_attack_targets.push(target);
471 }
472 if sa.check_mode(&StaticMode::CantBlock) {
473 cant_block_targets.push(target);
474 }
475 };
476
477 if is_cda {
478 if source_card.zone == ZoneType::Battlefield {
480 apply_to_target(source_id);
481 }
482 } else if let Some(defined) = sa.ir.affected_defined_text.as_deref() {
483 for target in crate::ability::ability_utils::get_defined_cards(
484 game,
485 Some(source_id),
486 defined,
487 Some(source_card.controller),
488 ) {
489 let card = game.card(target);
490 if !card.phased_out
491 && crate::card::valid_filter::matches_valid_card_selector_opt_in_game(
492 sa.ir.affected.as_ref(),
493 card,
494 &source_card,
495 game,
496 )
497 {
498 apply_to_target(target);
499 }
500 }
501 } else if affected_str.eq_ignore_ascii_case("Card.Self")
502 || affected_str.starts_with("Card.Self+")
503 {
504 if source_card.zone == ZoneType::Battlefield
511 && crate::card::valid_filter::matches_valid_card(
512 affected_str,
513 &source_card,
514 &source_card,
515 )
516 {
517 apply_to_target(source_id);
518 }
519 } else if affected_str.eq_ignore_ascii_case("Card.EnchantedBy")
520 || affected_str.contains(".EquippedBy")
521 || affected_str.contains(".EnchantedBy")
522 {
523 if let Some(cid) = source_card.attached_to {
529 if game.card(cid).zone == ZoneType::Battlefield {
530 apply_to_target(cid);
531 }
532 }
533 } else {
534 let filter = CardFilter::parse(affected_str);
535 let affected_zones = if sa.ir.affected_zones.is_empty() {
538 None
539 } else {
540 Some(sa.ir.affected_zones.as_slice())
541 };
542 for card in &game.cards {
543 let zone_matches = match &affected_zones {
544 Some(zones) => zones.contains(&card.zone),
545 None => card.zone == ZoneType::Battlefield,
546 };
547 if zone_matches && filter.matches_with_game(card, &source_card, game) {
548 apply_to_target(card.id);
549 }
550 }
551 }
552 }
553 }
554
555 for (source_id, granted) in granted_player_rules {
556 apply_player_rules_effects(game, source_id, &granted);
557 }
558
559 for target in cant_attack_targets {
560 game.cards[target.index()].cant_attack_static = true;
561 }
562 for target in cant_block_targets {
563 game.cards[target.index()].cant_block_static = true;
564 }
565
566 pending.sort_by_key(|e| e.layer);
571
572 for effect in pending {
573 match effect.kind {
574 EffectKind::SetController { controller } => {
575 game.change_controller(effect.target, controller);
576 }
577 EffectKind::AddPT { power, toughness } => {
578 let card = &mut game.cards[effect.target.index()];
579 card.static_power_modifier += power;
580 card.static_toughness_modifier += toughness;
581 }
582 EffectKind::SetPT { power, toughness } => {
583 let card = &mut game.cards[effect.target.index()];
584 if let Some(p) = power {
588 card.static_set_power = Some(p);
589 }
590 if let Some(t) = toughness {
591 card.static_set_toughness = Some(t);
592 }
593 }
594 EffectKind::RemoveAllCardTraits {
595 timestamp,
596 static_id,
597 } => {
598 game.cards[effect.target.index()].add_changed_card_traits(
599 crate::card::card_trait_changes::CardTraitChanges::remove_all_layer(
600 Vec::new(),
601 Vec::new(),
602 Vec::new(),
603 Vec::new(),
604 ),
605 timestamp,
606 static_id,
607 );
608 }
609 EffectKind::GrantKeyword {
610 keyword: kw,
611 timestamp,
612 static_id,
613 } => {
614 let card = &mut game.cards[effect.target.index()];
615 card.add_changed_card_keyword_at(&kw, timestamp, static_id);
616 if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(&kw, "Ward") {
617 let next_id = card
618 .triggers
619 .iter()
620 .map(|t| t.id)
621 .max()
622 .unwrap_or(0)
623 .saturating_add(1);
624 let mut next_id_mut = next_id;
625 let execute = format!("TrigWardGranted{next_id}");
626 let raw = format!(
627 "Mode$ BecomesTarget | ValidSource$ SpellAbility.OppCtrl | ValidTarget$ Card.Self | Secondary$ True | Execute$ {execute} | TriggerZones$ Battlefield | TriggerDescription$ Ward"
628 );
629 if let Some(mut trig) = crate::trigger::parse_trigger(&raw, &mut next_id_mut) {
630 trig.execute = execute.clone();
631 card.add_trigger(trig);
632 }
633 card.granted_svars.insert(
634 execute,
635 format!(
636 "DB$ Counter | Defined$ TriggeredSourceSA | UnlessCost$ {cost_str}"
637 ),
638 );
639 }
640 }
641 EffectKind::AddType(t) => {
642 let card = &mut game.cards[effect.target.index()];
643 if !type_line_has_token(&card.type_line, &t) {
644 if card.static_type_line_base.is_none() {
645 card.static_type_line_base = Some(card.type_line.clone());
646 }
647 card.add_type(&t);
648 card.static_added_subtypes.push(t);
649 }
650 }
651 EffectKind::GrantAbility { text, svars } => {
652 game.cards[effect.target.index()]
655 .granted_svars
656 .extend(svars);
657 let target_idx = effect.target.index();
658 let next_idx = game.cards[target_idx].activated_abilities.len();
659 if let Some(ab) =
660 crate::ability::activated::parse_activated_ability(&text, next_idx)
661 {
662 game.cards[target_idx].activated_abilities.push(ab);
663 }
664 }
665 EffectKind::GrantTrigger { text, svars } => {
666 game.cards[effect.target.index()]
667 .granted_svars
668 .extend(svars);
669 let next_id = game.cards[effect.target.index()]
670 .triggers
671 .iter()
672 .map(|t| t.id)
673 .max()
674 .unwrap_or(0)
675 .saturating_add(1);
676 let mut next_id_mut = next_id;
677 if let Some(trig) = crate::trigger::parse_trigger(&text, &mut next_id_mut) {
678 game.cards[effect.target.index()].add_trigger(trig);
679 }
680 }
681 }
682 }
683
684 for card in game.cards.iter_mut() {
687 if card.zone == ZoneType::Battlefield {
688 card.generate_basic_land_mana_abilities();
689 }
690 }
691}
692
693fn apply_player_rules_effects(game: &mut GameState, source_id: CardId, sa: &StaticAbility) {
694 let Some(adjust_land_plays) = sa.ir.adjust_land_plays_text.as_deref() else {
695 return;
696 };
697 let affected_players = affected_players_for_static(game, source_id, sa);
698 if affected_players.is_empty() {
699 return;
700 }
701 if adjust_land_plays.eq_ignore_ascii_case("Unlimited") {
702 for player in affected_players {
703 game.player_mut(player).unlimited_land_plays = true;
704 }
705 return;
706 }
707 let amount = resolve_rules_amount(game, source_id, adjust_land_plays);
708 for player in affected_players {
709 game.player_mut(player).max_land_plays_per_turn += amount;
710 }
711}
712
713fn affected_players_for_static(
714 game: &GameState,
715 source_id: CardId,
716 sa: &StaticAbility,
717) -> Vec<PlayerId> {
718 let Some(affected) = sa.ir.affected_text.as_deref() else {
719 return Vec::new();
720 };
721 let source = game.card(source_id);
722 game.player_order
723 .iter()
724 .copied()
725 .filter(|&player| {
726 !sa.ignore_effect_players.contains(&player)
727 && crate::card::valid_filter::matches_valid(
728 affected,
729 None,
730 Some(player),
731 source,
732 source.controller,
733 )
734 })
735 .collect()
736}
737
738fn resolve_rules_amount(game: &GameState, source_id: CardId, value: &str) -> i32 {
739 if let Ok(n) = value.trim().parse::<i32>() {
740 return n;
741 }
742 let source = game.card(source_id);
743 if let Some(svar_expr) = source.svars.get(value.trim()) {
744 if svar_expr.starts_with("Count$") {
745 return crate::ability::effects::resolve_count_svar(
746 svar_expr,
747 game,
748 source_id,
749 source.controller,
750 );
751 }
752 return crate::ability::effects::evaluate_svar(
753 svar_expr,
754 &crate::spellability::SpellAbility::new_empty(Some(source_id), source.controller),
755 );
756 }
757 0
758}
759
760pub fn apply_etb_tapped(game: &mut GameState, entering_card: CardId) {
770 apply_etb_tapped_with_agents(game, entering_card, None);
771}
772
773fn applicable_etb_tapped_replacement_sources(
774 game: &GameState,
775 entering_card: CardId,
776) -> Vec<(CardId, String)> {
777 let mut repl_sources: Vec<(CardId, String, String)> = Vec::new();
778 for c in &game.cards {
779 if c.zone != ZoneType::Battlefield {
780 continue;
781 }
782 for re in &c.replacement_effects {
783 if re.event == ReplacementType::Moved
784 && re.replace_with() == Some("ETBTapped")
785 && re.ir.destination_zone == Some(ZoneType::Battlefield)
786 && re.active_in_zone(ZoneType::Battlefield)
787 {
788 let filter = re
789 .ir
790 .valid_card_text
791 .as_deref()
792 .unwrap_or("Card.Self")
793 .to_string();
794 let desc = re.description(c, game);
795 repl_sources.push((c.id, filter, desc));
796 }
797 }
798 }
799
800 repl_sources
801 .into_iter()
802 .filter_map(|(source_id, filter_str, desc)| {
803 let tapped = if filter_str == "Card.Self" || filter_str.is_empty() {
804 source_id == entering_card
805 } else {
806 let source = &game.cards[source_id.index()];
807 let filter = CardFilter::parse(&filter_str);
808 filter.matches_with_game(&game.cards[entering_card.index()], source, game)
809 };
810 tapped.then_some((source_id, desc))
811 })
812 .collect()
813}
814
815pub fn prompt_etb_tapped_replacement_with_agents(
816 game: &mut GameState,
817 entering_card: CardId,
818 agents: &mut [Box<dyn PlayerAgent>],
819) {
820 let applicable = applicable_etb_tapped_replacement_sources(game, entering_card);
821 if applicable.len() <= 1 {
822 return;
823 }
824
825 let affected_player = game.cards[entering_card.index()].controller;
826 let descriptions: Vec<String> = applicable
827 .iter()
828 .map(|(source_id, desc)| format!("{}: {}", game.card(*source_id).card_name, desc))
829 .collect();
830 let _chosen = agents[affected_player.index()]
831 .choose_single_replacement_effect(affected_player, &descriptions)
832 .min(applicable.len().saturating_sub(1));
833}
834
835pub fn apply_etb_tapped_with_agents(
836 game: &mut GameState,
837 entering_card: CardId,
838 agents: Option<&mut [Box<dyn PlayerAgent>]>,
839) {
840 let etb_sources: Vec<(CardId, String)> = game
843 .cards
844 .iter()
845 .filter(|c| c.zone == ZoneType::Battlefield)
846 .flat_map(|c| {
847 c.static_abilities.iter().filter_map(move |sa| {
848 if sa.check_mode(&StaticMode::ETBTapped) {
849 let filter_str = sa
850 .ir
851 .valid_cards_text
852 .clone()
853 .or_else(|| sa.ir.affected_text.clone())
854 .unwrap_or_else(|| "Card.Self".to_string());
856 Some((c.id, filter_str))
857 } else {
858 None
859 }
860 })
861 })
862 .collect();
863
864 for (source_id, filter_str) in etb_sources {
865 let tapped = if filter_str == "Card.Self" || filter_str.is_empty() {
867 source_id == entering_card
868 } else {
869 let source = &game.cards[source_id.index()];
870 let filter = CardFilter::parse(&filter_str);
871 filter.matches_with_game(&game.cards[entering_card.index()], source, game)
872 };
873
874 if tapped {
875 game.cards[entering_card.index()].tapped = true;
876 return; }
878 }
879
880 let applicable = applicable_etb_tapped_replacement_sources(game, entering_card);
885 if applicable.is_empty() {
886 return;
887 }
888
889 if let Some(agents) = agents {
890 prompt_etb_tapped_replacement_with_agents(game, entering_card, agents);
891 }
892
893 game.cards[entering_card.index()].tapped = true;
894}
895
896pub fn get_etb_unless_life_cost(card: &crate::card::Card) -> Option<i32> {
904 for re in &card.replacement_effects {
905 if re.event != ReplacementType::Moved {
906 continue;
907 }
908 if re.ir.destination_zone != Some(ZoneType::Battlefield) {
909 continue;
910 }
911 if let Some(svar_name) = re.replace_with() {
912 if svar_name == "ETBTapped" {
913 continue;
914 }
915 if let Some(svar_val) = card.svars.get(svar_name) {
916 if svar_val.contains("DB$ Tap") && svar_val.contains("ETB$ True") {
917 if let Some(pos) = svar_val.find("PayLife<") {
919 let after = &svar_val[pos + 8..]; if let Some(end) = after.find('>') {
921 if let Ok(n) = after[..end].parse::<i32>() {
922 return Some(n);
923 }
924 }
925 }
926 }
927 }
928 }
929 }
930 None
931}
932
933pub fn get_etb_unless_reveal_cost(card: &crate::card::Card) -> Option<(i32, String)> {
940 for re in &card.replacement_effects {
941 if re.event != ReplacementType::Moved {
942 continue;
943 }
944 if re.ir.destination_zone != Some(ZoneType::Battlefield) {
945 continue;
946 }
947 if let Some(svar_name) = re.replace_with() {
948 if svar_name == "ETBTapped" {
949 continue;
950 }
951 if let Some(svar_val) = card.svars.get(svar_name) {
952 if svar_val.contains("DB$ Tap") && svar_val.contains("ETB$ True") {
953 if let Some(pos) = svar_val.find("Reveal<") {
955 let after = &svar_val[pos + 7..]; if let Some(end) = after.find('>') {
957 let inner = &after[..end]; let mut parts = inner.splitn(2, '/');
959 let n = parts
960 .next()
961 .and_then(|s| s.trim().parse::<i32>().ok())
962 .unwrap_or(1);
963 let filter = parts.next().unwrap_or("").trim().to_string();
964 return Some((n, filter));
965 }
966 }
967 }
968 }
969 }
970 }
971 None
972}
973
974fn resolve_add_pt_value(game: &GameState, source_id: CardId, val_str: Option<&str>) -> i32 {
977 let val_str = match val_str {
978 Some(val_str) => val_str,
979 None => return 0,
980 };
981
982 if let Ok(n) = val_str.trim().parse::<i32>() {
984 return n;
985 }
986
987 let source = game.card(source_id);
989 if let Some(svar_expr) = source.svars.get(val_str.trim()) {
990 if svar_expr.starts_with("Count$") {
991 return crate::ability::effects::resolve_count_svar(
992 svar_expr,
993 game,
994 source_id,
995 source.controller,
996 );
997 }
998 return crate::ability::effects::evaluate_svar(
999 svar_expr,
1000 &crate::spellability::SpellAbility::new_empty(Some(source_id), source.controller),
1001 );
1002 }
1003
1004 0
1005}
1006
1007fn resolve_set_pt_value(game: &GameState, source_id: CardId, val_str: Option<&str>) -> Option<i32> {
1011 let val_str = val_str?;
1012 if let Ok(n) = val_str.trim().parse::<i32>() {
1014 return Some(n);
1015 }
1016
1017 let source = game.card(source_id);
1019 if let Some(svar_expr) = source.svars.get(val_str.trim()) {
1020 if svar_expr.starts_with("Count$") {
1021 return Some(crate::ability::effects::resolve_count_svar(
1022 svar_expr,
1023 game,
1024 source_id,
1025 source.controller,
1026 ));
1027 }
1028 return Some(crate::ability::effects::evaluate_svar(
1030 svar_expr,
1031 &crate::spellability::SpellAbility::new_empty(Some(source_id), source.controller),
1032 ));
1033 }
1034
1035 None
1036}
1037
1038fn basic_land_mana_ability_text(subtype: &str) -> Option<&'static str> {
1039 match subtype {
1040 "Plains" => Some("AB$ Mana | Cost$ T | Produced$ W | SpellDescription$ Add {W}."),
1041 "Island" => Some("AB$ Mana | Cost$ T | Produced$ U | SpellDescription$ Add {U}."),
1042 "Swamp" => Some("AB$ Mana | Cost$ T | Produced$ B | SpellDescription$ Add {B}."),
1043 "Mountain" => Some("AB$ Mana | Cost$ T | Produced$ R | SpellDescription$ Add {R}."),
1044 "Forest" => Some("AB$ Mana | Cost$ T | Produced$ G | SpellDescription$ Add {G}."),
1045 _ => None,
1046 }
1047}
1048
1049fn resolve_added_basic_land_types(
1050 source: &crate::card::Card,
1051 add_type: Option<&str>,
1052) -> Vec<String> {
1053 resolve_added_types(source, add_type)
1054 .into_iter()
1055 .filter(|added| basic_land_mana_ability_text(added).is_some())
1056 .collect()
1057}
1058
1059fn resolve_added_types(source: &crate::card::Card, add_type: Option<&str>) -> Vec<String> {
1060 let Some(add_type) = add_type else {
1061 return Vec::new();
1062 };
1063 let mut resolved = Vec::new();
1064 for raw in add_type.split('&').map(str::trim).filter(|s| !s.is_empty()) {
1065 match raw {
1066 "ChosenType" => {
1067 if let Some(chosen) = source.chosen_type.as_ref() {
1068 resolved.push(chosen.clone());
1069 }
1070 }
1071 "ChosenType2" => {
1072 if let Some(chosen) = source.chosen_type2.as_ref() {
1073 resolved.push(chosen.clone());
1074 }
1075 }
1076 "AllBasicLandType" => {
1077 resolved.extend(
1078 ["Plains", "Island", "Swamp", "Mountain", "Forest"]
1079 .into_iter()
1080 .map(str::to_string),
1081 );
1082 }
1083 other => resolved.push(other.to_string()),
1084 }
1085 }
1086 resolved
1087}
1088
1089#[cfg(test)]
1092mod tests {
1093 use super::*;
1094 use forge_foundation::{CardTypeLine, ColorSet, ManaCost, ZoneType};
1095
1096 use crate::card::Card;
1097 use crate::ids::{CardId, PlayerId};
1098
1099 fn new_game() -> GameState {
1101 GameState::new(&["Alice", "Bob"], 20)
1102 }
1103
1104 fn add_creature(
1105 game: &mut GameState,
1106 owner: PlayerId,
1107 power: i32,
1108 toughness: i32,
1109 keywords: Vec<String>,
1110 abilities: Vec<String>,
1111 ) -> CardId {
1112 let card = Card::new(
1113 CardId(0), "Creature".to_string(),
1115 owner,
1116 CardTypeLine::parse("Creature"),
1117 ManaCost::parse("1 G"),
1118 ColorSet::GREEN,
1119 Some(power),
1120 Some(toughness),
1121 keywords,
1122 abilities,
1123 );
1124 let id = game.create_card(card);
1125 game.move_card(id, ZoneType::Battlefield, owner);
1126 id
1127 }
1128
1129 fn add_enchantment(game: &mut GameState, owner: PlayerId, abilities: Vec<String>) -> CardId {
1130 let card = Card::new(
1131 CardId(0),
1132 "Enchantment".to_string(),
1133 owner,
1134 CardTypeLine::parse("Enchantment"),
1135 ManaCost::parse("2 W"),
1136 ColorSet::WHITE,
1137 None,
1138 None,
1139 vec![],
1140 abilities,
1141 );
1142 let id = game.create_card(card);
1143 game.move_card(id, ZoneType::Battlefield, owner);
1144 id
1145 }
1146
1147 fn add_land(
1148 game: &mut GameState,
1149 owner: PlayerId,
1150 name: &str,
1151 type_line: &str,
1152 abilities: Vec<String>,
1153 ) -> CardId {
1154 let card = Card::new(
1155 CardId(0),
1156 name.to_string(),
1157 owner,
1158 CardTypeLine::parse(type_line),
1159 ManaCost::no_cost(),
1160 ColorSet::COLORLESS,
1161 None,
1162 None,
1163 vec![],
1164 abilities,
1165 );
1166 let id = game.create_card(card);
1167 game.move_card(id, ZoneType::Battlefield, owner);
1168 id
1169 }
1170
1171 fn add_effect(game: &mut GameState, owner: PlayerId, abilities: Vec<String>) -> CardId {
1172 let card = Card::new(
1173 CardId(0),
1174 "Effect".to_string(),
1175 owner,
1176 CardTypeLine::parse("Effect"),
1177 ManaCost::parse("0"),
1178 ColorSet::COLORLESS,
1179 None,
1180 None,
1181 vec![],
1182 abilities,
1183 );
1184 let id = game.create_card(card);
1185 game.move_card(id, ZoneType::Command, owner);
1186 id
1187 }
1188
1189 #[test]
1192 fn anthem_boosts_your_creatures() {
1193 let mut game = new_game();
1194 let alice = PlayerId(0);
1195 let bob = PlayerId(1);
1196
1197 let a1 = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1199 let a2 = add_creature(&mut game, alice, 1, 1, vec![], vec![]);
1200 let b1 = add_creature(&mut game, bob, 2, 2, vec![], vec![]);
1201
1202 let _anthem = add_enchantment(
1204 &mut game,
1205 alice,
1206 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1 | Description$ Creatures you control get +1/+1.".to_string()],
1207 );
1208
1209 apply_continuous_effects(&mut game);
1210
1211 assert_eq!(game.card(a1).power(), 3, "Alice's 2/2 should be 3/3");
1213 assert_eq!(game.card(a1).toughness(), 3);
1214 assert_eq!(game.card(a2).power(), 2, "Alice's 1/1 should be 2/2");
1215 assert_eq!(game.card(a2).toughness(), 2);
1216
1217 assert_eq!(
1219 game.card(b1).power(),
1220 2,
1221 "Bob's creature should be unchanged"
1222 );
1223 assert_eq!(game.card(b1).toughness(), 2);
1224 }
1225
1226 #[test]
1227 fn command_effect_adjusts_land_plays_for_affected_player() {
1228 let mut game = new_game();
1229 let alice = PlayerId(0);
1230 let bob = PlayerId(1);
1231
1232 let effect = add_effect(
1233 &mut game,
1234 alice,
1235 vec![
1236 "S$ Mode$ Continuous | EffectZone$ Command | Affected$ You | AdjustLandPlays$ 1"
1237 .to_string(),
1238 ],
1239 );
1240
1241 apply_continuous_effects(&mut game);
1242
1243 assert_eq!(game.player(alice).max_land_plays_per_turn, 2);
1244 assert_eq!(game.player(bob).max_land_plays_per_turn, 1);
1245
1246 game.move_card(effect, ZoneType::Exile, alice);
1247 apply_continuous_effects(&mut game);
1248
1249 assert_eq!(game.player(alice).max_land_plays_per_turn, 1);
1250 }
1251
1252 #[test]
1253 fn anthem_resets_when_removed() {
1254 let mut game = new_game();
1255 let alice = PlayerId(0);
1256
1257 let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1258 let anthem = add_enchantment(
1259 &mut game,
1260 alice,
1261 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
1262 );
1263
1264 apply_continuous_effects(&mut game);
1265 assert_eq!(game.card(creature).power(), 3);
1266
1267 game.move_card(anthem, ZoneType::Graveyard, alice);
1269 apply_continuous_effects(&mut game);
1270
1271 assert_eq!(
1272 game.card(creature).power(),
1273 2,
1274 "Bonus should be gone after anthem leaves"
1275 );
1276 }
1277
1278 #[test]
1279 fn stacking_anthems() {
1280 let mut game = new_game();
1281 let alice = PlayerId(0);
1282
1283 let creature = add_creature(&mut game, alice, 1, 1, vec![], vec![]);
1284 add_enchantment(
1286 &mut game,
1287 alice,
1288 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
1289 );
1290 add_enchantment(
1291 &mut game,
1292 alice,
1293 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
1294 );
1295
1296 apply_continuous_effects(&mut game);
1297 assert_eq!(game.card(creature).power(), 3, "Two anthems should give +2");
1298 assert_eq!(game.card(creature).toughness(), 3);
1299 }
1300
1301 #[test]
1304 fn grant_flying_to_your_creatures() {
1305 let mut game = new_game();
1306 let alice = PlayerId(0);
1307 let bob = PlayerId(1);
1308
1309 let a1 = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1310 let b1 = add_creature(&mut game, bob, 2, 2, vec![], vec![]);
1311
1312 add_enchantment(
1313 &mut game,
1314 alice,
1315 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddKeyword$ Flying | Description$ Creatures you control have flying.".to_string()],
1316 );
1317
1318 apply_continuous_effects(&mut game);
1319
1320 assert!(
1321 game.card(a1).has_flying(),
1322 "Alice's creature should have flying"
1323 );
1324 assert!(
1325 !game.card(b1).has_flying(),
1326 "Bob's creature should not have flying"
1327 );
1328 }
1329
1330 #[test]
1331 fn grant_multiple_keywords() {
1332 let mut game = new_game();
1333 let alice = PlayerId(0);
1334
1335 let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1336 add_enchantment(
1337 &mut game,
1338 alice,
1339 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddKeyword$ Flying & First Strike".to_string()],
1340 );
1341
1342 apply_continuous_effects(&mut game);
1343
1344 assert!(game.card(creature).has_flying());
1345 assert!(game.card(creature).has_first_strike());
1346 }
1347
1348 #[test]
1351 fn set_pt_overrides_base() {
1352 let mut game = new_game();
1353 let alice = PlayerId(0);
1354
1355 let creature = add_creature(&mut game, alice, 5, 5, vec![], vec![]);
1356 add_enchantment(
1358 &mut game,
1359 alice,
1360 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | SetPower$ 0 | SetToughness$ 1".to_string()],
1361 );
1362
1363 apply_continuous_effects(&mut game);
1364 assert_eq!(game.card(creature).power(), 0);
1365 assert_eq!(game.card(creature).toughness(), 1);
1366 }
1367
1368 #[test]
1369 fn modify_pt_adds_on_top_of_set_pt() {
1370 let mut game = new_game();
1372 let alice = PlayerId(0);
1373
1374 let creature = add_creature(&mut game, alice, 5, 5, vec![], vec![]);
1375 add_enchantment(
1377 &mut game,
1378 alice,
1379 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | SetPower$ 0 | SetToughness$ 1".to_string()],
1380 );
1381 add_enchantment(
1383 &mut game,
1384 alice,
1385 vec!["S$ Mode$ Continuous | Affected$ Creature.YouControl | AddPower$ 1 | AddToughness$ 1".to_string()],
1386 );
1387
1388 apply_continuous_effects(&mut game);
1389 assert_eq!(game.card(creature).power(), 1);
1391 assert_eq!(game.card(creature).toughness(), 2);
1392 }
1393
1394 #[test]
1397 fn cant_attack_flag_set() {
1398 let mut game = new_game();
1399 let alice = PlayerId(0);
1400
1401 let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1402 add_enchantment(
1404 &mut game,
1405 alice,
1406 vec!["S$ Mode$ CantAttack | Affected$ Creature.YouControl | Description$ Creatures you control can't attack.".to_string()],
1407 );
1408
1409 apply_continuous_effects(&mut game);
1410 assert!(game.card(creature).cant_attack_static);
1411 }
1412
1413 #[test]
1414 fn cant_block_flag_set() {
1415 let mut game = new_game();
1416 let alice = PlayerId(0);
1417
1418 let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1419 add_enchantment(
1420 &mut game,
1421 alice,
1422 vec!["S$ Mode$ CantBlock | Affected$ Creature.YouControl".to_string()],
1423 );
1424
1425 apply_continuous_effects(&mut game);
1426 assert!(game.card(creature).cant_block_static);
1427 }
1428
1429 #[test]
1430 fn flags_reset_on_reapplication() {
1431 let mut game = new_game();
1432 let alice = PlayerId(0);
1433
1434 let creature = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1435 let restrictor = add_enchantment(
1436 &mut game,
1437 alice,
1438 vec!["S$ Mode$ CantAttack | Affected$ Creature.YouControl".to_string()],
1439 );
1440
1441 apply_continuous_effects(&mut game);
1442 assert!(game.card(creature).cant_attack_static);
1443
1444 game.move_card(restrictor, ZoneType::Graveyard, alice);
1445 apply_continuous_effects(&mut game);
1446 assert!(
1447 !game.card(creature).cant_attack_static,
1448 "Flag should clear after enchantment leaves"
1449 );
1450 }
1451
1452 #[test]
1453 fn lands_gain_swamp_mana_ability_from_urborg_style_effect() {
1454 let mut game = new_game();
1455 let alice = PlayerId(0);
1456
1457 let urborg = add_land(
1458 &mut game,
1459 alice,
1460 "Urborg, Tomb of Yawgmoth",
1461 "Legendary Land",
1462 vec!["S$ Mode$ Continuous | Affected$ Land | AddType$ Swamp | Description$ Each land is a Swamp in addition to its other land types.".to_string()],
1463 );
1464 let black_gate = add_land(
1465 &mut game,
1466 alice,
1467 "The Black Gate",
1468 "Legendary Land Gate",
1469 vec![],
1470 );
1471
1472 apply_continuous_effects(&mut game);
1473
1474 for land_id in [urborg, black_gate] {
1475 let land = game.card(land_id);
1476 assert!(
1477 land.type_line.has_subtype("Swamp"),
1478 "{} should gain the Swamp subtype",
1479 land.card_name
1480 );
1481 assert!(
1482 land.activated_abilities.iter().any(|ab| {
1483 ab.is_mana_ability
1484 && ab
1485 .produced_ir
1486 .as_ref()
1487 .is_some_and(|ir| ir.as_script_text() == "B")
1488 }),
1489 "{} should gain an intrinsic black mana ability from Swamp",
1490 land.card_name
1491 );
1492 }
1493 }
1494
1495 #[test]
1498 fn self_etb_tapped() {
1499 let mut game = new_game();
1500 let alice = PlayerId(0);
1501
1502 let card = Card::new(
1504 CardId(0),
1505 "TappedLand".to_string(),
1506 alice,
1507 CardTypeLine::parse("Land"),
1508 ManaCost::parse(""),
1509 ColorSet::from_mask(0),
1510 None,
1511 None,
1512 vec![],
1513 vec!["S$ Mode$ ETBTapped | Description$ Enters tapped.".to_string()],
1514 );
1515 let id = game.create_card(card);
1516 game.move_card(id, ZoneType::Battlefield, alice);
1517 apply_etb_tapped(&mut game, id);
1518
1519 assert!(
1520 game.card(id).tapped,
1521 "Card with ETBTapped should enter tapped"
1522 );
1523 }
1524
1525 #[test]
1526 fn no_etb_tapped_without_ability() {
1527 let mut game = new_game();
1528 let alice = PlayerId(0);
1529
1530 let id = add_creature(&mut game, alice, 2, 2, vec![], vec![]);
1531 assert!(
1533 !game.card(id).tapped,
1534 "Normal creature should not enter tapped"
1535 );
1536 }
1537
1538 #[test]
1539 fn etb_tapped_via_replacement_effect() {
1540 let mut game = new_game();
1541 let alice = PlayerId(0);
1542
1543 let card = Card::new(
1545 CardId(0),
1546 "PathOfAncestry".to_string(),
1547 alice,
1548 CardTypeLine::parse("Land"),
1549 ManaCost::parse(""),
1550 ColorSet::from_mask(0),
1551 None,
1552 None,
1553 vec![],
1554 vec!["R:Event$ Moved | Destination$ Battlefield | ValidCard$ Card.Self | ReplaceWith$ ETBTapped | Description$ ~ enters tapped.".to_string()],
1555 );
1556 let id = game.create_card(card);
1557 game.move_card(id, ZoneType::Battlefield, alice);
1558 apply_etb_tapped(&mut game, id);
1559
1560 assert!(
1561 game.card(id).tapped,
1562 "Card with ReplaceWith$ ETBTapped replacement should enter tapped"
1563 );
1564 }
1565}