1use super::*;
2use crate::player::actions::player_action::STATIC_ALTERNATIVE_ABILITY_INDEX;
3use crate::player::actions::{PlayerAction, PlayerActionOutcome};
4use crate::player::PlayerController;
5
6impl GameLoop {
7 fn describe_priority_action(
8 &self,
9 game: &GameState,
10 action: MainPhaseAction,
11 ability_idx: Option<usize>,
12 ) -> String {
13 let card_name_or_id = |card_id: CardId| -> String {
14 game.cards
15 .get(card_id.index())
16 .map(|c| c.card_name.clone())
17 .unwrap_or_else(|| format!("CardId({})", card_id.0))
18 };
19 match action {
20 MainPhaseAction::Pass => "Pass".to_string(),
21 MainPhaseAction::Play(play) => {
22 format!("Play {}", card_name_or_id(play.card_id))
23 }
24 MainPhaseAction::ActivateMana(card_id, _, _) => {
25 format!("Activate mana ({})", card_name_or_id(card_id))
26 }
27 MainPhaseAction::UntapMana(card_id) => {
28 format!("Untap mana ({})", card_name_or_id(card_id))
29 }
30 MainPhaseAction::ActivateAbility(card_id, _) => {
31 let idx = ability_idx.unwrap_or_default();
32 format!("Activate ability {} ({})", idx, card_name_or_id(card_id))
33 }
34 }
35 }
36
37 pub fn priority_round(
38 &mut self,
39 game: &mut GameState,
40 agents: &mut [Box<dyn PlayerAgent>],
41 is_main_phase: bool,
42 ) {
43 let _perf_scope =
44 crate::perf::ParamsLookupScopeGuard::enter(crate::perf::ParamsLookupScope::Priority);
45 let mut priority_player = game.active_player();
46 let mut last_notified_priority: Option<PlayerId> = None;
47 let mut passed_count = 0;
48 let num_players = game.players.len();
49 while passed_count < num_players {
50 if game.game_over {
51 return;
52 }
53 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
54 game.turn.priority_player = priority_player;
55 });
56
57 if last_notified_priority != Some(priority_player) {
58 self.notify_priority_changed(game, agents, priority_player);
59 last_notified_priority = Some(priority_player);
60 }
61 if game.game_over {
62 return;
63 }
64
65 loop {
66 let sba_changed = super::check_sba(game, &mut self.trigger_handler, agents);
67 if game.game_over {
68 return;
69 }
70 let stack_before = game.stack.len();
71 self.with_shared_state_mutation(game, agents, |this, game, agents| {
72 this.process_triggers(game, agents);
73 });
74 let triggers_added = game.stack.len() > stack_before;
75 if !sba_changed && !triggers_added {
77 break;
78 }
79 }
80 if game.game_over {
81 return;
82 }
83
84 if let Some(target) = agents[priority_player.index()].get_pass_until() {
85 let current_phase = game.turn.phase;
86 let active = game.active_player();
87 let has_declared_attackers = self.combat.has_attackers();
88 let is_active_combat = !target.through_combat
89 && has_declared_attackers
90 && matches!(
91 current_phase,
92 forge_foundation::PhaseType::CombatDeclareAttackers
93 | forge_foundation::PhaseType::CombatDeclareBlockers
94 | forge_foundation::PhaseType::CombatFirstStrikeDamage
95 | forge_foundation::PhaseType::CombatDamage
96 | forge_foundation::PhaseType::CombatEnd
97 );
98 let reached = (active == target.player && !current_phase.is_before(target.phase))
99 || !game.player(target.player).is_alive();
100 if reached {
101 agents[priority_player.index()].clear_pass_until();
102 } else if !is_active_combat && game.stack.is_empty() {
103 self.log_priority_pass(game, priority_player);
104 passed_count += 1;
105 priority_player = game.next_player(priority_player);
106 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
107 game.turn.priority_player = priority_player;
108 });
109 continue;
110 }
111 }
112
113 let mut action_space = if self.provide_priority_action_space {
114 crate::staticability::layer::apply_continuous_effects(game);
115 Some(self.action_space(game, priority_player, is_main_phase))
116 } else {
117 None
118 };
119 if action_space.as_ref().is_some_and(|space| space.is_empty()) {
120 self.invalidate_mana_undo_for_player(priority_player);
121 self.log_priority_pass(game, priority_player);
122 passed_count += 1;
123 priority_player = game.next_player(priority_player);
124 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
125 game.turn.priority_player = priority_player;
126 });
127 continue;
128 }
129 self.log_waiting_for_priority(game, priority_player);
130 let action = {
131 let _perf_scope = crate::perf::ParamsLookupScopeGuard::enter(
132 crate::perf::ParamsLookupScope::PriorityChoice,
133 );
134 {
135 let _perf_scope = crate::perf::ParamsLookupScopeGuard::enter(
136 crate::perf::ParamsLookupScope::PrioritySnapshot,
137 );
138 crate::perf::increment_priority_snapshot();
139 let agent = agents[priority_player.index()].as_mut();
140 let mut controller = PlayerController::new(game, priority_player, agent);
141 controller.snapshot_state(&self.mana_pools);
142 }
143 if self.is_aborted() {
144 game.game_over = true;
145 return;
146 }
147 let mut request_action_space = || {
148 crate::staticability::layer::apply_continuous_effects(game);
149 self.action_space(game, priority_player, is_main_phase)
150 };
151 agents[priority_player.index()].choose_action(
152 priority_player,
153 action_space.as_ref(),
154 &mut request_action_space,
155 )
156 };
157
158 if action == PlayerAction::Concede {
159 let _ = agents[priority_player.index()].take_restore_request();
160 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
161 crate::player::concede(game, priority_player);
162 });
163 if game.alive_players().len() > 1 {
164 agents[priority_player.index()].snapshot_state(game, &self.mana_pools);
165 agents[priority_player.index()]
166 .notify(crate::agent::notification::GameNotification::GameOver);
167 }
168 passed_count = 0;
169 priority_player = game.next_player(priority_player);
170 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
171 game.turn.priority_player = priority_player;
172 });
173 continue;
174 }
175
176 if self.apply_pending_snapshot_restore(game, agents) {
177 passed_count = 0;
178 priority_player = game.turn.priority_player;
179 continue;
180 }
181
182 let priority_action = if action == PlayerAction::PassPriority {
183 MainPhaseAction::Pass
184 } else {
185 if action_space.is_none() {
186 crate::staticability::layer::apply_continuous_effects(game);
187 action_space = Some(self.action_space(game, priority_player, is_main_phase));
188 }
189 let action_space = action_space
190 .as_ref()
191 .expect("non-pass priority action requires action space");
192 let agent = agents[priority_player.index()].as_mut();
193 let mut controller = PlayerController::new(game, priority_player, agent);
194 let activatable_ids: Vec<(CardId, usize)> = action_space
195 .activatable
196 .iter()
197 .map(|a| (a.card_id, a.ability_index))
198 .collect();
199 match action.run(
200 &mut controller,
201 &action_space.playable,
202 &action_space.tappable_lands,
203 &action_space.untappable_lands,
204 &activatable_ids,
205 ) {
206 PlayerActionOutcome::Priority(action) => action,
207 PlayerActionOutcome::Pending | PlayerActionOutcome::Target(_) => {
208 crate::agent::notify_all_agents(
209 agents,
210 crate::agent::GameLogEvent::warning(
211 "Illegal action ignored: unsupported priority action",
212 )
213 .with_player(priority_player),
214 );
215 passed_count += 1;
216 priority_player = game.next_player(priority_player);
217 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
218 game.turn.priority_player = priority_player;
219 });
220 continue;
221 }
222 }
223 };
224 let _perf_scope = crate::perf::ParamsLookupScopeGuard::enter(
225 crate::perf::ParamsLookupScope::PriorityExecution,
226 );
227 match priority_action {
228 MainPhaseAction::Pass => {
229 self.invalidate_mana_undo_for_player(priority_player);
230 self.log_priority_pass(game, priority_player);
231 passed_count += 1;
232 priority_player = game.next_player(priority_player);
233 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
234 game.turn.priority_player = priority_player;
235 });
236 }
237 MainPhaseAction::Play(play) => {
238 agents[priority_player.index()].clear_pass_until();
239 let action_space = action_space
240 .as_ref()
241 .expect("play priority action requires action space");
242 self.invalidate_mana_undo_for_player(priority_player);
243 self.log_priority_response(
244 game,
245 priority_player,
246 &self.describe_priority_action(game, priority_action, None),
247 );
248 if !action_space.playable.contains(&play) {
249 crate::agent::notify_all_agents(
250 agents,
251 crate::agent::GameLogEvent::warning(
252 "Illegal action ignored: unplayable card",
253 )
254 .with_player(priority_player),
255 );
256 passed_count += 1;
257 priority_player = game.next_player(priority_player);
258 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
259 game.turn.priority_player = priority_player;
260 });
261 continue;
262 }
263
264 if let crate::agent::PlayCardMode::UnlockDoor { door } = play.mode {
267 let unlock_ab_idx =
268 game.card(play.card_id)
269 .activated_abilities
270 .iter()
271 .find(|ab| {
272 ab.is_unlock_door
273 && ab.params.get("CardState").and_then(
274 forge_foundation::CardStateName::from_str_compat,
275 ) == Some(door)
276 })
277 .map(|ab| ab.ability_index);
278 if let Some(ability_idx) = unlock_ab_idx {
279 let played = self.with_shared_state_mutation(
280 game,
281 agents,
282 |this, game, agents| {
283 let ability_text = game
284 .card(play.card_id)
285 .activated_abilities
286 .iter()
287 .find(|ab| ab.ability_index == ability_idx)
288 .map(|ab| ab.ability_text.clone())?;
289 let mut sa = crate::spellability::build_spell_ability(
290 game,
291 play.card_id,
292 &ability_text,
293 priority_player,
294 );
295 sa.is_activated = true;
296 this.play_spell_ability(
297 game,
298 agents,
299 priority_player,
300 PreparedSpellAbility {
301 spell_ability: sa,
302 activated_ability_index: Some(ability_idx),
303 static_alternative_cost_prepared: false,
304 },
305 )
306 },
307 );
308 if played.is_some() {
309 self.with_shared_state_mutation(
310 game,
311 agents,
312 |this, game, agents| {
313 this.process_triggers(game, agents);
314 },
315 );
316 passed_count = 0;
317 }
318 continue;
320 }
321 }
322
323 let origin_zone = game.card_current_zone(play.card_id);
324 let played =
325 self.with_shared_state_mutation(game, agents, |this, game, agents| {
326 let card_name = game.card(play.card_id).card_name.clone();
327 if game.card(play.card_id).is_land()
328 || play.mode == crate::agent::PlayCardMode::BackFaceLand
329 {
330 this.play_land(
331 game,
332 agents,
333 priority_player,
334 play.card_id,
335 &card_name,
336 play.mode,
337 )
338 .map(|(card_id, card_name)| PlaySpellAbilityResult::CardPlayed {
339 card_id,
340 card_name,
341 })
342 } else if let Some(result) = this.play_special_card_action(
343 game,
344 agents,
345 priority_player,
346 play.card_id,
347 play.mode,
348 ) {
349 result.map(|(card_id, card_name)| {
350 PlaySpellAbilityResult::CardPlayed { card_id, card_name }
351 })
352 } else {
353 let prepared = this.prepare_card_spell_ability(
354 game,
355 priority_player,
356 play.card_id,
357 play,
358 )?;
359 this.play_spell_ability(game, agents, priority_player, prepared)
360 }
361 });
362 if let Some(PlaySpellAbilityResult::CardPlayed {
363 card_id: played_id,
364 card_name: played_name,
365 }) = played
366 {
367 let set_code = game.card(played_id).set_code.clone().unwrap_or_default();
368 for agent in agents.iter_mut() {
369 agent.snapshot_state(game, &self.mana_pools);
370 agent.notify(
371 crate::agent::notification::GameNotification::CardPlayed {
372 player: priority_player,
373 card_id: played_id,
374 card_name: played_name.clone(),
375 set_code: set_code.clone(),
376 },
377 );
378 }
379 self.with_shared_state_mutation(game, agents, |this, game, agents| {
384 let current_zone = game.card_current_zone(played_id);
385 if current_zone != origin_zone {
386 let mut trigger_list =
387 crate::card::card_zone_table::CardZoneTable::default();
388 trigger_list.put(Some(origin_zone), Some(current_zone), played_id);
389 trigger_list.trigger_changes_zone_all(
390 &mut this.trigger_handler,
391 game,
392 None,
393 );
394 }
395 this.process_triggers(game, agents);
396 });
397 passed_count = 0;
398 } else {
399 crate::agent::notify_all_agents(
400 agents,
401 crate::agent::GameLogEvent::warning("Card play failed")
402 .with_player(priority_player),
403 );
404 }
405 }
406 MainPhaseAction::ActivateMana(land_id, requested_ability_idx, express_choice) => {
407 let action_space = action_space
408 .as_ref()
409 .expect("mana priority action requires action space");
410 self.log_priority_response(
411 game,
412 priority_player,
413 &self.describe_priority_action(game, priority_action, None),
414 );
415 if !action_space.tappable_lands.contains(&land_id) {
416 crate::agent::notify_all_agents(
417 agents,
418 crate::agent::GameLogEvent::warning(
419 "Illegal action ignored: permanent can't tap for mana",
420 )
421 .with_player(priority_player),
422 );
423 passed_count += 1;
424 priority_player = game.next_player(priority_player);
425 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
426 game.turn.priority_player = priority_player;
427 });
428 continue;
429 }
430 let undo_record = self.begin_mana_undo_action(game, priority_player, land_id);
431 let pool_snapshot = self.pool(priority_player).begin_tap_tracking();
432
433 let mana_abs: Vec<_> = {
434 let c = game.card(land_id);
435 c.activated_abilities
436 .iter()
437 .filter(|ab| ab.is_mana_ability)
438 .cloned()
439 .collect()
440 };
441 if !mana_abs.is_empty() {
442 let (tap_abs, non_tap_abs): (Vec<_>, Vec<_>) =
447 mana_abs.iter().partition(|ab| {
448 ab.cost
449 .parts
450 .iter()
451 .any(|p| matches!(p, crate::cost::CostPart::Tap))
452 });
453
454 let chosen_ab: Option<crate::ability::activated::ActivatedAbility> =
455 if let Some(req_idx) = requested_ability_idx {
456 tap_abs
457 .iter()
458 .chain(non_tap_abs.iter())
459 .find(|ab| ab.ability_index == req_idx)
460 .map(|ab| (*ab).clone())
461 } else if tap_abs.len() <= 1 {
462 tap_abs.first().map(|ab| (*ab).clone()).or_else(|| {
463 if non_tap_abs.len() == 1 {
464 Some((*non_tap_abs[0]).clone())
465 } else {
466 None
467 }
468 })
469 } else {
470 let mut color_options: Vec<(String, usize)> = Vec::new();
472 for (i, ab) in tap_abs.iter().enumerate() {
473 if let Some(produced_ir) = ab.produced_ir.as_ref() {
474 let chosen_colors =
475 game.card(land_id).chosen_colors.clone();
476 let names = produced_ir.to_color_names(&chosen_colors);
477 for name in names {
478 if !color_options.iter().any(|(n, _)| *n == name) {
479 color_options.push((name, i));
480 }
481 }
482 }
483 }
484 let color_names: Vec<String> =
485 color_options.iter().map(|(n, _)| n.clone()).collect();
486 let chosen_idx = if color_names.len() == 1 {
487 Some(0usize)
488 } else {
489 agents[priority_player.index()]
490 .choose_color(priority_player, &color_names)
491 .and_then(|chosen| {
492 color_options.iter().position(|(n, _)| *n == chosen)
493 })
494 };
495 chosen_idx.and_then(|ci| {
496 let (_, ab_idx) = &color_options[ci];
497 tap_abs.get(*ab_idx).map(|ab| (*ab).clone())
498 })
499 };
500
501 let chosen_idx = chosen_ab.as_ref().map(|ab| ab.ability_index);
502 let chosen_is_tap = chosen_ab
503 .as_ref()
504 .map(|ab| {
505 ab.cost
506 .parts
507 .iter()
508 .any(|p| matches!(p, crate::cost::CostPart::Tap))
509 })
510 .unwrap_or(false);
511
512 if let Some(ab) = chosen_ab {
513 self.with_shared_state_mutation(game, agents, |this, game, agents| {
514 this.resolve_mana_ability(
515 game,
516 agents,
517 priority_player,
518 land_id,
519 &ab,
520 express_choice,
521 );
522 });
523 }
524
525 if chosen_is_tap {
526 for ab in &non_tap_abs {
527 if Some(ab.ability_index) == chosen_idx {
528 continue;
529 }
530 if !ab.cost.parts.is_empty() {
531 continue;
532 }
533 let ab = (*ab).clone();
534 self.with_shared_state_mutation(
535 game,
536 agents,
537 |this, game, agents| {
538 this.resolve_mana_ability(
539 game,
540 agents,
541 priority_player,
542 land_id,
543 &ab,
544 None,
545 );
546 },
547 );
548 }
549 }
550 } else {
551 self.with_shared_state_mutation(game, agents, |this, game, agents| {
553 let atom_opt = {
554 let c = game.card(land_id);
555 if c.is_land() && !c.tapped {
556 basic_land_mana_atom(c)
557 } else {
558 None
559 }
560 };
561 if let Some(atom) = atom_opt {
562 game.tap(land_id);
563 this.pool_mut(priority_player).add(atom, 1);
564 this.trigger_handler.run_trigger(
565 TriggerType::Taps,
566 RunParams {
567 card: Some(land_id),
568 player: Some(priority_player),
569 ..Default::default()
570 },
571 false,
572 );
573 this.trigger_handler.run_trigger(
574 TriggerType::TapsForMana,
575 RunParams {
576 card: Some(land_id),
577 player: Some(priority_player),
578 ..Default::default()
579 },
580 false,
581 );
582 let pending = this.trigger_handler.run_waiting_triggers(game);
584 if !pending.is_empty() {
585 this.mark_mana_undo_disqualified();
586 }
587 for pt in pending {
588 this.resolve_single_effect(
589 game,
590 agents,
591 &pt.entry.spell_ability,
592 None,
593 );
594 }
595 }
596 });
597 }
598
599 let produced = self.pool(priority_player).end_tap_tracking(&pool_snapshot);
602 let produced_count = produced.len();
603 if !produced.is_empty() {
604 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
605 game.card_mut(land_id).last_mana_produced = Some(produced);
606 });
607 }
608 self.finish_mana_undo_action(undo_record, produced_count);
609 passed_count = 0;
610 }
611 MainPhaseAction::UntapMana(land_id) => {
612 let action_space = action_space
613 .as_ref()
614 .expect("mana undo priority action requires action space");
615 self.log_priority_response(
616 game,
617 priority_player,
618 &self.describe_priority_action(game, priority_action, None),
619 );
620 if !action_space.untappable_lands.contains(&land_id) {
621 crate::agent::notify_all_agents(
622 agents,
623 crate::agent::GameLogEvent::warning(
624 "Illegal action ignored: land can't be untapped for mana rollback",
625 )
626 .with_player(priority_player),
627 );
628 passed_count += 1;
629 priority_player = game.next_player(priority_player);
630 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
631 game.turn.priority_player = priority_player;
632 });
633 continue;
634 }
635 self.with_shared_state_mutation(game, agents, |this, game, _agents| {
636 this.undo_mana_action(game, priority_player, land_id);
637 });
638 passed_count = 0;
639 }
640 MainPhaseAction::ActivateAbility(card_id, ability_idx) => {
641 agents[priority_player.index()].clear_pass_until();
642 let action_space = action_space
643 .as_ref()
644 .expect("ability priority action requires action space");
645 self.invalidate_mana_undo_for_player(priority_player);
646 self.log_priority_response(
647 game,
648 priority_player,
649 &self.describe_priority_action(game, priority_action, Some(ability_idx)),
650 );
651 if !action_space
652 .activatable
653 .iter()
654 .any(|a| a.card_id == card_id && a.ability_index == ability_idx)
655 {
656 crate::agent::notify_all_agents(
657 agents,
658 crate::agent::GameLogEvent::warning(
659 "Illegal action ignored: ability not activatable",
660 )
661 .with_player(priority_player),
662 );
663 passed_count += 1;
664 priority_player = game.next_player(priority_player);
665 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
666 game.turn.priority_player = priority_player;
667 });
668 continue;
669 }
670 let activated =
671 self.with_shared_state_mutation(game, agents, |this, game, agents| {
672 if ability_idx == STATIC_ALTERNATIVE_ABILITY_INDEX {
673 let can_play_sorcery = is_main_phase
674 && priority_player == game.active_player()
675 && game.stack.is_empty();
676 let (ab, sa) = this.prepare_static_alternative_activated_ability(
677 game,
678 priority_player,
679 card_id,
680 can_play_sorcery,
681 )?;
682 return this
683 .play_prepared_activated_ability_on_stack(
684 game,
685 agents,
686 priority_player,
687 card_id,
688 &ab,
689 sa,
690 )
691 .then_some(PlaySpellAbilityResult::AbilityActivated);
692 }
693 let ability_text = game
694 .card(card_id)
695 .activated_abilities
696 .iter()
697 .find(|ab| ab.ability_index == ability_idx)
698 .map(|ab| ab.ability_text.clone())?;
699 let mut sa = crate::spellability::build_spell_ability(
700 game,
701 card_id,
702 &ability_text,
703 priority_player,
704 );
705 sa.is_activated = true;
706 this.play_spell_ability(
707 game,
708 agents,
709 priority_player,
710 PreparedSpellAbility {
711 spell_ability: sa,
712 activated_ability_index: Some(ability_idx),
713 static_alternative_cost_prepared: false,
714 },
715 )
716 });
717 if activated.is_some() {
718 self.with_shared_state_mutation(game, agents, |this, game, agents| {
722 this.process_triggers(game, agents);
723 });
724 passed_count = 0;
725 }
726 }
727 }
728 }
729 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
730 game.turn.priority_player = game.active_player();
731 });
732 }
733}