Skip to main content

manabrew_engine/agent/
mod.rs

1use crate::agent::notification::GameNotification;
2use crate::card::CounterType;
3use crate::combat::DefenderId;
4use crate::cost::payment_decision::PaymentDecision;
5use crate::cost::CostPart;
6use crate::game::GameState;
7use crate::ids::{CardId, PlayerId};
8use crate::mana::ManaPool;
9use crate::player::actions::PlayerAction;
10use crate::spellability::SpellAbility;
11
12pub mod attach_ai;
13pub mod creature_evaluator;
14pub mod game_log;
15pub mod notification;
16pub mod types;
17
18pub use game_log::*;
19pub use types::*;
20
21/// A held pass-priority-until target: keep auto-passing until `player` reaches
22/// `phase` in turn order.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct PassUntilTarget {
25    pub player: PlayerId,
26    pub phase: forge_foundation::PhaseType,
27    pub through_combat: bool,
28}
29
30/// Trait for player decision-making. Decouples the engine from UI/AI.
31/// Implementations can be interactive (prompt user), AI, or network-driven.
32pub trait PlayerAgent {
33    /// Called before each agent decision point with the current game state.
34    /// Override this to capture snapshots for a UI or network layer.
35    fn snapshot_state(&mut self, _game: &GameState, _mana_pools: &[ManaPool]) {}
36
37    /// Poll and clear any pending snapshot-restore request from this agent.
38    fn take_restore_request(&mut self) -> Option<u64> {
39        None
40    }
41
42    fn reveal_cards(
43        &mut self,
44        _game: &GameState,
45        _player: PlayerId,
46        _cards: &[CardId],
47        _zone: forge_foundation::ZoneType,
48        _owner: PlayerId,
49        _message_prefix: Option<&str>,
50    ) {
51    }
52
53    /// Returns the `(player, phase)` slot this player auto-passes until.
54    /// A stop is genuinely `(player, phase)`: "pass until Player2's end" is
55    /// distinct from "pass until my end". The declaration is HELD across
56    /// priority windows — the engine does not consume it each pass — and is
57    /// cleared only when the target is reached or a meaningful event occurs.
58    /// `None` = no standing pass-until (prompt normally).
59    fn get_pass_until(&self) -> Option<PassUntilTarget> {
60        None
61    }
62
63    /// Clear the pass-until declaration (target reached, cast, attackers
64    /// declared, …).
65    fn clear_pass_until(&mut self) {}
66
67    /// Choose whether to keep the current opening hand or mulligan.
68    /// `mulligan_count` is the number of mulligans already taken this game.
69    /// Returns true to keep, false to mulligan.
70    fn mulligan_decision(&mut self, player: PlayerId, hand: &[CardId], mulligan_count: u32)
71        -> bool;
72
73    /// Fire the mulligan prompt without blocking for a response.
74    /// Default: no-op. UI agents override to decouple prompt dispatch from
75    /// response collection so multiple players can be prompted in parallel.
76    fn mulligan_decision_send(
77        &mut self,
78        _player: PlayerId,
79        _hand: &[CardId],
80        _mulligan_count: u32,
81    ) {
82    }
83
84    /// Block waiting for the mulligan response previously sent via
85    /// `mulligan_decision_send`. Default falls back to the blocking
86    /// `mulligan_decision` so agents that don't split send/recv still work.
87    fn mulligan_decision_recv(
88        &mut self,
89        player: PlayerId,
90        hand: &[CardId],
91        mulligan_count: u32,
92    ) -> bool {
93        self.mulligan_decision(player, hand, mulligan_count)
94    }
95
96    /// London Mulligan: after keeping, choose `count` cards from hand to put
97    /// on the bottom of the library. Returns exactly `count` card IDs.
98    /// Default: picks the first `count` cards (suitable for simple AI agents).
99    fn choose_cards_to_bottom(
100        &mut self,
101        _player: PlayerId,
102        hand: &[CardId],
103        count: usize,
104    ) -> Vec<CardId> {
105        hand.iter().copied().take(count).collect()
106    }
107
108    /// Fire the put-back prompt without blocking. Default: no-op.
109    fn choose_cards_to_bottom_send(&mut self, _player: PlayerId, _hand: &[CardId], _count: usize) {}
110
111    /// Block waiting for the put-back response. Default falls back to the
112    /// blocking `choose_cards_to_bottom`.
113    fn choose_cards_to_bottom_recv(
114        &mut self,
115        player: PlayerId,
116        hand: &[CardId],
117        count: usize,
118    ) -> Vec<CardId> {
119        self.choose_cards_to_bottom(player, hand, count)
120    }
121
122    /// Choose a main-phase action: play a card from hand, tap a land for mana, untap a land,
123    /// activate an ability, or pass.
124    /// `tappable_lands` lists untapped lands available for tapping.
125    /// `untappable_lands` lists source IDs whose most recent mana action can be undone.
126    /// `activatable` lists (card_id, ability_index) pairs for activated abilities that can be used.
127    fn choose_action(
128        &mut self,
129        player: PlayerId,
130        action_space: Option<&PriorityActionSpace>,
131        request_action_space: &mut dyn FnMut() -> PriorityActionSpace,
132    ) -> PlayerAction;
133
134    /// Choose attackers from available creatures, assigning each to a defender.
135    /// `possible_defenders` lists valid attack targets (opponent players + their planeswalkers).
136    /// Returns (attacker, defender) pairs.
137    fn choose_attackers(
138        &mut self,
139        player: PlayerId,
140        available: &[CardId],
141        possible_defenders: &[DefenderId],
142    ) -> Vec<(CardId, DefenderId)>;
143
144    /// Choose which attackers to exert.
145    /// Input is the subset of already-declared attackers that can pay an Exert
146    /// optional attack cost. Return a subset of `attackers`.
147    /// Default: choose none.
148    fn exert_attackers(&mut self, _player: PlayerId, _attackers: &[CardId]) -> Vec<CardId> {
149        vec![]
150    }
151
152    /// Choose which attackers to enlist.
153    /// Input is the subset of already-declared attackers that can pay an Enlist
154    /// optional attack cost. Return a subset of `attackers`.
155    /// Default: choose none.
156    fn enlist_attackers(&mut self, _player: PlayerId, _attackers: &[CardId]) -> Vec<CardId> {
157        vec![]
158    }
159
160    /// Choose blockers. Returns pairs of (blocker, attacker).
161    /// `max_blockers` is the BlockRestrict limit (if any) — agent should stop after this many.
162    fn choose_blockers(
163        &mut self,
164        player: PlayerId,
165        attackers: &[CardId],
166        available_blockers: &[CardId],
167        max_blockers: Option<usize>,
168    ) -> Vec<(CardId, CardId)>;
169
170    /// Choose one attacker for a specific blocker during sequential declaration.
171    ///
172    /// Return `Some(attacker_id)` to assign this blocker, or `None` to leave it
173    /// unassigned. Default behavior maps through `choose_blockers` for the single
174    /// blocker, preserving existing agent behavior when not overridden.
175    fn choose_blocker_for(
176        &mut self,
177        player: PlayerId,
178        attackers: &[CardId],
179        blocker: CardId,
180    ) -> Option<CardId> {
181        let pairs = self.choose_blockers(player, attackers, &[blocker], None);
182        pairs
183            .into_iter()
184            .find_map(|(b, a)| if b == blocker { Some(a) } else { None })
185    }
186
187    /// Choose the order in which an attacker assigns damage to its blockers.
188    /// The attacker must assign lethal damage to each blocker in order before
189    /// assigning damage to the next one.
190    /// Returns a permutation of `blockers` in the desired assignment order.
191    /// Default: return blockers as-is (no reordering).
192    fn choose_damage_assignment_order(
193        &mut self,
194        _player: PlayerId,
195        _attacker: CardId,
196        blockers: &[CardId],
197    ) -> Vec<CardId> {
198        blockers.to_vec()
199    }
200
201    /// Choose exact combat damage assignment for one blocked attacker.
202    ///
203    /// `blockers_in_order` are in assignment order. `defender_id` is provided
204    /// only when damage can legally be assigned to the defender (e.g. trample).
205    ///
206    /// Return pairs of `(assignee, damage)` where:
207    /// - `Some(card_id)` assigns to a blocker
208    /// - `None` assigns to defender
209    ///
210    fn assign_combat_damage(
211        &mut self,
212        game: &GameState,
213        _player: PlayerId,
214        attacker: CardId,
215        blockers_in_order: &[CardId],
216        defender_id: Option<DefenderId>,
217        damage_to_assign: i32,
218    ) -> Vec<(Option<CardId>, i32)> {
219        let mut out: Vec<(Option<CardId>, i32)> = Vec::new();
220        if damage_to_assign <= 0 {
221            return out;
222        }
223
224        let mut dmg_left = damage_to_assign;
225        let has_deathtouch = game.card(attacker).has_deathtouch();
226        let can_assign_to_defender = defender_id.is_some() && game.card(attacker).has_trample();
227        let mut last_blocker: Option<CardId> = None;
228
229        for &blocker_id in blockers_in_order {
230            if dmg_left <= 0 {
231                break;
232            }
233            if game.card(blocker_id).zone != forge_foundation::ZoneType::Battlefield {
234                continue;
235            }
236            if crate::staticability::static_ability_colorless_damage_source::target_is_protected_from_source(
237                &game.cards,
238                game.card(blocker_id),
239                game.card(attacker),
240            ) {
241                continue;
242            }
243            last_blocker = Some(blocker_id);
244
245            let blocker_card = game.card(blocker_id);
246            let is_indestructible = blocker_card.has_keyword("Indestructible");
247            let attacker_has_wither =
248                game.card(attacker).has_wither() || game.card(attacker).has_infect();
249            let lethal = if is_indestructible && !attacker_has_wither {
250                // Can't kill by damage — assign all remaining (mirrors maxDamage + 1)
251                dmg_left + 1
252            } else if has_deathtouch {
253                1
254            } else if blocker_card.type_line.is_planeswalker() {
255                blocker_card
256                    .counter_count(&crate::card::CounterType::Loyalty)
257                    .max(0)
258            } else {
259                (blocker_card.toughness() - blocker_card.damage).max(0)
260            };
261            let assign = lethal.min(dmg_left);
262            if assign > 0 {
263                out.push((Some(blocker_id), assign));
264                dmg_left -= assign;
265            }
266        }
267
268        if dmg_left > 0 {
269            if can_assign_to_defender {
270                out.push((None, dmg_left));
271            } else if let Some(last) = last_blocker {
272                if let Some((_, amount)) = out
273                    .iter_mut()
274                    .find(|(assignee, _)| assignee.map(|id| id == last).unwrap_or(false))
275                {
276                    *amount += dmg_left;
277                } else {
278                    out.push((Some(last), dmg_left));
279                }
280            }
281        }
282        out
283    }
284
285    fn choose_targets_for(
286        &mut self,
287        sa: &mut SpellAbility,
288        game: &GameState,
289        mana_pools: &[ManaPool],
290    ) -> bool;
291
292    fn set_targeting_cancellable(&mut self, _cancellable: bool) {}
293
294    /// Choose a target player (e.g. for Lightning Bolt targeting a player).
295    /// `sa` is the active spell ability context (source card, API type, etc.) for UI display.
296    fn choose_target_player(
297        &mut self,
298        player: PlayerId,
299        valid: &[PlayerId],
300        sa: Option<&SpellAbility>,
301    ) -> Option<PlayerId>;
302
303    /// Choose a target card (e.g. for Lightning Bolt targeting a creature).
304    fn choose_target_card(
305        &mut self,
306        player: PlayerId,
307        valid: &[CardId],
308        sa: Option<&SpellAbility>,
309    ) -> Option<CardId>;
310
311    /// Choose a target card from a specific zone (e.g. Raise Dead from graveyard).
312    fn choose_target_card_from_zone(
313        &mut self,
314        player: PlayerId,
315        _zone: forge_foundation::ZoneType,
316        valid: &[CardId],
317        sa: Option<&SpellAbility>,
318    ) -> Option<CardId> {
319        self.choose_target_card(player, valid, sa)
320    }
321
322    /// Choose a target that can be a player or a card (e.g. "any target").
323    fn choose_target_any(
324        &mut self,
325        player: PlayerId,
326        valid_players: &[PlayerId],
327        valid_cards: &[CardId],
328        sa: Option<&SpellAbility>,
329    ) -> TargetChoice;
330
331    /// Choose one permanent to sacrifice/select from the valid options.
332    /// `sa` is the active spell ability context for UI display.
333    /// Default picks the first (used by AI agents).
334    fn choose_sacrifice(
335        &mut self,
336        _player: PlayerId,
337        valid: &[CardId],
338        _source: Option<CardId>,
339    ) -> Option<CardId> {
340        valid.first().copied()
341    }
342
343    /// Distribute the looked-at Scry cards across the zones. Returns one ordered
344    /// pile per zone — `[top, bottom]` — where the last id in each pile is placed
345    /// on top of that pile. Default: keep everything on top, nothing to bottom.
346    fn choose_scry(
347        &mut self,
348        _game: &GameState,
349        _player: PlayerId,
350        _source: Option<CardId>,
351        cards: &[CardId],
352    ) -> Vec<Vec<CardId>> {
353        vec![cards.to_vec(), vec![]]
354    }
355
356    /// Distribute the looked-at Surveil cards: `[top, graveyard]` ordered piles.
357    /// Default: keep everything on top, nothing milled.
358    fn choose_surveil(
359        &mut self,
360        _game: &GameState,
361        _player: PlayerId,
362        _source: Option<CardId>,
363        cards: &[CardId],
364    ) -> Vec<Vec<CardId>> {
365        vec![cards.to_vec(), vec![]]
366    }
367
368    /// Choose up to `max` cards from `valid` to move to the destination zone (Dig effect).
369    /// `optional` means the player is not required to choose any.
370    /// Default: take first `max` cards.
371    fn choose_dig(
372        &mut self,
373        _game: &GameState,
374        _player: PlayerId,
375        valid: &[CardId],
376        max: usize,
377        _optional: bool,
378    ) -> Vec<CardId> {
379        valid.iter().copied().take(max).collect()
380    }
381
382    /// Choose an ordering for the top N cards being put back on the library (Ponder/Reorder).
383    /// Returns the cards in desired order: index 0 will be placed deepest, last will be on top.
384    /// Default: keep original order.
385    fn choose_reorder_library(
386        &mut self,
387        _game: &GameState,
388        _player: PlayerId,
389        cards: &[CardId],
390    ) -> Vec<CardId> {
391        cards.to_vec()
392    }
393
394    /// Choose which cards to discard from hand (for SP$ Discard effects).
395    /// `hand` is the full hand, `num` is how many must be discarded.
396    /// Default: discard the first `num` cards.
397    fn choose_discard(&mut self, _player: PlayerId, hand: &[CardId], num: usize) -> Vec<CardId> {
398        hand.iter().copied().take(num).collect()
399    }
400
401    /// Choose any number of cards to discard (for `AnyNumber$ True` on
402    /// SP$/DB$ Discard). The agent may pick 0..=hand.len() cards.
403    /// Default: discard `min` cards (the minimum forced amount).
404    fn choose_discard_any_number(
405        &mut self,
406        _player: PlayerId,
407        hand: &[CardId],
408        min: usize,
409        max: usize,
410    ) -> Vec<CardId> {
411        let _ = max;
412        hand.iter().copied().take(min).collect()
413    }
414
415    /// Choose cards to discard at random (for Mode$ Random discard, e.g. Hypnotic Specter).
416    /// The engine calls this instead of `choose_discard` when the discard is random.
417    /// Default: discard the first `num` cards (same as choose_discard).
418    /// Deterministic agents should override this to use their seeded RNG.
419    fn choose_random_discard(
420        &mut self,
421        _player: PlayerId,
422        hand: &[CardId],
423        num: usize,
424    ) -> Vec<CardId> {
425        hand.iter().copied().take(num).collect()
426    }
427
428    /// Choose a target spell on the stack (for SP$ Counter effects).
429    /// `valid` is a slice of stack entry IDs.
430    /// Default: target the first (topmost) spell.
431    fn choose_target_spell(
432        &mut self,
433        _player: PlayerId,
434        valid: &[u32],
435        _source: Option<CardId>,
436    ) -> Option<u32> {
437        valid.first().copied()
438    }
439
440    /// Choose N modes for a modal spell (SP$ Charm / Commands).
441    ///
442    /// `descriptions` — human-readable description of each mode.
443    /// `min` — minimum number of modes to choose.
444    /// `max` — maximum number of modes to choose.
445    ///
446    /// Returns indices into `descriptions` of the chosen modes, in order.
447    /// Default: choose the first `min` modes (index 0, 1, …).
448    fn choose_mode(
449        &mut self,
450        _player: PlayerId,
451        descriptions: &[String],
452        min: usize,
453        _max: usize,
454        _source_card_id: Option<CardId>,
455    ) -> Vec<usize> {
456        (0..min.min(descriptions.len())).collect()
457    }
458
459    fn choose_spell_abilities_for_effect(
460        &mut self,
461        _player: PlayerId,
462        abilities: &[SpellAbility],
463        num: usize,
464    ) -> Vec<usize> {
465        (0..num.min(abilities.len())).collect()
466    }
467
468    /// Choose exactly one entity (Card or Player) from a candidate list.
469    fn choose_single_entity_for_effect(
470        &mut self,
471        _player: PlayerId,
472        valid: &[GameEntity],
473        _is_optional: bool,
474    ) -> Option<GameEntity> {
475        valid.first().copied()
476    }
477
478    fn get_ability_to_play(
479        &mut self,
480        _player: PlayerId,
481        abilities: &[SpellAbility],
482    ) -> Option<usize> {
483        if abilities.is_empty() {
484            None
485        } else {
486            Some(0)
487        }
488    }
489
490    /// Choose which legendary permanent to keep when the legend rule applies.
491    /// `duplicates` contains all legendaries with the same name controlled by this player.
492    /// Returns the CardId of the one to keep; the rest are sacrificed.
493    fn choose_legend_keep(&mut self, _player: PlayerId, duplicates: &[CardId]) -> CardId {
494        duplicates[0]
495    }
496
497    /// Choose whether an optional triggered ability fires.
498    /// `description` is the trigger text shown to the player.
499    /// `source` is the engine card id of the source card (for UI display).
500    /// `api` is the spell ability API type.
501    /// Returns true to allow the trigger, false to decline.
502    /// Default: always allow (non-interactive agents accept all optional triggers).
503    fn choose_optional_trigger(
504        &mut self,
505        _player: PlayerId,
506        _description: &str,
507        _source: Option<CardId>,
508        _api: Option<crate::ability::api_type::ApiType>,
509    ) -> bool {
510        true
511    }
512
513    fn confirm_replacement_effect(
514        &mut self,
515        _player: PlayerId,
516        _question: &str,
517        _effect_description: &str,
518        _source: Option<CardId>,
519    ) -> bool {
520        true
521    }
522
523    /// Generic confirmation hook for optional effect prompts that don't yet
524    /// have a dedicated typed callback in the Rust agent interface.
525    ///
526    /// Returns true to accept/confirm, false to decline.
527    fn confirm_action(
528        &mut self,
529        _player: PlayerId,
530        _mode: Option<&str>,
531        _message: &str,
532        _options: &[String],
533        _source: Option<CardId>,
534        _api: Option<crate::ability::api_type::ApiType>,
535    ) -> bool {
536        false
537    }
538
539    fn confirm_payment(
540        &mut self,
541        player: PlayerId,
542        cost_kind: &str,
543        message: &str,
544        source: Option<CardId>,
545        api: Option<crate::ability::api_type::ApiType>,
546    ) -> bool {
547        let _ = (player, cost_kind, message, source, api);
548        true
549    }
550
551    fn pay_cost_to_prevent_effect(
552        &mut self,
553        player: PlayerId,
554        cost_kind: &str,
555        message: &str,
556        source: Option<CardId>,
557        api: Option<crate::ability::api_type::ApiType>,
558        can_pay: bool,
559        targets: &[GameEntity],
560        effect_text: &str,
561    ) -> bool {
562        let _ = (targets, effect_text);
563        if !can_pay {
564            return false;
565        }
566        self.confirm_payment(player, cost_kind, message, source, api)
567    }
568
569    fn choose_binary(
570        &mut self,
571        player: PlayerId,
572        question: &str,
573        kind: BinaryChoiceKind,
574        _default_choice: Option<bool>,
575        source: Option<CardId>,
576        api: Option<crate::ability::api_type::ApiType>,
577    ) -> bool {
578        let (left, right) = kind.labels();
579        self.confirm_action(
580            player,
581            Some(kind.as_str()),
582            question,
583            &[right.to_string(), left.to_string()],
584            source,
585            api,
586        )
587    }
588
589    /// Choose whether to pay the kicker cost for a spell.
590    /// `kicker_cost` is the mana cost string (e.g. "W", "2 R").
591    /// `source` is the name of the spell being cast (for UI display).
592    /// Returns true to kick, false to cast without kicker.
593    /// Default: don't kick (AI default).
594    fn choose_kicker(
595        &mut self,
596        _player: PlayerId,
597        _kicker_cost: &str,
598        _source: Option<CardId>,
599    ) -> bool {
600        false
601    }
602
603    /// Assist: another player asks if we'll help pay generic mana.
604    /// Returns how much generic mana to pay (0 = decline). Default: decline.
605    fn help_pay_assist(&mut self, _player: PlayerId, _card_name: &str, _max_generic: u32) -> u32 {
606        0
607    }
608
609    /// Choose whether to pay the buyback cost for a spell.
610    /// Returns true to pay buyback, false to cast normally.
611    /// Default: don't pay buyback.
612    fn choose_buyback(
613        &mut self,
614        _player: PlayerId,
615        _buyback_cost: &str,
616        _source: Option<CardId>,
617    ) -> bool {
618        false
619    }
620
621    /// Choose how many times to pay the multikicker cost.
622    /// `max_kicks` is the maximum affordable.
623    /// Returns the number of times to kick (0 to max_kicks).
624    /// Default: 0 (don't multikick).
625    fn choose_multikicker(
626        &mut self,
627        _player: PlayerId,
628        _cost: &str,
629        _max_kicks: u32,
630        _source: Option<CardId>,
631    ) -> u32 {
632        0
633    }
634
635    /// Choose how many times to pay the replicate cost.
636    /// `max_replicates` is the maximum affordable.
637    /// Returns the number of replicates.
638    /// Default: 0.
639    fn choose_replicate(
640        &mut self,
641        _player: PlayerId,
642        _cost: &str,
643        _max_replicates: u32,
644        _source: Option<CardId>,
645    ) -> u32 {
646        0
647    }
648
649    /// Choose a color (for ChooseColorEffect).
650    /// `valid_colors` lists the legal color choices (e.g. ["White","Blue","Black","Red","Green"]).
651    /// Default: pick the first valid color.
652    fn choose_color(&mut self, _player: PlayerId, valid_colors: &[String]) -> Option<String> {
653        valid_colors.first().cloned()
654    }
655
656    /// Choose one or more colors.
657    fn choose_colors(
658        &mut self,
659        _player: PlayerId,
660        valid_colors: &[String],
661        min: usize,
662        max: usize,
663    ) -> Vec<String> {
664        let hi = max.min(valid_colors.len());
665        let lo = min.min(hi);
666        valid_colors.iter().take(lo).cloned().collect()
667    }
668
669    /// Choose cards for an effect (ChooseCardEffect, CloneEffect, etc.).
670    /// `valid` lists eligible card IDs, `min`/`max` are the selection bounds.
671    /// Default: pick up to `max` from the front of `valid`.
672    fn choose_cards_for_effect(
673        &mut self,
674        _player: PlayerId,
675        valid: &[CardId],
676        _min: usize,
677        max: usize,
678    ) -> Vec<CardId> {
679        valid.iter().copied().take(max).collect()
680    }
681
682    /// Choose cards to tap for a `tapXType` cost that has a total-power floor
683    /// such as Crew. `card_powers` carries the effective tap-power value for
684    /// each candidate under the active ability; `card_sort_powers` carries the
685    /// normal net power value used by Forge's deterministic cost plumbing when
686    /// ordering candidates.
687    fn choose_tap_type_for_cost(
688        &mut self,
689        player: PlayerId,
690        valid: &[CardId],
691        _min_total_power: i32,
692        _card_powers: &[(CardId, i32)],
693        _card_sort_powers: &[(CardId, i32)],
694        _sa: Option<&SpellAbility>,
695    ) -> Vec<CardId> {
696        self.choose_cards_for_effect(player, valid, 1, valid.len())
697    }
698
699    /// Choose game entities (players and/or permanents) for an effect like Proliferate.
700    fn choose_entities_for_effect(
701        &mut self,
702        _player: PlayerId,
703        candidates: &[GameEntity],
704        _min: usize,
705        max: usize,
706    ) -> Vec<GameEntity> {
707        candidates.iter().copied().take(max).collect()
708    }
709
710    /// Choose a single card for hidden-origin zone changes (e.g. library search).
711    fn choose_single_card_for_zone_change(
712        &mut self,
713        _game: &GameState,
714        player: PlayerId,
715        valid: &[CardId],
716        _select_prompt: &str,
717        _is_optional: bool,
718    ) -> Option<CardId> {
719        self.choose_cards_for_effect(player, valid, 1, 1)
720            .into_iter()
721            .next()
722    }
723
724    /// Choose multiple cards for hidden-origin zone changes (e.g. tutor multi-select).
725    fn choose_cards_for_zone_change(
726        &mut self,
727        _game: &GameState,
728        player: PlayerId,
729        valid: &[CardId],
730        min: usize,
731        max: usize,
732        _select_prompt: &str,
733    ) -> Vec<CardId> {
734        self.choose_cards_for_effect(player, valid, min, max)
735    }
736
737    /// Choose a creature/card type (for ChooseType effect).
738    /// `type_category` is "Creature", "Card", "Land", etc.
739    /// `valid_types` lists the legal type choices.
740    /// Default: pick the first valid type.
741    fn choose_type(
742        &mut self,
743        _player: PlayerId,
744        _type_category: &str,
745        valid_types: &[String],
746    ) -> Option<String> {
747        valid_types.first().cloned()
748    }
749
750    /// Choose a counter type.
751    fn choose_counter_type(
752        &mut self,
753        _player: PlayerId,
754        options: &[CounterType],
755        _prompt: &str,
756    ) -> Option<CounterType> {
757        options.first().cloned()
758    }
759
760    /// Choose a card name (for NameCard effect).
761    /// `valid_names` lists the legal card name choices (for ChooseFromList mode).
762    /// Default: pick the first valid name.
763    fn choose_card_name(&mut self, _player: PlayerId, valid_names: &[String]) -> Option<String> {
764        valid_names.first().cloned()
765    }
766
767    /// Choose a number within `[min, max]`. `title`/`description` present the
768    /// choice and `source` is the card driving it (shown in the prompt).
769    /// Default: pick the minimum.
770    fn choose_number(
771        &mut self,
772        _player: PlayerId,
773        _source: Option<CardId>,
774        _title: &str,
775        _description: Option<&str>,
776        min: i32,
777        _max: i32,
778    ) -> Option<i32> {
779        Some(min)
780    }
781
782    /// Choose how many times to pay an optional keyword cost.
783    /// Default: decline optional keyword costs.
784    fn choose_number_for_keyword_cost(
785        &mut self,
786        _player: PlayerId,
787        _max: i32,
788        _prompt: &str,
789        _source: Option<CardId>,
790    ) -> i32 {
791        0
792    }
793
794    /// Choose one number from an explicit list of legal rolled values.
795    fn choose_number_from_list(
796        &mut self,
797        _player: PlayerId,
798        choices: &[i32],
799        _message: &str,
800        _source_card_id: Option<CardId>,
801    ) -> Option<i32> {
802        choices.first().copied()
803    }
804
805    /// Choose one die result from a rolled list to ignore.
806    fn choose_roll_to_ignore(
807        &mut self,
808        _player: PlayerId,
809        rolls: &[i32],
810        _source: Option<CardId>,
811    ) -> Option<i32> {
812        rolls.first().copied()
813    }
814
815    /// Choose one rolled result to exchange with a card's power or toughness.
816    fn choose_roll_to_swap(
817        &mut self,
818        _player: PlayerId,
819        rolls: &[i32],
820        _source: Option<CardId>,
821    ) -> Option<i32> {
822        rolls.first().copied()
823    }
824
825    /// Choose one or more dice to reroll from the current natural roll list.
826    fn choose_dice_to_reroll(
827        &mut self,
828        _player: PlayerId,
829        _rolls: &[i32],
830        _source: Option<CardId>,
831    ) -> Vec<i32> {
832        vec![]
833    }
834
835    /// Choose one rolled result to increment or decrement by 1.
836    fn choose_roll_to_modify(
837        &mut self,
838        _player: PlayerId,
839        rolls: &[i32],
840        _source: Option<CardId>,
841    ) -> Option<i32> {
842        rolls.first().copied()
843    }
844
845    /// Choose whether a swap should use power or toughness.
846    fn choose_roll_swap_value(
847        &mut self,
848        _player: PlayerId,
849        _current_result: i32,
850        _power: i32,
851        _toughness: i32,
852        _source: Option<CardId>,
853    ) -> Option<RollSwapChoice> {
854        Some(RollSwapChoice::Power)
855    }
856
857    /// Choose heads or tails for a coin flip.
858    /// Returns true for heads, false for tails.
859    /// Default: always call heads.
860    fn flip_coin_call(&mut self, _player: PlayerId) -> bool {
861        true
862    }
863
864    /// Choose whether to pay life instead of mana for a Phyrexian mana shard.
865    /// Returns true to pay 2 life, false to pay the color.
866    /// Default: always pay color (never pay life).
867    fn choose_phyrexian_pay_life(
868        &mut self,
869        _player: PlayerId,
870        _color: &str,
871        _source: Option<CardId>,
872    ) -> bool {
873        false
874    }
875
876    /// Pay an attack cost for a creature (Propaganda, Ghostly Prison).
877    /// Called in a loop: tap lands to build mana, then Pay or Decline.
878    fn pay_combat_cost(
879        &mut self,
880        _player: PlayerId,
881        _attacker: CardId,
882        _cost: i32,
883        _description: &str,
884        _mana_ability_options: &[ManaAbilityOption],
885        _tappable_lands: &[CardId],
886        _untappable_lands: &[CardId],
887        _mana_pool_total: i32,
888    ) -> CombatCostAction {
889        CombatCostAction::Decline
890    }
891
892    /// Choose graveyard cards to exile for Delve (reduces generic cost).
893    /// `valid` lists graveyard card IDs, `max` is the maximum that can be exiled.
894    /// Default: exile max cards (maximize cost reduction). The interactive UI
895    /// resolves delve inside the mana-payment session, not via this callback.
896    fn choose_delve(
897        &mut self,
898        _player: PlayerId,
899        valid: &[CardId],
900        max: usize,
901        _source: Option<CardId>,
902    ) -> Vec<CardId> {
903        valid.iter().copied().take(max).collect()
904    }
905
906    /// Choose artifacts to tap for Improvise (each pays {1} generic).
907    /// `untapped_artifacts` lists available artifacts to tap.
908    /// Default: don't improvise (AI default — auto-tap handles mana).
909    fn choose_improvise(
910        &mut self,
911        _player: PlayerId,
912        _untapped_artifacts: &[CardId],
913        _remaining_cost: &forge_foundation::ManaCost,
914        _source: Option<CardId>,
915    ) -> Vec<CardId> {
916        vec![]
917    }
918
919    /// Choose creatures to tap for Convoke (each pays {1} or a matching colored mana).
920    /// `untapped_creatures` lists available creatures to tap.
921    /// Default: don't convoke (AI default — auto-tap handles mana).
922    fn choose_convoke(
923        &mut self,
924        _player: PlayerId,
925        _untapped_creatures: &[CardId],
926        _remaining_cost: &forge_foundation::ManaCost,
927        _source: Option<CardId>,
928    ) -> Vec<CardId> {
929        vec![]
930    }
931
932    /// Pay a mana cost within a single payment session.
933    /// Called in a loop for manual interaction: tap lands to build mana, then
934    /// `Pay { auto: false }` or `Cancel`. Agents can also return
935    /// `Pay { auto: true }` to delegate the rest of the session to engine
936    /// auto-pay.
937    /// Default: always cancel.
938    fn pay_mana_cost(
939        &mut self,
940        _player: PlayerId,
941        _card_id: CardId,
942        _card_name: &str,
943        _mana_cost: &str,
944        _mana_cost_display: &str,
945        _mana_cost_checkpoint: &str,
946        _can_confirm_from_pool: bool,
947        _allow_reserved_source_reuse: bool,
948        _reserved_sacrifices: &[CardId],
949        _mana_ability_options: &[ManaAbilityOption],
950        _tappable_lands: &[CardId],
951        _untappable_lands: &[CardId],
952        _mana_pool: &ManaPool,
953    ) -> ManaCostAction {
954        ManaCostAction::AttemptedAndFailed
955    }
956
957    /// Block until this agent acknowledges a display-only prompt that
958    /// requires UI dwell time (e.g. dice roll animations). Default
959    /// implementation is a no-op — only human-driven transports need
960    /// to wait for an ack.
961    ///
962    /// Used to make multi-agent broadcasts run their UI in parallel:
963    /// the broadcast loop dispatches the prompt to every agent in one
964    /// pass (so all clients receive it simultaneously), then a second
965    /// pass calls `await_display_ack` on each agent so the engine
966    /// blocks until the slowest player finishes their animation.
967    fn await_display_ack(&mut self) {}
968
969    /// Decide how to pay a single cost part.
970    fn decide_cost_part(
971        &mut self,
972        _player: PlayerId,
973        _source: CardId,
974        _cost_part: &CostPart,
975        _game: &GameState,
976    ) -> Option<PaymentDecision> {
977        // TODO: Implement default decisions per CostPart variant,
978        None
979    }
980
981    /// Whether this agent pays each cost part immediately after deciding (true)
982    /// or batches all decisions first, then pays (false).
983    fn pays_right_after_decision(&self) -> bool {
984        false
985    }
986
987    /// Reorder cost parts before payment (for human players to choose payment order).
988    fn order_cost_parts(&mut self, parts: Vec<CostPart>) -> Vec<CostPart> {
989        parts
990    }
991
992    /// Specify mana color distribution for combo/any mana production.
993    /// `available_colors` lists which colors can be produced.
994    /// `amount` is the total mana to distribute across colors.
995    /// Returns a list of color letters (e.g. ["W", "W", "U"]) totaling `amount`.
996    /// Default: picks the color with least mana in pool for each unit (AI heuristic).
997    fn specify_mana_combo(
998        &mut self,
999        _player: PlayerId,
1000        available_colors: &[String],
1001        amount: usize,
1002        _source: Option<CardId>,
1003        _express_choice: Option<u16>,
1004    ) -> Vec<String> {
1005        // Default AI: pick first available color for all
1006        if let Some(first) = available_colors.first() {
1007            vec![first.clone(); amount]
1008        } else {
1009            vec!["C".to_string(); amount]
1010        }
1011    }
1012
1013    /// Choose whether to play a land or cast a spell when both are possible.
1014    /// Returns true for land, false for spell, None to pass.
1015    fn choose_land_or_spell(&mut self, player: PlayerId) -> Option<bool>;
1016
1017    /// Receive engine notifications for UI/game-log observers.
1018    /// Default is a no-op so simple agents do not need to handle them.
1019    fn notify(&mut self, _event: GameNotification) {}
1020
1021    /// Choose which replacement effect to apply when multiple effects match the same event.
1022    fn choose_single_replacement_effect(
1023        &mut self,
1024        _player: PlayerId,
1025        _descriptions: &[String],
1026    ) -> usize {
1027        0
1028    }
1029}
1030
1031/// A simple agent that always passes priority and makes no choices.
1032/// Useful for testing.
1033pub struct PassAgent;
1034
1035impl PlayerAgent for PassAgent {
1036    fn choose_targets_for(
1037        &mut self,
1038        _sa: &mut SpellAbility,
1039        _game: &GameState,
1040        _mana_pools: &[ManaPool],
1041    ) -> bool {
1042        true
1043    }
1044
1045    fn mulligan_decision(
1046        &mut self,
1047        _player: PlayerId,
1048        _hand: &[CardId],
1049        _mulligan_count: u32,
1050    ) -> bool {
1051        true
1052    }
1053
1054    fn choose_action(
1055        &mut self,
1056        _player: PlayerId,
1057        _action_space: Option<&PriorityActionSpace>,
1058        _request_action_space: &mut dyn FnMut() -> PriorityActionSpace,
1059    ) -> PlayerAction {
1060        PlayerAction::PassPriority
1061    }
1062
1063    fn choose_attackers(
1064        &mut self,
1065        _player: PlayerId,
1066        _available: &[CardId],
1067        _possible_defenders: &[DefenderId],
1068    ) -> Vec<(CardId, DefenderId)> {
1069        Vec::new() // no attackers
1070    }
1071
1072    fn choose_blockers(
1073        &mut self,
1074        _player: PlayerId,
1075        _attackers: &[CardId],
1076        _available_blockers: &[CardId],
1077        _max_blockers: Option<usize>,
1078    ) -> Vec<(CardId, CardId)> {
1079        Vec::new() // no blockers
1080    }
1081
1082    fn choose_target_player(
1083        &mut self,
1084        _player: PlayerId,
1085        valid: &[PlayerId],
1086        _sa: Option<&SpellAbility>,
1087    ) -> Option<PlayerId> {
1088        valid.first().copied()
1089    }
1090
1091    fn choose_target_card(
1092        &mut self,
1093        _player: PlayerId,
1094        valid: &[CardId],
1095        _sa: Option<&SpellAbility>,
1096    ) -> Option<CardId> {
1097        valid.first().copied()
1098    }
1099
1100    fn choose_target_any(
1101        &mut self,
1102        _player: PlayerId,
1103        valid_players: &[PlayerId],
1104        valid_cards: &[CardId],
1105        _sa: Option<&SpellAbility>,
1106    ) -> TargetChoice {
1107        if let Some(&pid) = valid_players.first() {
1108            TargetChoice::Player(pid)
1109        } else if let Some(&cid) = valid_cards.first() {
1110            TargetChoice::Card(cid)
1111        } else {
1112            TargetChoice::None
1113        }
1114    }
1115
1116    fn choose_sacrifice(
1117        &mut self,
1118        _player: PlayerId,
1119        valid: &[CardId],
1120        _source: Option<CardId>,
1121    ) -> Option<CardId> {
1122        valid.first().copied()
1123    }
1124
1125    fn choose_land_or_spell(&mut self, _player: PlayerId) -> Option<bool> {
1126        None
1127    }
1128}