Skip to main content

manabrew_agent_interface/agent_impl/
mod.rs

1use std::collections::HashMap;
2
3use forge_foundation::{ManaAtom, ZoneType};
4use manabrew_engine::agent::notification::GameNotification;
5use manabrew_engine::agent::{
6    BinaryChoiceKind, CombatCostAction, GameEntity, ManaCostAction, PlayerAgent,
7    PriorityActionSpace, RollSwapChoice, TargetChoice,
8};
9use manabrew_engine::card::CounterType;
10use manabrew_engine::combat::DefenderId;
11use manabrew_engine::game::GameState;
12use manabrew_engine::ids::{CardId, PlayerId};
13use manabrew_engine::mana::ManaPool;
14use manabrew_engine::player::actions::player_action::AbilityRef;
15use manabrew_engine::player::actions::PlayerAction as EnginePlayerAction;
16
17use crate::game_log_event::GameLogEntryDto;
18use crate::game_snapshot_event::GameSnapshotEventDto;
19use crate::game_view_dto::{card_to_dto, CardDto, GameViewDto, GameViewDtoExt, StepKind};
20use crate::ids_codec::{card_id_str, parse_card_id, parse_player_id, player_id_str};
21use crate::mana_action_id::{mana_ability_actions, parse_tap_action_id};
22use crate::prompt::*;
23
24mod choices;
25mod combat;
26mod costs;
27mod library;
28mod targeting;
29
30/// Match a mana symbol letter (e.g. "U") or a full color name (e.g. "Blue")
31/// against a list of color strings.  Handles the Blue/U mismatch where the
32/// mana symbol "U" doesn't match the first character of "Blue".
33pub(crate) fn find_matching_color<'a>(
34    pending: &str,
35    colors: impl Iterator<Item = &'a String>,
36) -> Option<String> {
37    let mana_to_name: &[(&str, &str)] = &[
38        ("W", "White"),
39        ("U", "Blue"),
40        ("B", "Black"),
41        ("R", "Red"),
42        ("G", "Green"),
43        ("C", "Colorless"),
44    ];
45    colors
46        .into_iter()
47        .find(|c| {
48            // Direct case-insensitive match (covers both "U"=="U" and "Blue"=="Blue")
49            c.eq_ignore_ascii_case(pending)
50            // Mana symbol → full name lookup (covers "U" matching "Blue")
51            || mana_to_name.iter().any(|(sym, name)| {
52                pending.eq_ignore_ascii_case(sym) && c.eq_ignore_ascii_case(name)
53            })
54            // Full name → mana symbol lookup (covers "Blue" matching "U")
55            || mana_to_name.iter().any(|(sym, name)| {
56                pending.eq_ignore_ascii_case(name) && c.eq_ignore_ascii_case(sym)
57            })
58        })
59        .cloned()
60}
61
62pub(crate) fn parse_express_mana_choice(color: Option<&str>) -> Option<u16> {
63    color
64        .map(|color| ManaAtom::from_name(&color.to_ascii_lowercase()))
65        .filter(|&atom| atom != 0)
66}
67
68/// Answers the prompts a `PromptAgent` builds.
69///
70pub trait Responder {
71    fn respond(&mut self, prompt: AgentPrompt) -> ClientToServerMessage;
72    fn present(&mut self, _message: &AgentMessage) {}
73    fn await_ack(&mut self) -> ClientToServerMessage {
74        ClientToServerMessage::Response {
75            prompt_id: 0,
76            action: PromptOutput::DiceRolled(DiceRolledOutput::DiceRolledAcknowledged),
77        }
78    }
79    fn send_log(&mut self, _entry: GameLogEntryDto) {}
80    fn send_snapshot(&mut self, _snapshot: GameSnapshotEventDto) {}
81}
82
83pub struct PromptAgent<R: Responder> {
84    pub player_id: PlayerId,
85    pub game_id: String,
86    pub responder: R,
87    pending_prompt: Option<AgentPrompt>,
88    pub(crate) latest_view: Option<GameViewDto>,
89    source_cards: HashMap<CardId, CardDto>,
90    pub pass_until: Option<manabrew_engine::agent::PassUntilTarget>,
91    conceded: bool,
92    next_prompt_id: u32,
93    pub(crate) targeting_cancellable: bool,
94    pub(crate) targeting_cancelled: bool,
95}
96
97impl<R: Responder> PromptAgent<R> {
98    pub fn new(player_id: PlayerId, game_id: String, responder: R) -> Self {
99        Self {
100            player_id,
101            game_id,
102            responder,
103            pending_prompt: None,
104            latest_view: None,
105            source_cards: HashMap::new(),
106            pass_until: None,
107            conceded: false,
108            next_prompt_id: 0,
109            targeting_cancellable: false,
110            targeting_cancelled: false,
111        }
112    }
113
114    fn build_prompt(&mut self, inner: PromptInput, source: Option<CardId>) -> AgentPrompt {
115        self.next_prompt_id += 1;
116        let source_card = source.and_then(|card_id| self.source_cards.get(&card_id).cloned());
117        let source_ability_text = source_card.as_ref().and_then(|card| {
118            self.latest_view
119                .as_ref()?
120                .stack
121                .iter()
122                .rev()
123                .find(|entry| entry.source_id == card.id)?
124                .source_ability_text
125                .clone()
126        });
127        AgentPrompt {
128            prompt_id: self.next_prompt_id,
129            deciding_player_id: player_id_str(self.player_id),
130            source_card,
131            source_ability_text,
132            input: inner,
133        }
134    }
135
136    pub(crate) fn send_prompt(&mut self, inner: PromptInput, source: Option<CardId>) {
137        let prompt = self.build_prompt(inner, source);
138        self.emit_state();
139        self.responder
140            .present(&AgentMessage::Prompt(prompt.clone()));
141        self.pending_prompt = Some(prompt);
142    }
143
144    pub(crate) fn recv_action(&mut self) -> PromptOutput {
145        let prompt = self
146            .pending_prompt
147            .take()
148            .expect("recv_action called without a pending prompt");
149        if self.conceded {
150            return Self::default_pass();
151        }
152        loop {
153            match self.responder.respond(prompt.clone()) {
154                ClientToServerMessage::Response { prompt_id: 0, .. } => {
155                    return Self::default_pass();
156                }
157                ClientToServerMessage::Response { prompt_id, action } => {
158                    if prompt_id != prompt.prompt_id {
159                        self.reject(
160                            &prompt,
161                            ProtocolErrorCode::StalePrompt,
162                            format!(
163                                "response for prompt {prompt_id}, open prompt is {}",
164                                prompt.prompt_id
165                            ),
166                        );
167                        continue;
168                    }
169                    match prompt.input.validate_response(&action) {
170                        Ok(()) => return action,
171                        Err(ResponseViolation::WrongPromptType) => {
172                            self.reject(
173                                &prompt,
174                                ProtocolErrorCode::WrongPromptType,
175                                "response output does not match the prompt type".to_string(),
176                            );
177                        }
178                        Err(ResponseViolation::UnknownActionId(id)) => {
179                            self.reject(
180                                &prompt,
181                                ProtocolErrorCode::UnknownActionId,
182                                format!("action id {id:?} was not advertised by the prompt"),
183                            );
184                        }
185                        Err(ResponseViolation::CancelNotAllowed) => {
186                            self.reject(
187                                &prompt,
188                                ProtocolErrorCode::CancelNotAllowed,
189                                "this prompt is not cancellable".to_string(),
190                            );
191                        }
192                    }
193                }
194                ClientToServerMessage::Directive { directive } => {
195                    self.handle_directive(directive);
196                    return Self::default_pass();
197                }
198            }
199        }
200    }
201
202    fn default_pass() -> PromptOutput {
203        PromptOutput::ChooseAction(ChooseActionOutput::Pass {
204            until: None,
205            exhaust_stack: false,
206        })
207    }
208
209    fn reject(&mut self, prompt: &AgentPrompt, code: ProtocolErrorCode, message: String) {
210        self.responder.present(&AgentMessage::Error(ProtocolError {
211            code,
212            message,
213            prompt_id: Some(prompt.prompt_id),
214        }));
215        self.responder
216            .present(&AgentMessage::Prompt(prompt.clone()));
217    }
218
219    fn handle_directive(&mut self, directive: DirectiveInput) {
220        match directive {
221            DirectiveInput::Concede => self.conceded = true,
222            DirectiveInput::RequestRestore { .. }
223            | DirectiveInput::RestoreVote { .. }
224            | DirectiveInput::SetSnapshotRecording { .. } => {}
225        }
226    }
227
228    pub(crate) fn present_prompt(&mut self, inner: PromptInput, source: Option<CardId>) {
229        let prompt = self.build_prompt(inner, source);
230        self.emit_state();
231        self.responder.present(&AgentMessage::Prompt(prompt));
232    }
233
234    pub(crate) fn emit_state(&mut self) {
235        let game_view = self.view();
236        self.responder
237            .present(&AgentMessage::State(StateUpdate { game_view }));
238    }
239
240    pub(crate) fn emit_display(&mut self, event: DisplayEvent) {
241        self.responder.present(&AgentMessage::Display(event));
242    }
243
244    pub(crate) fn view(&self) -> GameViewDto {
245        self.latest_view.clone().unwrap_or_else(|| GameViewDto {
246            game_id: self.game_id.clone(),
247            step: StepKind::Main1,
248            ..Default::default()
249        })
250    }
251
252    pub(crate) fn card_ids(cards: &[CardId]) -> Vec<String> {
253        cards.iter().map(|&c| card_id_str(c)).collect()
254    }
255
256    pub(crate) fn player_ids(players: &[PlayerId]) -> Vec<String> {
257        players.iter().map(|&p| player_id_str(p)).collect()
258    }
259
260    pub(crate) fn attack_targets_to_dtos(
261        defenders: &[DefenderId],
262    ) -> Vec<crate::prompt::AttackTargetDto> {
263        use crate::prompt::AttackTargetKind;
264        defenders
265            .iter()
266            .map(|d| match d {
267                DefenderId::Player(pid) => crate::prompt::AttackTargetDto {
268                    id: format!("player-{}", pid.0),
269                    label: format!("Player {}", pid.0),
270                    kind: AttackTargetKind::Player,
271                },
272                // The Rust engine can't distinguish a planeswalker from a
273                // battle yet; approximate any permanent target as a walker.
274                DefenderId::Permanent(cid) => crate::prompt::AttackTargetDto {
275                    id: format!("card-{}", cid.0),
276                    label: format!("Permanent {}", cid.0),
277                    kind: AttackTargetKind::Planeswalker,
278                },
279            })
280            .collect()
281    }
282
283    fn alt_cost_kind(alt: manabrew_engine::spellability::AlternativeCost) -> AlternativeCostKind {
284        use manabrew_engine::spellability::AlternativeCost as A;
285        match alt {
286            A::Flashback => AlternativeCostKind::Flashback,
287            A::Spectacle => AlternativeCostKind::Spectacle,
288            A::Evoke => AlternativeCostKind::Evoke,
289            A::Dash => AlternativeCostKind::Dash,
290            A::Blitz => AlternativeCostKind::Blitz,
291            A::Escape => AlternativeCostKind::Escape,
292            A::Overload => AlternativeCostKind::Overload,
293            A::Madness => AlternativeCostKind::Madness,
294            A::Foretell => AlternativeCostKind::Foretell,
295            A::Emerge => AlternativeCostKind::Emerge,
296            A::Suspend => AlternativeCostKind::Suspend,
297            A::Morph => AlternativeCostKind::Morph,
298            A::Megamorph => AlternativeCostKind::Megamorph,
299            A::Bestow => AlternativeCostKind::Bestow,
300            A::Warp => AlternativeCostKind::Warp,
301            A::SacrificeAlt => AlternativeCostKind::SacrificeAlt,
302            A::Plot => AlternativeCostKind::Plot,
303            A::Awaken => AlternativeCostKind::Awaken,
304            A::Disturb => AlternativeCostKind::Disturb,
305            A::Harmonize => AlternativeCostKind::Harmonize,
306            A::Freerunning => AlternativeCostKind::Freerunning,
307            A::Impending => AlternativeCostKind::Impending,
308            A::Mayhem => AlternativeCostKind::Mayhem,
309            A::MTMtE => AlternativeCostKind::MTMtE,
310            A::Mutate => AlternativeCostKind::Mutate,
311            A::Prowl => AlternativeCostKind::Prowl,
312            A::Sneak => AlternativeCostKind::Sneak,
313            A::Surge => AlternativeCostKind::Surge,
314            A::WebSlinging => AlternativeCostKind::WebSlinging,
315            A::Plotted => AlternativeCostKind::Plotted,
316        }
317    }
318
319    fn play_mode_dto(mode: &manabrew_engine::agent::PlayCardMode) -> (PlayCardMode, String) {
320        use manabrew_engine::agent::PlayCardMode as E;
321        match mode {
322            E::Normal => (PlayCardMode::Normal, "Cast normally".to_string()),
323            E::BackFaceLand => (
324                PlayCardMode::BackFaceLand,
325                "Play back face as land".to_string(),
326            ),
327            E::RoomRightSplit => (PlayCardMode::RoomRightSplit, "Cast right room".to_string()),
328            E::StaticAlternative => (
329                PlayCardMode::StaticAlternative,
330                "Cast with alternative cost".to_string(),
331            ),
332            E::ForetellExile => (
333                PlayCardMode::ForetellExile,
334                "Foretell (exile face-down)".to_string(),
335            ),
336            E::UnlockDoor => (PlayCardMode::UnlockDoor, "Unlock door".to_string()),
337            E::Alternative(alt) => (
338                PlayCardMode::Alternative {
339                    cost: Self::alt_cost_kind(*alt),
340                },
341                format!("Cast with {alt:?}"),
342            ),
343        }
344    }
345
346    fn play_mode_key(mode: &manabrew_engine::agent::PlayCardMode) -> String {
347        use manabrew_engine::agent::PlayCardMode as E;
348        match mode {
349            E::Normal => "normal".to_string(),
350            E::BackFaceLand => "backFaceLand".to_string(),
351            E::RoomRightSplit => "roomRightSplit".to_string(),
352            E::StaticAlternative => "staticAlternative".to_string(),
353            E::ForetellExile => "foretellExile".to_string(),
354            E::UnlockDoor => "unlockDoor".to_string(),
355            E::Alternative(alt) => format!("alternative:{}", format!("{alt:?}").to_lowercase()),
356        }
357    }
358
359    fn parse_play_mode(mode_str: &str) -> Option<manabrew_engine::agent::PlayCardMode> {
360        use manabrew_engine::agent::PlayCardMode;
361        use manabrew_engine::spellability::AlternativeCost as A;
362        match mode_str {
363            "normal" => Some(PlayCardMode::Normal),
364            "backFaceLand" => Some(PlayCardMode::BackFaceLand),
365            "staticAlternative" => Some(PlayCardMode::StaticAlternative),
366            "foretellExile" => Some(PlayCardMode::ForetellExile),
367            "unlockDoor" => Some(PlayCardMode::UnlockDoor),
368            "roomRightSplit" => Some(PlayCardMode::RoomRightSplit),
369            s if s.starts_with("alternative:") => {
370                let alt = match &s["alternative:".len()..] {
371                    "flashback" => A::Flashback,
372                    "spectacle" => A::Spectacle,
373                    "evoke" => A::Evoke,
374                    "dash" => A::Dash,
375                    "blitz" => A::Blitz,
376                    "escape" => A::Escape,
377                    "overload" => A::Overload,
378                    "madness" => A::Madness,
379                    "foretell" => A::Foretell,
380                    "emerge" => A::Emerge,
381                    "suspend" => A::Suspend,
382                    "morph" => A::Morph,
383                    "megamorph" => A::Megamorph,
384                    "bestow" => A::Bestow,
385                    "warp" => A::Warp,
386                    "sacrificealt" => A::SacrificeAlt,
387                    "plot" => A::Plot,
388                    "awaken" => A::Awaken,
389                    "disturb" => A::Disturb,
390                    "harmonize" => A::Harmonize,
391                    "freerunning" => A::Freerunning,
392                    "impending" => A::Impending,
393                    "mayhem" => A::Mayhem,
394                    "mtmte" => A::MTMtE,
395                    "mutate" => A::Mutate,
396                    "prowl" => A::Prowl,
397                    "sneak" => A::Sneak,
398                    "surge" => A::Surge,
399                    "webslinging" => A::WebSlinging,
400                    "plotted" => A::Plotted,
401                    _ => return None,
402                };
403                Some(PlayCardMode::Alternative(alt))
404            }
405            _ => None,
406        }
407    }
408
409    pub(crate) fn parse_defender_id(id: &str, possible: &[DefenderId]) -> Option<DefenderId> {
410        if let Some(rest) = id.strip_prefix("player-") {
411            let idx: u32 = rest.parse().ok()?;
412            possible
413                .iter()
414                .find(|d| matches!(d, DefenderId::Player(p) if p.0 == idx))
415                .copied()
416        } else if let Some(rest) = id.strip_prefix("card-") {
417            let idx: u32 = rest.parse().ok()?;
418            possible
419                .iter()
420                .find(|d| matches!(d, DefenderId::Permanent(c) if c.0 == idx))
421                .copied()
422        } else {
423            None
424        }
425    }
426
427    pub(crate) fn recv_card_choice_or_first(&mut self, valid: &[CardId]) -> Option<CardId> {
428        match self.recv_action() {
429            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::Cancel) => {
430                self.targeting_cancelled = true;
431                None
432            }
433            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::BoardTargets { chosen }) => {
434                chosen.into_iter().find_map(|r| match r.kind {
435                    TargetKind::Card => parse_card_id(&r.id),
436                    _ => None,
437                })
438            }
439            _ => valid.first().copied(),
440        }
441    }
442
443    pub(crate) fn recv_player_choice_or_first(&mut self, valid: &[PlayerId]) -> Option<PlayerId> {
444        match self.recv_action() {
445            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::Cancel) => {
446                self.targeting_cancelled = true;
447                None
448            }
449            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::BoardTargets { chosen }) => {
450                chosen.into_iter().find_map(|r| match r.kind {
451                    TargetKind::Player => parse_player_id(&r.id),
452                    _ => None,
453                })
454            }
455            _ => valid.first().copied(),
456        }
457    }
458
459    pub(crate) fn recv_spell_choice_or_first(&mut self, valid: &[u32]) -> Option<u32> {
460        match self.recv_action() {
461            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::Cancel) => {
462                self.targeting_cancelled = true;
463                None
464            }
465            PromptOutput::ChooseBoardTargets(ChooseBoardTargetsOutput::BoardTargets { chosen }) => {
466                chosen.into_iter().find_map(|r| match r.kind {
467                    TargetKind::Spell => crate::ids_codec::parse_stack_id(&r.id),
468                    _ => None,
469                })
470            }
471            _ => valid.first().copied(),
472        }
473    }
474}
475
476impl<R: Responder> PlayerAgent for PromptAgent<R> {
477    fn choose_targets_for(
478        &mut self,
479        sa: &mut manabrew_engine::spellability::SpellAbility,
480        game: &GameState,
481        mana_pools: &[ManaPool],
482    ) -> bool {
483        self.targeting_cancelled = false;
484        let ok = manabrew_engine::spellability::choose_targets_by_kind(self, sa, game, mana_pools);
485        ok && !self.targeting_cancelled
486    }
487
488    fn set_targeting_cancellable(&mut self, cancellable: bool) {
489        self.targeting_cancellable = cancellable;
490    }
491
492    fn get_pass_until(&self) -> Option<manabrew_engine::agent::PassUntilTarget> {
493        self.pass_until
494    }
495
496    fn clear_pass_until(&mut self) {
497        self.pass_until = None;
498    }
499
500    fn snapshot_state(&mut self, game: &GameState, mana_pools: &[ManaPool]) {
501        self.source_cards = game
502            .cards
503            .iter()
504            .map(|card| (card.id, card_to_dto(game, card.id)))
505            .collect();
506        self.latest_view = Some(GameViewDto::from_engine(
507            game,
508            mana_pools,
509            self.player_id,
510            &self.game_id,
511        ));
512    }
513
514    fn mulligan_decision(
515        &mut self,
516        player: PlayerId,
517        hand: &[CardId],
518        mulligan_count: u32,
519    ) -> bool {
520        choices::mulligan_decision(self, player, hand, mulligan_count)
521    }
522
523    fn mulligan_decision_send(&mut self, player: PlayerId, hand: &[CardId], mulligan_count: u32) {
524        choices::mulligan_decision_send(self, player, hand, mulligan_count);
525    }
526
527    fn mulligan_decision_recv(
528        &mut self,
529        player: PlayerId,
530        hand: &[CardId],
531        mulligan_count: u32,
532    ) -> bool {
533        choices::mulligan_decision_recv(self, player, hand, mulligan_count)
534    }
535
536    fn choose_cards_to_bottom(
537        &mut self,
538        player: PlayerId,
539        hand: &[CardId],
540        count: usize,
541    ) -> Vec<CardId> {
542        choices::choose_cards_to_bottom(self, player, hand, count)
543    }
544
545    fn choose_cards_to_bottom_send(&mut self, player: PlayerId, hand: &[CardId], count: usize) {
546        choices::choose_cards_to_bottom_send(self, player, hand, count);
547    }
548
549    fn choose_cards_to_bottom_recv(
550        &mut self,
551        player: PlayerId,
552        hand: &[CardId],
553        count: usize,
554    ) -> Vec<CardId> {
555        choices::choose_cards_to_bottom_recv(self, player, hand, count)
556    }
557
558    fn choose_action(
559        &mut self,
560        _player: PlayerId,
561        action_space: Option<&PriorityActionSpace>,
562        request_action_space: &mut dyn FnMut() -> PriorityActionSpace,
563    ) -> EnginePlayerAction {
564        if self.conceded {
565            return EnginePlayerAction::Concede;
566        }
567        let requested_action_space;
568        let action_space = match action_space {
569            Some(action_space) => action_space,
570            None => {
571                requested_action_space = request_action_space();
572                &requested_action_space
573            }
574        };
575        let playable = &action_space.playable;
576        let untappable_lands = &action_space.untappable_lands;
577        let _activatable = &action_space.activatable;
578        let untappable_land_ids: Vec<String> =
579            untappable_lands.iter().map(|&c| card_id_str(c)).collect();
580
581        let mut actions: Vec<AvailableAction> = Vec::new();
582        for play in playable.iter() {
583            let card_id = card_id_str(play.card_id);
584            let (mode, label) = Self::play_mode_dto(&play.mode);
585            let key = Self::play_mode_key(&play.mode);
586            actions.push(AvailableAction {
587                id: format!("cast:{card_id}:{key}"),
588                kind: AvailableActionKind::Cast {
589                    card_id: card_id.clone(),
590                    mode,
591                    label,
592                },
593            });
594        }
595        for a in action_space
596            .activatable
597            .iter()
598            .chain(action_space.mana_abilities.iter())
599        {
600            let card_id = card_id_str(a.card_id);
601            if a.is_mana_ability {
602                actions.extend(
603                    mana_ability_actions(
604                        &card_id,
605                        a.ability_index,
606                        &a.description,
607                        a.cost.clone(),
608                        a.produced_mana.clone(),
609                        a.produced_mana_amount,
610                    )
611                    .into_iter()
612                    .map(|(id, info)| AvailableAction {
613                        id,
614                        kind: AvailableActionKind::ActivateAbility(info),
615                    }),
616                );
617            } else {
618                actions.push(AvailableAction {
619                    id: format!("ability:{card_id}:{}", a.ability_index),
620                    kind: AvailableActionKind::ActivateAbility(ActivatableAbilityInfo {
621                        card_id,
622                        ability_index: a.ability_index,
623                        description: a.description.clone(),
624                        cost: a.cost.clone(),
625                        is_mana_ability: false,
626                        is_class_level_up: Some(a.is_class_level_up),
627                        produced_mana: None,
628                    }),
629                });
630            }
631        }
632        for card_id in &untappable_land_ids {
633            actions.push(AvailableAction {
634                id: format!("untap:{card_id}"),
635                kind: AvailableActionKind::UndoMana {
636                    card_id: card_id.clone(),
637                },
638            });
639        }
640
641        self.send_prompt(
642            PromptInput::ChooseAction(
643                manabrew_protocol::prompts::choose_action::ChooseActionInput { actions },
644            ),
645            None,
646        );
647        let prompt = self
648            .pending_prompt
649            .take()
650            .expect("choose_action called without a pending prompt");
651        let action = match self.responder.respond(prompt) {
652            ClientToServerMessage::Response { action, .. } => action,
653            ClientToServerMessage::Directive {
654                directive: DirectiveInput::Concede,
655            } => return EnginePlayerAction::Concede,
656            ClientToServerMessage::Directive {
657                directive:
658                    DirectiveInput::RequestRestore { .. }
659                    | DirectiveInput::RestoreVote { .. }
660                    | DirectiveInput::SetSnapshotRecording { .. },
661            } => Self::default_pass(),
662        };
663        match action {
664            PromptOutput::ChooseAction(ChooseActionOutput::Act { action_id }) => {
665                if let Some(rest) = action_id.strip_prefix("cast:") {
666                    let (id_part, mode) = rest.split_once(':').unwrap_or((rest, "normal"));
667                    let resolved = parse_card_id(id_part).and_then(|cid| {
668                        Self::parse_play_mode(mode)
669                            .and_then(|m| {
670                                playable
671                                    .iter()
672                                    .copied()
673                                    .find(|play| play.card_id == cid && play.mode == m)
674                            })
675                            .or_else(|| playable.iter().copied().find(|play| play.card_id == cid))
676                    });
677                    resolved
678                        .map(EnginePlayerAction::CastSpell)
679                        .unwrap_or(EnginePlayerAction::PassPriority)
680                } else if let Some(rest) = action_id.strip_prefix("tap:") {
681                    let tap = parse_tap_action_id(rest);
682                    match parse_card_id(tap.card_id) {
683                        Some(cid) => EnginePlayerAction::ActivateMana(
684                            cid,
685                            tap.ability_index,
686                            parse_express_mana_choice(tap.color),
687                        ),
688                        None => EnginePlayerAction::PassPriority,
689                    }
690                } else if let Some(rest) = action_id.strip_prefix("ability:") {
691                    let (id_part, idx) = rest.split_once(':').unwrap_or((rest, ""));
692                    match (parse_card_id(id_part), idx.parse::<usize>()) {
693                        (Some(cid), Ok(ability_index)) => {
694                            EnginePlayerAction::ActivateAbility(AbilityRef {
695                                card_id: cid,
696                                ability_index,
697                            })
698                        }
699                        _ => EnginePlayerAction::PassPriority,
700                    }
701                } else if let Some(id_part) = action_id.strip_prefix("untap:") {
702                    parse_card_id(id_part)
703                        .map(EnginePlayerAction::UndoMana)
704                        .unwrap_or(EnginePlayerAction::PassPriority)
705                } else {
706                    EnginePlayerAction::PassPriority
707                }
708            }
709            PromptOutput::ChooseAction(ChooseActionOutput::Pass { until, .. }) => {
710                self.pass_until = until.and_then(|u| {
711                    Some(manabrew_engine::agent::PassUntilTarget {
712                        player: crate::ids_codec::parse_player_id(&u.player_id)?,
713                        phase: crate::game_view_dto::step_to_phase(u.phase),
714                        through_combat: u.through_combat,
715                    })
716                });
717                EnginePlayerAction::PassPriority
718            }
719            _ => EnginePlayerAction::PassPriority,
720        }
721    }
722
723    fn choose_attackers(
724        &mut self,
725        player: PlayerId,
726        available: &[CardId],
727        possible_defenders: &[DefenderId],
728    ) -> Vec<(CardId, DefenderId)> {
729        combat::choose_attackers(self, player, available, possible_defenders)
730    }
731
732    fn choose_blockers(
733        &mut self,
734        player: PlayerId,
735        attackers: &[CardId],
736        available_blockers: &[CardId],
737        max_blockers: Option<usize>,
738    ) -> Vec<(CardId, CardId)> {
739        combat::choose_blockers(self, player, attackers, available_blockers, max_blockers)
740    }
741
742    fn choose_damage_assignment_order(
743        &mut self,
744        player: PlayerId,
745        attacker: CardId,
746        blockers: &[CardId],
747    ) -> Vec<CardId> {
748        combat::choose_damage_assignment_order(self, player, attacker, blockers)
749    }
750
751    fn assign_combat_damage(
752        &mut self,
753        game: &GameState,
754        player: PlayerId,
755        attacker: CardId,
756        blockers_in_order: &[CardId],
757        defender_id: Option<DefenderId>,
758        damage_to_assign: i32,
759    ) -> Vec<(Option<CardId>, i32)> {
760        let attacker_has_deathtouch = game.card(attacker).has_deathtouch();
761        combat::choose_combat_damage_assignment(
762            self,
763            player,
764            attacker,
765            blockers_in_order,
766            defender_id,
767            damage_to_assign,
768            attacker_has_deathtouch,
769        )
770    }
771
772    fn choose_target_player(
773        &mut self,
774        player: PlayerId,
775        valid: &[PlayerId],
776        sa: Option<&manabrew_engine::spellability::SpellAbility>,
777    ) -> Option<PlayerId> {
778        let source = sa.and_then(|s| s.source);
779        let intent = sa
780            .map(crate::game_view_dto::targeting_intent_of)
781            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
782        let hostile = crate::game_view_dto::intent_is_hostile(intent);
783        targeting::choose_target_player(self, player, valid, source, hostile, intent)
784    }
785
786    fn choose_target_card(
787        &mut self,
788        player: PlayerId,
789        valid: &[CardId],
790        sa: Option<&manabrew_engine::spellability::SpellAbility>,
791    ) -> Option<CardId> {
792        let source = sa.and_then(|s| s.source);
793        let intent = sa
794            .map(crate::game_view_dto::targeting_intent_of)
795            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
796        let hostile = crate::game_view_dto::intent_is_hostile(intent);
797        targeting::choose_target_card(self, player, valid, source, hostile, intent)
798    }
799
800    fn choose_target_card_from_zone(
801        &mut self,
802        player: PlayerId,
803        zone: ZoneType,
804        valid: &[CardId],
805        sa: Option<&manabrew_engine::spellability::SpellAbility>,
806    ) -> Option<CardId> {
807        let source = sa.and_then(|s| s.source);
808        let intent = sa
809            .map(crate::game_view_dto::targeting_intent_of)
810            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
811        let hostile = crate::game_view_dto::intent_is_hostile(intent);
812        targeting::choose_target_card_from_zone(self, player, zone, valid, source, hostile, intent)
813    }
814
815    fn choose_target_any(
816        &mut self,
817        player: PlayerId,
818        valid_players: &[PlayerId],
819        valid_cards: &[CardId],
820        sa: Option<&manabrew_engine::spellability::SpellAbility>,
821    ) -> TargetChoice {
822        let source = sa.and_then(|s| s.source);
823        let intent = sa
824            .map(crate::game_view_dto::targeting_intent_of)
825            .unwrap_or(crate::game_view_dto::TargetingIntent::Hostile);
826        let hostile = crate::game_view_dto::intent_is_hostile(intent);
827        targeting::choose_target_any(
828            self,
829            player,
830            valid_players,
831            valid_cards,
832            source,
833            hostile,
834            intent,
835        )
836    }
837
838    fn choose_sacrifice(
839        &mut self,
840        player: PlayerId,
841        valid: &[CardId],
842        source: Option<CardId>,
843    ) -> Option<CardId> {
844        targeting::choose_sacrifice(self, player, valid, source)
845    }
846
847    fn reveal_cards(
848        &mut self,
849        game: &GameState,
850        _player: PlayerId,
851        cards: &[CardId],
852        zone: ZoneType,
853        owner: PlayerId,
854        message_prefix: Option<&str>,
855    ) {
856        choices::reveal_cards(self, game, cards, zone, owner, message_prefix)
857    }
858
859    fn choose_scry(
860        &mut self,
861        game: &GameState,
862        player: PlayerId,
863        source: Option<CardId>,
864        cards: &[CardId],
865    ) -> Vec<Vec<CardId>> {
866        library::choose_scry(self, game, player, source, cards)
867    }
868
869    fn choose_surveil(
870        &mut self,
871        game: &GameState,
872        player: PlayerId,
873        source: Option<CardId>,
874        cards: &[CardId],
875    ) -> Vec<Vec<CardId>> {
876        library::choose_surveil(self, game, player, source, cards)
877    }
878
879    fn choose_dig(
880        &mut self,
881        game: &GameState,
882        player: PlayerId,
883        valid: &[CardId],
884        max: usize,
885        optional: bool,
886    ) -> Vec<CardId> {
887        library::choose_dig(self, game, player, valid, max, optional)
888    }
889
890    fn choose_discard(&mut self, player: PlayerId, hand: &[CardId], num: usize) -> Vec<CardId> {
891        choices::choose_discard(self, player, hand, num)
892    }
893
894    fn choose_discard_any_number(
895        &mut self,
896        player: PlayerId,
897        hand: &[CardId],
898        min: usize,
899        max: usize,
900    ) -> Vec<CardId> {
901        choices::choose_discard_any_number(self, player, hand, min, max)
902    }
903
904    fn choose_legend_keep(&mut self, player: PlayerId, duplicates: &[CardId]) -> CardId {
905        choices::choose_legend_keep(self, player, duplicates)
906    }
907
908    fn choose_target_spell(
909        &mut self,
910        player: PlayerId,
911        valid: &[u32],
912        source: Option<CardId>,
913    ) -> Option<u32> {
914        targeting::choose_target_spell(self, player, valid, source)
915    }
916
917    fn choose_mode(
918        &mut self,
919        player: PlayerId,
920        descriptions: &[String],
921        min: usize,
922        max: usize,
923        source_card_id: Option<CardId>,
924    ) -> Vec<usize> {
925        choices::choose_mode(self, player, descriptions, min, max, source_card_id)
926    }
927
928    fn choose_spell_abilities_for_effect(
929        &mut self,
930        player: PlayerId,
931        abilities: &[manabrew_engine::spellability::SpellAbility],
932        num: usize,
933    ) -> Vec<usize> {
934        choices::choose_spell_abilities_for_effect(self, player, abilities, num)
935    }
936
937    fn get_ability_to_play(
938        &mut self,
939        player: PlayerId,
940        abilities: &[manabrew_engine::spellability::SpellAbility],
941    ) -> Option<usize> {
942        choices::get_ability_to_play(self, player, abilities)
943    }
944
945    fn choose_single_entity_for_effect(
946        &mut self,
947        player: PlayerId,
948        valid: &[GameEntity],
949        is_optional: bool,
950    ) -> Option<GameEntity> {
951        choices::choose_single_entity_for_effect(self, player, valid, is_optional)
952    }
953
954    fn choose_entities_for_effect(
955        &mut self,
956        player: PlayerId,
957        candidates: &[GameEntity],
958        min: usize,
959        max: usize,
960    ) -> Vec<GameEntity> {
961        choices::choose_entities_for_effect(self, player, candidates, min, max)
962    }
963
964    fn choose_single_replacement_effect(
965        &mut self,
966        player: PlayerId,
967        descriptions: &[String],
968    ) -> usize {
969        choices::choose_single_replacement_effect(self, player, descriptions)
970    }
971
972    fn confirm_replacement_effect(
973        &mut self,
974        player: PlayerId,
975        question: &str,
976        effect_description: &str,
977        source: Option<CardId>,
978    ) -> bool {
979        choices::confirm_replacement_effect(self, player, question, effect_description, source)
980    }
981
982    fn choose_optional_trigger(
983        &mut self,
984        player: PlayerId,
985        description: &str,
986        source: Option<CardId>,
987        api: Option<manabrew_engine::ability::api_type::ApiType>,
988    ) -> bool {
989        choices::choose_optional_trigger(self, player, description, source, api)
990    }
991
992    fn confirm_action(
993        &mut self,
994        player: PlayerId,
995        mode: Option<&str>,
996        message: &str,
997        options: &[String],
998        source: Option<CardId>,
999        api: Option<manabrew_engine::ability::api_type::ApiType>,
1000    ) -> bool {
1001        choices::confirm_action(self, player, mode, message, options, source, api)
1002    }
1003
1004    fn confirm_payment(
1005        &mut self,
1006        player: PlayerId,
1007        cost_kind: &str,
1008        message: &str,
1009        source: Option<CardId>,
1010        api: Option<manabrew_engine::ability::api_type::ApiType>,
1011    ) -> bool {
1012        choices::confirm_payment(self, player, cost_kind, message, source, api)
1013    }
1014
1015    fn pay_cost_to_prevent_effect(
1016        &mut self,
1017        player: PlayerId,
1018        cost_kind: &str,
1019        message: &str,
1020        source: Option<CardId>,
1021        api: Option<manabrew_engine::ability::api_type::ApiType>,
1022        can_pay: bool,
1023        targets: &[manabrew_engine::agent::GameEntity],
1024        effect_text: &str,
1025    ) -> bool {
1026        choices::pay_cost_to_prevent_effect(
1027            self,
1028            player,
1029            cost_kind,
1030            message,
1031            source,
1032            api,
1033            can_pay,
1034            targets,
1035            effect_text,
1036        )
1037    }
1038
1039    fn choose_binary(
1040        &mut self,
1041        player: PlayerId,
1042        question: &str,
1043        kind: BinaryChoiceKind,
1044        default_choice: Option<bool>,
1045        source: Option<CardId>,
1046        api: Option<manabrew_engine::ability::api_type::ApiType>,
1047    ) -> bool {
1048        choices::choose_binary(self, player, question, kind, default_choice, source, api)
1049    }
1050
1051    fn choose_phyrexian_pay_life(
1052        &mut self,
1053        player: PlayerId,
1054        color: &str,
1055        source: Option<CardId>,
1056    ) -> bool {
1057        costs::choose_phyrexian_pay_life(self, player, color, source)
1058    }
1059
1060    fn choose_kicker(
1061        &mut self,
1062        player: PlayerId,
1063        kicker_cost: &str,
1064        source: Option<CardId>,
1065    ) -> bool {
1066        costs::choose_kicker(self, player, kicker_cost, source)
1067    }
1068
1069    fn choose_buyback(
1070        &mut self,
1071        player: PlayerId,
1072        buyback_cost: &str,
1073        source: Option<CardId>,
1074    ) -> bool {
1075        costs::choose_buyback(self, player, buyback_cost, source)
1076    }
1077
1078    fn choose_multikicker(
1079        &mut self,
1080        player: PlayerId,
1081        cost: &str,
1082        max_kicks: u32,
1083        source: Option<CardId>,
1084    ) -> u32 {
1085        costs::choose_multikicker(self, player, cost, max_kicks, source)
1086    }
1087
1088    fn choose_replicate(
1089        &mut self,
1090        player: PlayerId,
1091        cost: &str,
1092        max_replicates: u32,
1093        source: Option<CardId>,
1094    ) -> u32 {
1095        costs::choose_replicate(self, player, cost, max_replicates, source)
1096    }
1097
1098    fn choose_color(&mut self, player: PlayerId, valid_colors: &[String]) -> Option<String> {
1099        choices::choose_color(self, player, valid_colors)
1100    }
1101
1102    fn choose_colors(
1103        &mut self,
1104        player: PlayerId,
1105        valid_colors: &[String],
1106        min: usize,
1107        max: usize,
1108    ) -> Vec<String> {
1109        choices::choose_colors(self, player, valid_colors, min, max)
1110    }
1111
1112    fn choose_cards_for_effect(
1113        &mut self,
1114        player: PlayerId,
1115        valid: &[CardId],
1116        min: usize,
1117        max: usize,
1118    ) -> Vec<CardId> {
1119        choices::choose_cards_for_effect(self, player, valid, min, max)
1120    }
1121
1122    fn choose_single_card_for_zone_change(
1123        &mut self,
1124        game: &GameState,
1125        player: PlayerId,
1126        valid: &[CardId],
1127        select_prompt: &str,
1128        is_optional: bool,
1129    ) -> Option<CardId> {
1130        choices::choose_single_card_for_zone_change(
1131            self,
1132            game,
1133            player,
1134            valid,
1135            select_prompt,
1136            is_optional,
1137        )
1138    }
1139
1140    fn choose_cards_for_zone_change(
1141        &mut self,
1142        game: &GameState,
1143        player: PlayerId,
1144        valid: &[CardId],
1145        min: usize,
1146        max: usize,
1147        select_prompt: &str,
1148    ) -> Vec<CardId> {
1149        choices::choose_cards_for_zone_change(self, game, player, valid, min, max, select_prompt)
1150    }
1151
1152    fn choose_type(
1153        &mut self,
1154        player: PlayerId,
1155        type_category: &str,
1156        valid_types: &[String],
1157    ) -> Option<String> {
1158        choices::choose_type(self, player, type_category, valid_types)
1159    }
1160
1161    fn choose_counter_type(
1162        &mut self,
1163        player: PlayerId,
1164        options: &[CounterType],
1165        prompt: &str,
1166    ) -> Option<CounterType> {
1167        choices::choose_counter_type(self, player, options, prompt)
1168    }
1169
1170    fn choose_card_name(&mut self, player: PlayerId, valid_names: &[String]) -> Option<String> {
1171        choices::choose_card_name(self, player, valid_names)
1172    }
1173
1174    fn choose_number(
1175        &mut self,
1176        player: PlayerId,
1177        source: Option<CardId>,
1178        title: &str,
1179        description: Option<&str>,
1180        min: i32,
1181        max: i32,
1182    ) -> Option<i32> {
1183        choices::choose_number(self, player, source, title, description, min, max)
1184    }
1185
1186    fn choose_number_from_list(
1187        &mut self,
1188        player: PlayerId,
1189        choices: &[i32],
1190        message: &str,
1191        source_card_id: Option<CardId>,
1192    ) -> Option<i32> {
1193        choices::choose_number_from_list(self, player, choices, message, source_card_id)
1194    }
1195
1196    fn choose_roll_to_ignore(
1197        &mut self,
1198        player: PlayerId,
1199        rolls: &[i32],
1200        source: Option<CardId>,
1201    ) -> Option<i32> {
1202        choices::choose_roll_to_ignore(self, player, rolls, source)
1203    }
1204
1205    fn choose_roll_to_swap(
1206        &mut self,
1207        player: PlayerId,
1208        rolls: &[i32],
1209        source: Option<CardId>,
1210    ) -> Option<i32> {
1211        choices::choose_roll_to_swap(self, player, rolls, source)
1212    }
1213
1214    fn choose_dice_to_reroll(
1215        &mut self,
1216        player: PlayerId,
1217        rolls: &[i32],
1218        source: Option<CardId>,
1219    ) -> Vec<i32> {
1220        choices::choose_dice_to_reroll(self, player, rolls, source)
1221    }
1222
1223    fn choose_roll_to_modify(
1224        &mut self,
1225        player: PlayerId,
1226        rolls: &[i32],
1227        source: Option<CardId>,
1228    ) -> Option<i32> {
1229        choices::choose_roll_to_modify(self, player, rolls, source)
1230    }
1231
1232    fn choose_roll_swap_value(
1233        &mut self,
1234        player: PlayerId,
1235        current_result: i32,
1236        power: i32,
1237        toughness: i32,
1238        source: Option<CardId>,
1239    ) -> Option<RollSwapChoice> {
1240        choices::choose_roll_swap_value(self, player, current_result, power, toughness, source)
1241    }
1242
1243    fn flip_coin_call(&mut self, player: PlayerId) -> bool {
1244        choices::flip_coin_call(self, player)
1245    }
1246
1247    fn pay_combat_cost(
1248        &mut self,
1249        player: PlayerId,
1250        attacker: CardId,
1251        cost: i32,
1252        description: &str,
1253        mana_ability_options: &[manabrew_engine::agent::ManaAbilityOption],
1254        tappable_lands: &[CardId],
1255        untappable_lands: &[CardId],
1256        mana_pool_total: i32,
1257    ) -> CombatCostAction {
1258        combat::pay_combat_cost(
1259            self,
1260            player,
1261            attacker,
1262            cost,
1263            description,
1264            mana_ability_options,
1265            tappable_lands,
1266            untappable_lands,
1267            mana_pool_total,
1268        )
1269    }
1270
1271    fn choose_improvise(
1272        &mut self,
1273        player: PlayerId,
1274        untapped_artifacts: &[CardId],
1275        remaining_cost: &forge_foundation::ManaCost,
1276        source: Option<CardId>,
1277    ) -> Vec<CardId> {
1278        costs::choose_improvise(self, player, untapped_artifacts, remaining_cost, source)
1279    }
1280
1281    fn choose_convoke(
1282        &mut self,
1283        player: PlayerId,
1284        untapped_creatures: &[CardId],
1285        remaining_cost: &forge_foundation::ManaCost,
1286        source: Option<CardId>,
1287    ) -> Vec<CardId> {
1288        costs::choose_convoke(self, player, untapped_creatures, remaining_cost, source)
1289    }
1290
1291    fn pay_mana_cost(
1292        &mut self,
1293        player: PlayerId,
1294        card_id: CardId,
1295        card_name: &str,
1296        mana_cost: &str,
1297        mana_cost_display: &str,
1298        _mana_cost_checkpoint: &str,
1299        can_confirm_from_pool: bool,
1300        _allow_reserved_source_reuse: bool,
1301        _reserved_sacrifices: &[CardId],
1302        mana_ability_options: &[manabrew_engine::agent::ManaAbilityOption],
1303        tappable_lands: &[CardId],
1304        untappable_lands: &[CardId],
1305        mana_pool: &ManaPool,
1306    ) -> ManaCostAction {
1307        costs::pay_mana_cost(
1308            self,
1309            player,
1310            card_id,
1311            card_name,
1312            mana_cost,
1313            mana_cost_display,
1314            can_confirm_from_pool,
1315            mana_ability_options,
1316            tappable_lands,
1317            untappable_lands,
1318            mana_pool,
1319        )
1320    }
1321
1322    fn await_display_ack(&mut self) {
1323        if self.conceded {
1324            return;
1325        }
1326        if let ClientToServerMessage::Directive { directive } = self.responder.await_ack() {
1327            self.handle_directive(directive);
1328        }
1329    }
1330
1331    fn specify_mana_combo(
1332        &mut self,
1333        player: PlayerId,
1334        available_colors: &[String],
1335        amount: usize,
1336        source: Option<CardId>,
1337        express_choice: Option<u16>,
1338    ) -> Vec<String> {
1339        costs::specify_mana_combo(
1340            self,
1341            player,
1342            available_colors,
1343            amount,
1344            source,
1345            express_choice,
1346        )
1347    }
1348
1349    fn exert_attackers(&mut self, player: PlayerId, attackers: &[CardId]) -> Vec<CardId> {
1350        combat::exert_attackers(self, player, attackers)
1351    }
1352
1353    fn enlist_attackers(&mut self, player: PlayerId, attackers: &[CardId]) -> Vec<CardId> {
1354        combat::enlist_attackers(self, player, attackers)
1355    }
1356
1357    fn choose_reorder_library(
1358        &mut self,
1359        game: &GameState,
1360        player: PlayerId,
1361        cards: &[CardId],
1362    ) -> Vec<CardId> {
1363        library::choose_reorder_library(self, game, player, cards)
1364    }
1365
1366    fn help_pay_assist(&mut self, player: PlayerId, card_name: &str, max_generic: u32) -> u32 {
1367        choices::help_pay_assist(self, player, card_name, max_generic)
1368    }
1369
1370    fn choose_random_discard(
1371        &mut self,
1372        player: PlayerId,
1373        hand: &[CardId],
1374        num: usize,
1375    ) -> Vec<CardId> {
1376        choices::choose_random_discard(self, player, hand, num)
1377    }
1378
1379    fn choose_land_or_spell(&mut self, player: PlayerId) -> Option<bool> {
1380        choices::choose_land_or_spell(self, player)
1381    }
1382
1383    fn notify(&mut self, event: GameNotification) {
1384        match event {
1385            GameNotification::Event(log_event) => {
1386                self.responder
1387                    .send_log(GameLogEntryDto::from_event(log_event));
1388            }
1389            GameNotification::CardPlayed {
1390                player,
1391                card_id,
1392                card_name,
1393                set_code,
1394            } => {
1395                self.emit_display(DisplayEvent::CardPlayed {
1396                    card_id: card_id_str(card_id),
1397                    card_name,
1398                    set_code,
1399                    player_id: player_id_str(player),
1400                });
1401                self.emit_state();
1402            }
1403            GameNotification::TurnChanged {
1404                active_player,
1405                turn_number,
1406            } => {
1407                let player_id = player_id_str(active_player);
1408                let active_player_name = self
1409                    .latest_view
1410                    .as_ref()
1411                    .and_then(|v| v.players.iter().find(|p| p.id == player_id))
1412                    .map(|p| p.name.clone())
1413                    .unwrap_or_else(|| format!("Player {}", active_player.0));
1414                self.responder.send_log(GameLogEntryDto::from_event(
1415                    manabrew_engine::agent::GameLogEvent::rule(format!(
1416                        "TURN {turn_number} — {active_player_name}"
1417                    ))
1418                    .with_player(active_player),
1419                ));
1420                self.emit_display(DisplayEvent::TurnChanged {
1421                    active_player_id: player_id,
1422                    active_player_name,
1423                    turn_number,
1424                });
1425                self.emit_state();
1426            }
1427            GameNotification::PhaseChanged { .. } | GameNotification::StateChanged => {
1428                self.emit_state();
1429            }
1430            GameNotification::PriorityChanged { .. } => {
1431                self.emit_state();
1432            }
1433            GameNotification::FirstPlayerRoll {
1434                sides,
1435                rounds,
1436                winner,
1437            } => {
1438                let view = self.view();
1439                let winner_id = player_id_str(winner);
1440                let mut entries = Vec::new();
1441                let last_round = rounds.len().saturating_sub(1);
1442                for (round_index, round) in rounds.into_iter().enumerate() {
1443                    for (pid, value) in round {
1444                        let id = player_id_str(pid);
1445                        let name = view
1446                            .players
1447                            .iter()
1448                            .find(|p| p.id == id)
1449                            .map(|p| p.name.clone())
1450                            .unwrap_or_else(|| id.clone());
1451                        entries.push(manabrew_protocol::prompts::dice_rolled::DiceRollEntry {
1452                            label: Some(name),
1453                            highlighted: round_index == last_round && id == winner_id,
1454                            player_id: Some(id),
1455                            round: round_index as u32,
1456                            natural_results: vec![value],
1457                            final_results: vec![value],
1458                            ignored_rolls: vec![],
1459                        });
1460                    }
1461                }
1462                self.present_prompt(
1463                    PromptInput::DiceRolled(
1464                        manabrew_protocol::prompts::dice_rolled::DiceRolledInput {
1465                            presentation: PromptPresentation {
1466                                title: "Roll for first player".to_string(),
1467                                description: None,
1468                                text: None,
1469                                targets: Vec::new(),
1470                            },
1471                            sides,
1472                            rolls: entries,
1473                        },
1474                    ),
1475                    None,
1476                );
1477            }
1478            GameNotification::DiceRolled {
1479                player,
1480                sides,
1481                natural_results,
1482                final_results,
1483                ignored_rolls,
1484                source_card_id,
1485            } => {
1486                self.present_prompt(
1487                    PromptInput::DiceRolled(
1488                        manabrew_protocol::prompts::dice_rolled::DiceRolledInput {
1489                            presentation: PromptPresentation {
1490                                title: "Dice roll".to_string(),
1491                                description: None,
1492                                text: None,
1493                                targets: Vec::new(),
1494                            },
1495                            sides,
1496                            rolls: vec![manabrew_protocol::prompts::dice_rolled::DiceRollEntry {
1497                                label: None,
1498                                player_id: Some(player_id_str(player)),
1499                                round: 0,
1500                                natural_results,
1501                                final_results,
1502                                ignored_rolls,
1503                                highlighted: false,
1504                            }],
1505                        },
1506                    ),
1507                    source_card_id,
1508                );
1509            }
1510            GameNotification::SnapshotCreated {
1511                checkpoint_id,
1512                label,
1513            } => {
1514                if let Some(view) = self.latest_view.clone() {
1515                    self.responder.send_snapshot(GameSnapshotEventDto::new(
1516                        checkpoint_id,
1517                        label,
1518                        view,
1519                    ));
1520                }
1521            }
1522            GameNotification::GameOver => {
1523                self.emit_state();
1524                self.present_prompt(
1525                    PromptInput::GameOver(manabrew_protocol::prompts::game_over::GameOverInput {}),
1526                    None,
1527                );
1528            }
1529            GameNotification::ManaPaymentResolved { .. } => {}
1530            GameNotification::ActivatedAbilityPaymentFailed { .. } => {
1531                self.emit_state();
1532            }
1533        }
1534    }
1535}