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