//! The game engine and SGN interpreter, ported from //! `game_engine.dart` + the `star_gambit_notation` codes. //! //! The single public entry point mirroring Dart's `GameEngine.resolve` is //! [`GameEngine::execute`]. use std::collections::HashMap; use std::rc::Rc; use crate::config::StarGambitConfig; use crate::hex::{self, Hex, HexTransform}; use crate::model::Unit; use crate::result::{GameResult, LossReason}; use crate::zobrist; /// An error produced while interpreting SGN. Mirrors the Dart `SGNError` /// hierarchy (`InvalidMoveError` / `SyntaxError`); the precise sub-classes /// of `InvalidMoveError` are collapsed into a single message string. #[derive(Clone, PartialEq, Eq, Debug)] pub enum SgnError { InvalidMove { command: String, message: String }, Syntax(String), } fn invalid(command: &str, message: &str) -> SgnError { SgnError::InvalidMove { command: command.to_string(), message: message.to_string(), } } /// Splits `s` on the first occurrence of `sep`. Mirrors `splitOnFirst`. fn split_on_first(s: &str, sep: char) -> Option<(&str, &str)> { let i = s.find(sep)?; Some((&s[..i], &s[i + sep.len_utf8()..])) } /// The full game state. Field-for-field parallel to the Dart `GameEngine`. #[derive(Clone)] pub struct GameEngine { pub config: Rc, pub whos_turn: i32, pub result: Option, pub units: Vec, pub can_end_turn: bool, pub game_log: Vec, pub time_control: Option, pub player0time: Option, pub player1time: Option, pub timestamp: i32, /// Millisecond clock start. Only set in local games (unused here). pub clock_start: Option, pub local: bool, pub previous_state_hashes: HashMap, pub zobrist_hash: u64, pub previous: Option>, } impl GameEngine { /// Builds the initial state for a config. Mirrors `GameEngine.initial`. pub fn initial(config: StarGambitConfig, time_control: Option, local: bool) -> GameEngine { let mut units = Vec::new(); for (i, p) in config.initial_placements.iter().enumerate() { let kind = &config.unit_kinds[p.kind_index]; units.push(kind.new_unit(p.player_index, i as i32, p.transform, p.initial_damage)); } let player_time = time_control.map(|t| t * 1000); let mut game = GameEngine { config: Rc::new(config), whos_turn: 0, result: None, units, can_end_turn: false, game_log: Vec::new(), time_control, player0time: player_time, player1time: player_time, timestamp: 0, clock_start: None, local, previous_state_hashes: HashMap::new(), zobrist_hash: 0, previous: None, }; game.zobrist_hash = zobrist::compute(&game.units, &game.config, game.whos_turn, game.can_end_turn); game } /// Convenience: a fresh, non-local, untimed game. pub fn new_game(config: StarGambitConfig) -> GameEngine { GameEngine::initial(config, None, false) } pub fn action_count(&self) -> usize { self.game_log.len() } // ---- queries ------------------------------------------------------- fn active_units(&self) -> impl Iterator { self.units.iter().filter(|u| u.damage < u.kind.health) } fn unit_at(&self, hex: Hex) -> Option<&Unit> { self.active_units().find(|u| u.body().contains(&hex)) } fn is_out_of_bounds(&self, hex: Hex) -> bool { hex.ring() > self.config.board_size } fn current_players_placement_hex(&self) -> Hex { let n = self.config.board_size - 1; let v = if self.whos_turn == 0 { hex::D } else { hex::A }; Hex::new(v.x * n, v.y * n, v.z * n) } /// Players who started with at least one portal. Mirrors /// `playersWithPortal`. fn player_had_portal(&self, player: i32) -> bool { self.config.initial_placements.iter().any(|p| { p.player_index == player && self.config.unit_kinds[p.kind_index].name == "Portal" }) } fn placement_transform(&self, kind_id: usize, placement_id: usize) -> Option { let placements = self.config.placements.get(kind_id)?; let placement = *placements.get(placement_id)?; let placement = if self.whos_turn == 1 { HexTransform::new(Hex::ORIGIN, 3).combine(placement) } else { placement }; let base = HexTransform::from_translate(self.current_players_placement_hex()); Some(base.combine(placement)) } fn is_placement_legal(&self, kind_id: usize, placement_id: usize) -> bool { let transform = match self.placement_transform(kind_id, placement_id) { Some(t) => t, None => return false, }; let kind = &self.config.unit_kinds[kind_id]; let placed_body: Vec = kind.body.iter().map(|&m| transform.from_local(m)).collect(); !self .active_units() .any(|u| u.body().iter().any(|h| placed_body.contains(h))) } /// Undeployed unit counts per kind index for `player` (only kinds with a /// positive remaining count). Mirrors `undeployedUnits`. fn undeployed_units(&self, player: i32) -> Vec<(usize, i32)> { let mut out = Vec::new(); for (i, kind) in self.config.unit_kinds.iter().enumerate() { let on_board = self .units .iter() .filter(|u| u.kind.name == kind.name && u.owner == player) .count() as i32; let left = self.config.counts[i] - on_board; if left > 0 { out.push((i, left)); } } out } fn can_place(&self) -> bool { self.undeployed_units(self.whos_turn) .iter() .any(|&(kind_id, _)| self.has_legal_placement(kind_id)) } fn has_legal_placement(&self, kind_id: usize) -> bool { let n = self .config .placements .get(kind_id) .map(|p| p.len()) .unwrap_or(0); (0..n).any(|pid| self.is_placement_legal(kind_id, pid)) } fn would_collide(&self, unit_id: usize, move_id: usize) -> bool { let unit = &self.units[unit_id]; let m = &unit.kind.moves[move_id]; let new_position = unit.position.combine(m.to_transform()); let hexes = unit.kind.body_transformed(new_position); hexes.iter().any(|&h| match self.unit_at(h) { Some(u) => u.id != unit_id as i32, None => false, }) } /// Whether the unit has at least one legal move. Equivalent to /// `validMoves(unitId).isNotEmpty`. fn has_valid_move(&self, unit_id: usize) -> bool { let unit = &self.units[unit_id]; if unit.kind.move_ <= unit.moves_this_turn { return false; } let board_size = self.config.board_size; unit.kind.moves.iter().enumerate().any(|(id, m)| { !self.would_collide(unit_id, id) && unit .kind .body_transformed(unit.position.combine(m.to_transform())) .iter() .all(|h| h.ring() <= board_size) }) } /// The attack ids that can hit an enemy this turn (first target per /// attack). Mirrors `targets`; we only need its (non-)emptiness, but the /// blocking/ordering logic is reproduced faithfully. fn targets(&self, unit_id: usize) -> Vec<(usize, Hex, i32)> { let unit = &self.units[unit_id]; let mut ret: Vec<(usize, Hex, i32)> = Vec::new(); let mut blocked: Vec = Vec::new(); let mut have: Vec = Vec::new(); for (i, threat_local) in unit.kind.threats() { let global = unit.position.from_local(threat_local); let hits_friendly = self .active_units() .filter(|u| u.owner == unit.owner) .any(|u| u.body().contains(&global)); if hits_friendly { blocked.push(i); } if !blocked.contains(&i) && !have.contains(&i) && !unit.fired_this_turn.contains(&(i as i32)) && self .active_units() .filter(|u| u.owner != unit.owner) .any(|u| u.body().contains(&global)) { let damage = unit.kind.ray_attacks[i].damage_at(threat_local); ret.push((i, threat_local, damage)); have.push(i); } } ret } fn active_player_has_no_options(&self) -> bool { if self.can_end_turn { return false; } for (id, unit) in self.units.iter().enumerate() { if unit.damage >= unit.kind.health || unit.owner != self.whos_turn { continue; } if self.has_valid_move(id) || !self.targets(id).is_empty() { return false; } } if self.can_place() { return false; } true } pub fn is_draw(&self) -> bool { self.previous_state_hashes.values().any(|&v| v > 2) } pub fn compute_result(&self) -> Option { if self.active_player_has_no_options() { return Some(GameResult::Win { winner: if self.whos_turn == 1 { 0 } else { 1 }, reason: LossReason::NoOptions, }); } let portal0 = self .active_units() .any(|u| u.kind.name == "Portal" && u.owner == 0); let portal1 = self .active_units() .any(|u| u.kind.name == "Portal" && u.owner == 1); if self.player_had_portal(0) && !portal0 { return Some(GameResult::Win { winner: 1, reason: LossReason::NoPortal, }); } if self.player_had_portal(1) && !portal1 { return Some(GameResult::Win { winner: 0, reason: LossReason::NoPortal, }); } let p0_has_ships = self .active_units() .any(|u| u.kind.name != "Portal" && u.owner == 0); let p1_has_ships = self .active_units() .any(|u| u.kind.name != "Portal" && u.owner == 1); if !p0_has_ships && self.undeployed_units(0).is_empty() { return Some(GameResult::Win { winner: 1, reason: LossReason::NoShips, }); } else if !p1_has_ships && self.undeployed_units(1).is_empty() { return Some(GameResult::Win { winner: 0, reason: LossReason::NoShips, }); } if self.is_draw() { return Some(GameResult::Draw); } None } // ---- mutators (return new states) ---------------------------------- fn add_unit(&self, kind_id: usize, owner: i32, position: HexTransform) -> GameEngine { let mut g = self.clone(); let id = g.units.len() as i32; let kind = &self.config.unit_kinds[kind_id]; g.units.push(kind.new_unit(owner, id, position, 0)); g } fn damage_unit_at(&self, hex: Hex, damage: i32) -> GameEngine { match self.unit_at(hex) { None => self.clone(), Some(u) => { let id = u.id as usize; let mut g = self.clone(); g.units[id] = self.units[id].deal_damage(damage); g } } } // ---- SGN codes ----------------------------------------------------- /// Mirrors `mustEndTurnAfterPlacement`: only END may follow a placement. fn must_end_turn_after_placement(&self, command: &str) -> Result<(), SgnError> { if let Some(last) = self.game_log.last() { if last.contains('@') && !command.contains("END") { return Err(invalid( command, "Only step allowed after placement is end.", )); } } Ok(()) } fn apply_place(&self, command: &str) -> Result { self.must_end_turn_after_placement(command)?; let (left, right) = split_on_first(command, '@').ok_or_else(|| invalid(command, "Invalid Kind Id"))?; let kind_id: usize = left .parse() .map_err(|_| invalid(command, "Invalid Kind Id"))?; if kind_id >= self.config.unit_kinds.len() { return Err(invalid(command, "Invalid Kind Id")); } let placements_len = self .config .placements .get(kind_id) .map(|p| p.len()) .unwrap_or(0); let placement_id: usize = right .parse() .map_err(|_| invalid(command, "Invalid Placement Id"))?; if placement_id > placements_len { return Err(invalid(command, "Invalid Placement Id")); } if !self.is_placement_legal(kind_id, placement_id) { return Err(invalid(command, "Illegal placement")); } // Enforce reserves: refuse to deploy a kind the active player has // exhausted. (Mirrors the new `C_Place` check in star_engine.) if !self .undeployed_units(self.whos_turn) .iter() .any(|&(k, _)| k == kind_id) { return Err(invalid(command, "No units of that kind in reserve")); } let transform = self .placement_transform(kind_id, placement_id) .ok_or_else(|| invalid(command, "Illegal placement"))?; let mut g = self.add_unit(kind_id, self.whos_turn, transform); g.can_end_turn = true; Ok(g) } fn apply_move(&self, command: &str) -> Result { self.must_end_turn_after_placement(command)?; let (left, right) = split_on_first(command, '+').ok_or_else(|| invalid(command, "Invalid Unit Id"))?; let unit_id: usize = left .parse() .map_err(|_| invalid(command, "Invalid Unit Id"))?; if unit_id >= self.units.len() { return Err(invalid(command, "Invalid Unit Id")); } if self.units[unit_id].owner != self.whos_turn { return Err(invalid(command, "Cannot move opponent's units")); } if self.units[unit_id].remaining_health() <= 0 { return Err(invalid(command, "A destroyed unit cannot move")); } let move_id: usize = right .parse() .map_err(|_| invalid(command, "Invalid Move Id"))?; let unit = &self.units[unit_id]; if unit.kind.move_ <= unit.moves_this_turn { return Err(invalid(command, "Unit has no moves left")); } if move_id >= unit.kind.moves.len() { return Err(invalid(command, "Invalid Move Id")); } let new_unit = unit.moved(move_id); if new_unit.body().iter().any(|&h| self.is_out_of_bounds(h)) { return Err(invalid(command, "Invalid Move Id")); } if self.would_collide(unit_id, move_id) { return Err(invalid(command, "Invalid Move Id")); } let mut g = self.clone(); g.units[unit_id] = new_unit; g.can_end_turn = true; Ok(g) } fn apply_attack(&self, command: &str) -> Result { self.must_end_turn_after_placement(command)?; let (left, right) = split_on_first(command, '*').ok_or_else(|| invalid(command, "Invalid Unit Id"))?; let unit_id: usize = left .parse() .map_err(|_| invalid(command, "Invalid Unit Id"))?; if unit_id >= self.units.len() { return Err(invalid(command, "Invalid Unit Id")); } if self.units[unit_id].owner != self.whos_turn { return Err(invalid(command, "Cannot fire opponent's guns")); } let attack_id: usize = right .parse() .map_err(|_| invalid(command, "Invalid Attack Id"))?; let unit = &self.units[unit_id]; if attack_id >= unit.kind.ray_attacks.len() { return Err(invalid(command, "Invalid Unit Id")); } if unit.fired_this_turn.contains(&(attack_id as i32)) { return Err(invalid( command, "This gun has already been fired this turn", )); } if unit.remaining_health() <= 0 { return Err(invalid(command, "A destroyed unit cannot fire")); } let attack = &unit.kind.ray_attacks[attack_id]; let threats: Vec = attack .targets() .into_iter() .map(|t| unit.position.from_local(t)) .collect(); for (i, threat) in threats.into_iter().enumerate() { if let Some(target) = self.unit_at(threat) { if target.owner != unit.owner { let mut fired = self.clone(); fired.units[unit_id] = self.units[unit_id].with_fired(attack_id as i32); let mut g = fired.damage_unit_at(threat, 2 - i as i32); g.can_end_turn = true; return Ok(g); } else { return Err(invalid(command, "Cannot fire on your own pieces")); } } } Err(invalid(command, "Attack must hit a target")) } fn apply_end_turn(&self, command: &str) -> Result { let (_, time_string) = split_on_first(command, ':').ok_or_else(|| invalid(command, "Invalid end turn"))?; if !self.can_end_turn { return Err(invalid(command, "Cannot end turn yet")); } let time: i32 = time_string .parse() .map_err(|_| invalid(command, &format!("'{time_string}' is not a valid time")))?; let time_taken = time - self.timestamp; let mut g = self.clone(); g.can_end_turn = false; g.timestamp = time; g.whos_turn = if self.whos_turn == 1 { 0 } else { 1 }; for u in g.units.iter_mut() { u.fired_this_turn.clear(); u.moves_this_turn = 0; } // Local games stamp clock_start here; non-local games (all the proof // corpus) never take this branch. if self.local && self.action_count() == 3 && self.clock_start.is_none() { g.clock_start = Some(self.timestamp as i64); } if self.time_control.is_some() { g.player0time = if self.whos_turn == 0 { Some(self.player0time.unwrap() - time_taken) } else { self.player0time }; g.player1time = if self.whos_turn == 1 { Some(self.player1time.unwrap() - time_taken) } else { self.player1time }; } if let Some(r) = g.compute_result() { g.result = Some(r); } Ok(g) } fn apply_game_end(&self, command: &str) -> Result { if command.contains("==") { if self.is_draw() { let mut g = self.clone(); g.result = Some(GameResult::Draw); return Ok(g); } else { return Err(invalid(command, "Threefold repetition not met")); } } let (loser, reason) = split_on_first(command, '=').ok_or_else(|| invalid(command, "Invalid game end"))?; let player_id: i32 = loser .parse() .map_err(|_| invalid(command, &format!("\"{loser}\" is not a valid player ID")))?; if player_id != 0 && player_id != 1 { return Err(invalid( command, &format!("\"{loser}\" is not a valid player ID"), )); } let mut current = self.clone(); match reason { "FF" => {} "T" => { if self.time_control.is_none() || self.time_control == Some(0) { return Err(invalid(command, "No time control set")); } if self.clock_start.is_none() { return Err(invalid(command, "Clock not started")); } if player_id == 0 { current.player0time = Some(0); } else { current.player1time = Some(0); } } "P" => { if !self.player_had_portal(player_id) { return Err(invalid( command, &format!("Player {player_id} never had a portal"), )); } if self .active_units() .any(|u| u.owner == player_id && u.kind.name == "Portal") { return Err(invalid( command, &format!("Player {player_id} still has portal"), )); } } "W" => { let has_active = self .active_units() .any(|u| u.owner == player_id && u.kind.name != "Portal"); let has_undeployed = !self.undeployed_units(player_id).is_empty(); if has_active || has_undeployed { return Err(invalid( command, &format!("Player {player_id} still has ships"), )); } } "N" => { if !self.active_player_has_no_options() { return Err(invalid( command, &format!("Player {player_id} still has options"), )); } } _ => { return Err(invalid( command, &format!("\"{reason}\" is not a valid loss reason"), )); } } let reason_enum = match reason { "FF" => LossReason::Forfeit, "T" => LossReason::NoTime, "P" => LossReason::NoPortal, "W" => LossReason::NoShips, "N" => LossReason::NoOptions, _ => unreachable!(), }; current.result = Some(GameResult::Win { winner: if player_id == 0 { 1 } else { 0 }, reason: reason_enum, }); Ok(current) } /// Interprets a whitespace-separated SGN string against this state, /// returning the resulting state. pub fn execute(&self, sgn: &str) -> Result { let mut game = self.clone(); for command in sgn.split_whitespace() { let applied = if command.starts_with("END") { game.apply_end_turn(command) } else if command.contains('=') { game.apply_game_end(command) } else if command.contains('*') { game.apply_attack(command) } else if command.contains('+') { game.apply_move(command) } else if command.contains('@') { game.apply_place(command) } else { Err(SgnError::Syntax(command.to_string())) }; let mut next = applied?; next.game_log = game.game_log.clone(); next.game_log.push(command.to_string()); next.zobrist_hash = zobrist::compute(&next.units, &next.config, next.whos_turn, next.can_end_turn); // No `previous` back-link is kept. It is never read, and chaining it // makes `clone()` walk the entire game history — so a caller that // probes many candidate actions per turn (a bot, move generation) // goes quadratic. Keeping state a flat, O(1)-to-clone value avoids // that trap by default, which is why every caller used to null this // field by hand. next.previous = None; // Threefold-repetition bookkeeping happens only at turn boundaries. if command.starts_with("END:") { let h = next.zobrist_hash; *next.previous_state_hashes.entry(h).or_insert(0) += 1; } game = next; } Ok(game) } }