Skip to main content

manabrew_engine/phase/
mod.rs

1//! Phase module — turn structure, phase handling, and untap logic.
2//!
3//! Mirrors Java's `forge.game.phase` package.
4
5pub mod extra_phase;
6pub mod extra_turn;
7pub mod phase_handler;
8pub mod phase_type;
9pub mod untap;
10
11use std::collections::HashMap;
12
13use forge_foundation::PhaseType;
14use serde::{Deserialize, Serialize};
15
16use crate::ids::{CardId, PlayerId};
17
18// Re-exports
19pub use extra_phase::ExtraPhase;
20pub use extra_turn::ExtraTurn;
21pub use phase_handler::PhaseHandler;
22
23/// A phase command — a deferred action to execute at a phase boundary.
24/// Mirrors Java's `GameCommand` callbacks stored in `Phase`.
25///
26/// In Java, these are `Runnable`-like objects that modify game state.
27/// In Rust, we represent them as an enum of known command types,
28/// since we can't store closures in serializable state.
29#[derive(Debug, Clone)]
30pub enum PhaseCommand {
31    /// Remove a continuous effect by its ID.
32    RemoveEffect(CardId),
33    /// Restore a card's controller to its owner.
34    RestoreController(CardId),
35    /// Remove granted keywords from a card.
36    RemoveGrantedKeywords(CardId),
37    /// Generic cleanup marker.
38    Cleanup(CardId),
39}
40
41/// Phase instance — stores commands that execute at phase boundaries.
42///
43/// Mirrors Java's `Phase` class. Each `Phase` in Java holds lists of
44/// `GameCommand` callbacks for "at <phase>", "until <phase>", and
45/// per-player "until <player's> next <phase>" effects.
46#[derive(Debug, Clone, Default)]
47pub struct Phase {
48    #[allow(dead_code)]
49    phase_type: Option<PhaseType>,
50    /// Commands to execute "at" this phase.
51    at: Vec<PhaseCommand>,
52    /// Commands to execute "until" this phase (remove effects).
53    until: Vec<PhaseCommand>,
54    /// Per-player commands to execute "until <player's> next <phase>".
55    until_map: HashMap<PlayerId, Vec<PhaseCommand>>,
56    /// Per-player commands registered for end-of-phase execution.
57    until_end_map: HashMap<PlayerId, Vec<PhaseCommand>>,
58    /// Per-player commands staged to be moved to until_end_map.
59    register_map: HashMap<PlayerId, Vec<PhaseCommand>>,
60}
61
62impl Phase {
63    pub fn new(phase_type: PhaseType) -> Self {
64        Phase {
65            phase_type: Some(phase_type),
66            ..Default::default()
67        }
68    }
69
70    /// Clear all commands from this phase.
71    /// Mirrors Java's `Phase.clearCommands()`.
72    pub fn clear_commands(&mut self) {
73        self.at.clear();
74        self.until.clear();
75        self.until_map.clear();
76        self.until_end_map.clear();
77        self.register_map.clear();
78    }
79
80    /// Add a command to execute "at" this phase.
81    /// Mirrors Java's `Phase.addAt()`.
82    pub fn add_at(&mut self, cmd: PhaseCommand) {
83        self.at.insert(0, cmd);
84    }
85
86    /// Execute all "at" commands, draining the list.
87    /// Mirrors Java's `Phase.executeAt()`.
88    pub fn execute_at(&mut self) -> Vec<PhaseCommand> {
89        std::mem::take(&mut self.at)
90    }
91
92    /// Add a command to execute "until" this phase (global or per-player).
93    /// When called without a player, adds to the global until list.
94    /// When called with a player, adds to the per-player until map.
95    /// Mirrors Java's `Phase.addUntil()` (both overloads).
96    pub fn add_until(&mut self, player: Option<PlayerId>, cmd: PhaseCommand) {
97        if let Some(p) = player {
98            self.until_map.entry(p).or_default().insert(0, cmd);
99        } else {
100            self.until.insert(0, cmd);
101        }
102    }
103
104    /// Execute "until" commands, draining the list.
105    /// When called without a player, executes global until commands.
106    /// When called with a player, executes per-player until commands.
107    /// Mirrors Java's `Phase.executeUntil()` (both overloads).
108    pub fn execute_until(&mut self, player: Option<PlayerId>) -> Vec<PhaseCommand> {
109        if let Some(p) = player {
110            self.until_map.remove(&p).unwrap_or_default()
111        } else {
112            std::mem::take(&mut self.until)
113        }
114    }
115
116    /// Register a command for end-of-phase execution for a player.
117    /// Mirrors Java's `Phase.registerUntilEnd()`.
118    pub fn register_until_end(&mut self, player: PlayerId, cmd: PhaseCommand) {
119        self.register_map.entry(player).or_default().insert(0, cmd);
120    }
121
122    /// Add a command to the end-of-phase map for a player.
123    /// Mirrors Java's `Phase.addUntilEnd()`.
124    pub fn add_until_end(&mut self, player: PlayerId, cmd: PhaseCommand) {
125        self.until_end_map.entry(player).or_default().insert(0, cmd);
126    }
127
128    /// Move registered commands to the until-end map.
129    /// Mirrors Java's `Phase.registerUntilEndCommand()`.
130    pub fn register_until_end_command(&mut self, player: PlayerId) {
131        if let Some(cmds) = self.register_map.remove(&player) {
132            self.until_end_map.insert(player, cmds);
133        }
134    }
135
136    /// Execute end-of-phase commands for a player.
137    /// Mirrors Java's `Phase.executeUntilEndOfPhase()`.
138    pub fn execute_until_end_of_phase(&mut self, player: PlayerId) -> Vec<PhaseCommand> {
139        self.until_end_map.remove(&player).unwrap_or_default()
140    }
141}
142
143/// Tracks the current turn state: whose turn, which phase, turn number.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct TurnState {
146    pub turn_number: u32,
147    pub active_player: PlayerId,
148    pub phase: PhaseType,
149    pub priority_player: PlayerId,
150    #[serde(default)]
151    pub is_extra_turn: bool,
152    pub num_players: u32,
153
154    // Combat tracking
155    pub combat_attackers_declared: bool,
156    pub combat_blockers_declared: bool,
157    /// Authoritative blocker -> attacker assignments for the current combat.
158    pub combat_block_assignments: Vec<(CardId, CardId)>,
159
160    // Per-turn flags
161    pub drawn_for_turn: bool,
162}
163
164impl TurnState {
165    pub fn new(active_player: PlayerId, num_players: u32) -> Self {
166        TurnState {
167            turn_number: 1,
168            active_player,
169            phase: PhaseType::Untap,
170            priority_player: active_player,
171            num_players,
172            is_extra_turn: false,
173            combat_attackers_declared: false,
174            combat_blockers_declared: false,
175            combat_block_assignments: vec![],
176            drawn_for_turn: false,
177        }
178    }
179
180    /// Advance to the next phase. Returns true if the turn ended (wrapped to Untap).
181    pub fn advance_phase(&mut self) -> bool {
182        let next = self.phase.next();
183        let turn_ended = next == PhaseType::Untap && self.phase == PhaseType::Cleanup;
184        self.phase = next;
185
186        if turn_ended {
187            self.turn_number += 1;
188            self.combat_attackers_declared = false;
189            self.combat_blockers_declared = false;
190            self.combat_block_assignments.clear();
191            self.drawn_for_turn = false;
192        }
193
194        // Reset combat flags when entering combat
195        if self.phase == PhaseType::CombatBegin {
196            self.combat_attackers_declared = false;
197            self.combat_blockers_declared = false;
198            self.combat_block_assignments.clear();
199        }
200
201        turn_ended
202    }
203
204    /// Advance to the next player's turn (for multiplayer).
205    pub fn next_player_turn(&mut self, player_order: &[PlayerId]) {
206        if let Some(pos) = player_order.iter().position(|&p| p == self.active_player) {
207            let next = (pos + 1) % player_order.len();
208            self.active_player = player_order[next];
209            self.priority_player = self.active_player;
210            self.is_extra_turn = false;
211            self.turn_number += 1;
212            self.combat_attackers_declared = false;
213            self.combat_blockers_declared = false;
214            self.combat_block_assignments.clear();
215            self.drawn_for_turn = false;
216        }
217    }
218
219    /// Advance to the next turn, consuming an extra turn if available.
220    /// Returns `Some((player, skip_untap))` if the advancing player needs
221    /// their skip_next_untap flag set on PlayerState; `None` otherwise.
222    /// Mirrors Java's `PhaseHandler.handleNextTurn()`.
223    pub fn advance_turn(
224        &mut self,
225        extra_turns: &mut std::collections::VecDeque<ExtraTurn>,
226        player_order: &[PlayerId],
227    ) -> Option<(PlayerId, bool)> {
228        if let Some(extra_turn) = extra_turns.pop_front() {
229            let player = extra_turn.player;
230            self.active_player = player;
231            self.priority_player = player;
232            self.is_extra_turn = true;
233            self.turn_number += 1;
234            self.combat_attackers_declared = false;
235            self.combat_blockers_declared = false;
236            self.combat_block_assignments.clear();
237            self.drawn_for_turn = false;
238            if extra_turn.skip_untap {
239                Some((player, true))
240            } else {
241                None
242            }
243        } else {
244            self.is_extra_turn = false;
245            self.next_player_turn(player_order);
246            None
247        }
248    }
249
250    pub fn is_main_phase(&self) -> bool {
251        self.phase.is_main()
252    }
253
254    pub fn is_combat(&self) -> bool {
255        self.phase.is_combat()
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn advance_phases() {
265        let mut ts = TurnState::new(PlayerId(0), 2);
266        assert_eq!(ts.phase, PhaseType::Untap);
267
268        ts.advance_phase();
269        assert_eq!(ts.phase, PhaseType::Upkeep);
270
271        ts.advance_phase();
272        assert_eq!(ts.phase, PhaseType::Draw);
273    }
274
275    #[test]
276    fn turn_wraps() {
277        let mut ts = TurnState::new(PlayerId(0), 2);
278        assert_eq!(ts.turn_number, 1);
279
280        // Advance through all phases
281        loop {
282            let ended = ts.advance_phase();
283            if ended {
284                break;
285            }
286        }
287        assert_eq!(ts.turn_number, 2);
288        assert_eq!(ts.phase, PhaseType::Untap);
289    }
290
291    #[test]
292    fn phase_commands() {
293        let mut phase = Phase::new(PhaseType::Upkeep);
294        phase.add_at(PhaseCommand::Cleanup(CardId(1)));
295        phase.add_until(None, PhaseCommand::RemoveEffect(CardId(2)));
296
297        let at_cmds = phase.execute_at();
298        assert_eq!(at_cmds.len(), 1);
299
300        let until_cmds = phase.execute_until(None);
301        assert_eq!(until_cmds.len(), 1);
302
303        // After execution, lists should be empty
304        assert!(phase.execute_at().is_empty());
305        assert!(phase.execute_until(None).is_empty());
306    }
307
308    #[test]
309    fn phase_per_player_commands() {
310        let mut phase = Phase::new(PhaseType::Cleanup);
311        let p0 = PlayerId(0);
312        let p1 = PlayerId(1);
313
314        phase.add_until(Some(p0), PhaseCommand::Cleanup(CardId(1)));
315        phase.add_until(Some(p1), PhaseCommand::Cleanup(CardId(2)));
316
317        let p0_cmds = phase.execute_until(Some(p0));
318        assert_eq!(p0_cmds.len(), 1);
319
320        // p1 commands should still be there
321        let p1_cmds = phase.execute_until(Some(p1));
322        assert_eq!(p1_cmds.len(), 1);
323    }
324}