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 play.mode == crate::agent::PlayCardMode::UnlockDoor {
267 let unlock_ab_idx = game
268 .card(play.card_id)
269 .activated_abilities
270 .iter()
271 .find(|ab| ab.is_unlock_door)
272 .map(|ab| ab.ability_index);
273 if let Some(ability_idx) = unlock_ab_idx {
274 let played = self.with_shared_state_mutation(
275 game,
276 agents,
277 |this, game, agents| {
278 let ability_text = game
279 .card(play.card_id)
280 .activated_abilities
281 .iter()
282 .find(|ab| ab.ability_index == ability_idx)
283 .map(|ab| ab.ability_text.clone())?;
284 let mut sa = crate::spellability::build_spell_ability(
285 game,
286 play.card_id,
287 &ability_text,
288 priority_player,
289 );
290 sa.is_activated = true;
291 this.play_spell_ability(
292 game,
293 agents,
294 priority_player,
295 PreparedSpellAbility {
296 spell_ability: sa,
297 activated_ability_index: Some(ability_idx),
298 static_alternative_cost_prepared: false,
299 },
300 )
301 },
302 );
303 if played.is_some() {
304 self.with_shared_state_mutation(
305 game,
306 agents,
307 |this, game, agents| {
308 this.process_triggers(game, agents);
309 },
310 );
311 passed_count = 0;
312 }
313 continue;
315 }
316 }
317
318 let origin_zone = game.card_current_zone(play.card_id);
319 let played =
320 self.with_shared_state_mutation(game, agents, |this, game, agents| {
321 let card_name = game.card(play.card_id).card_name.clone();
322 if game.card(play.card_id).is_land()
323 || play.mode == crate::agent::PlayCardMode::BackFaceLand
324 {
325 this.play_land(
326 game,
327 agents,
328 priority_player,
329 play.card_id,
330 &card_name,
331 play.mode,
332 )
333 .map(|(card_id, card_name)| PlaySpellAbilityResult::CardPlayed {
334 card_id,
335 card_name,
336 })
337 } else if let Some(result) = this.play_special_card_action(
338 game,
339 agents,
340 priority_player,
341 play.card_id,
342 play.mode,
343 ) {
344 result.map(|(card_id, card_name)| {
345 PlaySpellAbilityResult::CardPlayed { card_id, card_name }
346 })
347 } else {
348 let prepared = this.prepare_card_spell_ability(
349 game,
350 priority_player,
351 play.card_id,
352 play,
353 )?;
354 this.play_spell_ability(game, agents, priority_player, prepared)
355 }
356 });
357 if let Some(PlaySpellAbilityResult::CardPlayed {
358 card_id: played_id,
359 card_name: played_name,
360 }) = played
361 {
362 let set_code = game.card(played_id).set_code.clone().unwrap_or_default();
363 for agent in agents.iter_mut() {
364 agent.snapshot_state(game, &self.mana_pools);
365 agent.notify(
366 crate::agent::notification::GameNotification::CardPlayed {
367 player: priority_player,
368 card_id: played_id,
369 card_name: played_name.clone(),
370 set_code: set_code.clone(),
371 },
372 );
373 }
374 self.with_shared_state_mutation(game, agents, |this, game, agents| {
379 let current_zone = game.card_current_zone(played_id);
380 if current_zone != origin_zone {
381 let mut trigger_list =
382 crate::card::card_zone_table::CardZoneTable::default();
383 trigger_list.put(Some(origin_zone), Some(current_zone), played_id);
384 trigger_list.trigger_changes_zone_all(
385 &mut this.trigger_handler,
386 game,
387 None,
388 );
389 }
390 this.process_triggers(game, agents);
391 });
392 passed_count = 0;
393 } else {
394 crate::agent::notify_all_agents(
395 agents,
396 crate::agent::GameLogEvent::warning("Card play failed")
397 .with_player(priority_player),
398 );
399 }
400 }
401 MainPhaseAction::ActivateMana(land_id, requested_ability_idx, express_choice) => {
402 let action_space = action_space
403 .as_ref()
404 .expect("mana priority action requires action space");
405 self.log_priority_response(
406 game,
407 priority_player,
408 &self.describe_priority_action(game, priority_action, None),
409 );
410 if !action_space.tappable_lands.contains(&land_id) {
411 crate::agent::notify_all_agents(
412 agents,
413 crate::agent::GameLogEvent::warning(
414 "Illegal action ignored: permanent can't tap for mana",
415 )
416 .with_player(priority_player),
417 );
418 passed_count += 1;
419 priority_player = game.next_player(priority_player);
420 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
421 game.turn.priority_player = priority_player;
422 });
423 continue;
424 }
425 let undo_record = self.begin_mana_undo_action(game, priority_player, land_id);
426 let pool_snapshot = self.pool(priority_player).begin_tap_tracking();
427
428 let mana_abs: Vec<_> = {
429 let c = game.card(land_id);
430 c.activated_abilities
431 .iter()
432 .filter(|ab| ab.is_mana_ability)
433 .cloned()
434 .collect()
435 };
436 if !mana_abs.is_empty() {
437 let (tap_abs, non_tap_abs): (Vec<_>, Vec<_>) =
442 mana_abs.iter().partition(|ab| {
443 ab.cost
444 .parts
445 .iter()
446 .any(|p| matches!(p, crate::cost::CostPart::Tap))
447 });
448
449 let chosen_ab: Option<crate::ability::activated::ActivatedAbility> =
450 if let Some(req_idx) = requested_ability_idx {
451 tap_abs
452 .iter()
453 .chain(non_tap_abs.iter())
454 .find(|ab| ab.ability_index == req_idx)
455 .map(|ab| (*ab).clone())
456 } else if tap_abs.len() <= 1 {
457 tap_abs.first().map(|ab| (*ab).clone()).or_else(|| {
458 if non_tap_abs.len() == 1 {
459 Some((*non_tap_abs[0]).clone())
460 } else {
461 None
462 }
463 })
464 } else {
465 let mut color_options: Vec<(String, usize)> = Vec::new();
467 for (i, ab) in tap_abs.iter().enumerate() {
468 if let Some(produced_ir) = ab.produced_ir.as_ref() {
469 let chosen_colors =
470 game.card(land_id).chosen_colors.clone();
471 let names = produced_ir.to_color_names(&chosen_colors);
472 for name in names {
473 if !color_options.iter().any(|(n, _)| *n == name) {
474 color_options.push((name, i));
475 }
476 }
477 }
478 }
479 let color_names: Vec<String> =
480 color_options.iter().map(|(n, _)| n.clone()).collect();
481 let chosen_idx = if color_names.len() == 1 {
482 Some(0usize)
483 } else {
484 agents[priority_player.index()]
485 .choose_color(priority_player, &color_names)
486 .and_then(|chosen| {
487 color_options.iter().position(|(n, _)| *n == chosen)
488 })
489 };
490 chosen_idx.and_then(|ci| {
491 let (_, ab_idx) = &color_options[ci];
492 tap_abs.get(*ab_idx).map(|ab| (*ab).clone())
493 })
494 };
495
496 let chosen_idx = chosen_ab.as_ref().map(|ab| ab.ability_index);
497 let chosen_is_tap = chosen_ab
498 .as_ref()
499 .map(|ab| {
500 ab.cost
501 .parts
502 .iter()
503 .any(|p| matches!(p, crate::cost::CostPart::Tap))
504 })
505 .unwrap_or(false);
506
507 if let Some(ab) = chosen_ab {
508 self.with_shared_state_mutation(game, agents, |this, game, agents| {
509 this.resolve_mana_ability(
510 game,
511 agents,
512 priority_player,
513 land_id,
514 &ab,
515 express_choice,
516 );
517 });
518 }
519
520 if chosen_is_tap {
521 for ab in &non_tap_abs {
522 if Some(ab.ability_index) == chosen_idx {
523 continue;
524 }
525 if !ab.cost.parts.is_empty() {
526 continue;
527 }
528 let ab = (*ab).clone();
529 self.with_shared_state_mutation(
530 game,
531 agents,
532 |this, game, agents| {
533 this.resolve_mana_ability(
534 game,
535 agents,
536 priority_player,
537 land_id,
538 &ab,
539 None,
540 );
541 },
542 );
543 }
544 }
545 } else {
546 self.with_shared_state_mutation(game, agents, |this, game, agents| {
548 let atom_opt = {
549 let c = game.card(land_id);
550 if c.is_land() && !c.tapped {
551 basic_land_mana_atom(c)
552 } else {
553 None
554 }
555 };
556 if let Some(atom) = atom_opt {
557 game.tap(land_id);
558 this.pool_mut(priority_player).add(atom, 1);
559 this.trigger_handler.run_trigger(
560 TriggerType::Taps,
561 RunParams {
562 card: Some(land_id),
563 player: Some(priority_player),
564 ..Default::default()
565 },
566 false,
567 );
568 this.trigger_handler.run_trigger(
569 TriggerType::TapsForMana,
570 RunParams {
571 card: Some(land_id),
572 player: Some(priority_player),
573 ..Default::default()
574 },
575 false,
576 );
577 let pending = this.trigger_handler.run_waiting_triggers(game);
579 if !pending.is_empty() {
580 this.mark_mana_undo_disqualified();
581 }
582 for pt in pending {
583 this.resolve_single_effect(
584 game,
585 agents,
586 &pt.entry.spell_ability,
587 None,
588 );
589 }
590 }
591 });
592 }
593
594 let produced = self.pool(priority_player).end_tap_tracking(&pool_snapshot);
597 let produced_count = produced.len();
598 if !produced.is_empty() {
599 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
600 game.card_mut(land_id).last_mana_produced = Some(produced);
601 });
602 }
603 self.finish_mana_undo_action(undo_record, produced_count);
604 passed_count = 0;
605 }
606 MainPhaseAction::UntapMana(land_id) => {
607 let action_space = action_space
608 .as_ref()
609 .expect("mana undo priority action requires action space");
610 self.log_priority_response(
611 game,
612 priority_player,
613 &self.describe_priority_action(game, priority_action, None),
614 );
615 if !action_space.untappable_lands.contains(&land_id) {
616 crate::agent::notify_all_agents(
617 agents,
618 crate::agent::GameLogEvent::warning(
619 "Illegal action ignored: land can't be untapped for mana rollback",
620 )
621 .with_player(priority_player),
622 );
623 passed_count += 1;
624 priority_player = game.next_player(priority_player);
625 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
626 game.turn.priority_player = priority_player;
627 });
628 continue;
629 }
630 self.with_shared_state_mutation(game, agents, |this, game, _agents| {
631 this.undo_mana_action(game, priority_player, land_id);
632 });
633 passed_count = 0;
634 }
635 MainPhaseAction::ActivateAbility(card_id, ability_idx) => {
636 agents[priority_player.index()].clear_pass_until();
637 let action_space = action_space
638 .as_ref()
639 .expect("ability priority action requires action space");
640 self.invalidate_mana_undo_for_player(priority_player);
641 self.log_priority_response(
642 game,
643 priority_player,
644 &self.describe_priority_action(game, priority_action, Some(ability_idx)),
645 );
646 if !action_space
647 .activatable
648 .iter()
649 .any(|a| a.card_id == card_id && a.ability_index == ability_idx)
650 {
651 crate::agent::notify_all_agents(
652 agents,
653 crate::agent::GameLogEvent::warning(
654 "Illegal action ignored: ability not activatable",
655 )
656 .with_player(priority_player),
657 );
658 passed_count += 1;
659 priority_player = game.next_player(priority_player);
660 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
661 game.turn.priority_player = priority_player;
662 });
663 continue;
664 }
665 let activated =
666 self.with_shared_state_mutation(game, agents, |this, game, agents| {
667 if ability_idx == STATIC_ALTERNATIVE_ABILITY_INDEX {
668 let can_play_sorcery = is_main_phase
669 && priority_player == game.active_player()
670 && game.stack.is_empty();
671 let (ab, sa) = this.prepare_static_alternative_activated_ability(
672 game,
673 priority_player,
674 card_id,
675 can_play_sorcery,
676 )?;
677 return this
678 .play_prepared_activated_ability_on_stack(
679 game,
680 agents,
681 priority_player,
682 card_id,
683 &ab,
684 sa,
685 )
686 .then_some(PlaySpellAbilityResult::AbilityActivated);
687 }
688 let ability_text = game
689 .card(card_id)
690 .activated_abilities
691 .iter()
692 .find(|ab| ab.ability_index == ability_idx)
693 .map(|ab| ab.ability_text.clone())?;
694 let mut sa = crate::spellability::build_spell_ability(
695 game,
696 card_id,
697 &ability_text,
698 priority_player,
699 );
700 sa.is_activated = true;
701 this.play_spell_ability(
702 game,
703 agents,
704 priority_player,
705 PreparedSpellAbility {
706 spell_ability: sa,
707 activated_ability_index: Some(ability_idx),
708 static_alternative_cost_prepared: false,
709 },
710 )
711 });
712 if activated.is_some() {
713 self.with_shared_state_mutation(game, agents, |this, game, agents| {
717 this.process_triggers(game, agents);
718 });
719 passed_count = 0;
720 }
721 }
722 }
723 }
724 self.with_shared_state_mutation(game, agents, |_this, game, _agents| {
725 game.turn.priority_player = game.active_player();
726 });
727 }
728}