//! Game document: tags, start position and the move tree. use shakmaty::{ CastlingMode, Chess, Color, EnPassantMode, FromSetup, Move, Position, fen::Fen, san::SanPlus, }; use crate::edit::Command; use crate::nag::Nag; use crate::start::StartPosition; /// Stable node identifier inside one [`Game`]. Never reused: deleting a /// variation detaches nodes but keeps their ids valid (needed for undo/redo). #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct NodeId(u32); impl NodeId { /// The root (start position, no move). pub const ROOT: NodeId = NodeId(0); pub fn index(self) -> usize { self.0 as usize } } /// What was played to reach a node. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum MoveKind { /// A legal move in the parent position. Normal(Move), /// Teaching null move `--` (side to move passes). Not a legal chess move: /// never generated by user move input; histories containing it are not /// ordinary games (see [`Game::engine_history`]). Null, } /// A move with its display SAN (`"Nf3+"`, `"O-O"`, `"--"`). #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct GameMove { pub kind: MoveKind, pub san: String, } impl GameMove { pub fn is_null(&self) -> bool { matches!(self.kind, MoveKind::Null) } /// UCI notation (`e1g1` for castling), `None` for a null move. pub fn uci(&self) -> Option { match self.kind { MoveKind::Normal(m) => Some(m.to_uci(CastlingMode::Standard).to_string()), MoveKind::Null => None, } } } /// Game termination marker. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum GameResult { WhiteWins, BlackWins, Draw, Unknown, } impl GameResult { pub fn as_str(self) -> &'static str { match self { GameResult::WhiteWins => "1-0", GameResult::BlackWins => "0-1", GameResult::Draw => "1/2-1/2", GameResult::Unknown => "*", } } pub fn from_pgn(s: &str) -> Option { Some(match s.trim() { "1-0" => GameResult::WhiteWins, "0-1" => GameResult::BlackWins, "1/2-1/2" | "½-½" => GameResult::Draw, "*" => GameResult::Unknown, _ => return None, }) } } /// A node of the move tree. The root has no move. #[derive(Clone, Debug)] pub struct Node { pub(crate) parent: Option, pub(crate) children: Vec, pub(crate) mv: Option, pub(crate) position: Chess, pub(crate) ply: u32, pub(crate) attached: bool, pub(crate) nags: Vec, pub(crate) comments_before: Vec, pub(crate) comments_after: Vec, pub(crate) unparsed: Vec, } impl Node { pub fn parent(&self) -> Option { self.parent } /// Continuations; the first is the main line, others are variations. pub fn children(&self) -> &[NodeId] { &self.children } /// `None` only for the root. pub fn game_move(&self) -> Option<&GameMove> { self.mv.as_ref() } /// Position after this node's move. pub fn position(&self) -> &Chess { &self.position } /// Half-moves from the start position. pub fn ply(&self) -> u32 { self.ply } pub fn nags(&self) -> &[Nag] { &self.nags } /// Comments printed before the move (e.g. the starting comment of a variation). pub fn comments_before(&self) -> &[String] { &self.comments_before } /// Comments after the move. For the root: the game's starting comment. pub fn comments_after(&self) -> &[String] { &self.comments_after } /// Raw PGN text that could not be interpreted (e.g. the rest of a branch /// after an illegal move). Written back verbatim on export. pub fn unparsed(&self) -> &[String] { &self.unparsed } pub fn is_attached(&self) -> bool { self.attached } } /// Starting point and moves for a UCI `position` command. #[derive(Clone, Debug, PartialEq, Eq)] pub struct EngineHistory { /// `None` = `startpos`; otherwise a normalized FEN (fullmove ≥ 1). pub start_fen: Option, /// UCI moves from `start_fen` to the node. pub moves: Vec, /// Normalized FEN of the node's position (fallback). pub current_fen: String, pub kind: HistoryKind, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum HistoryKind { /// Real move history from the game's start position. Complete, /// The path contains teaching null moves. `start_fen` is the position right /// after the last null move and `moves` follow it; earlier history is not /// sent because it is not an ordinary game. AfterNullMove { null_moves: usize }, } /// Position after a teaching null move: side to move passes, en passant is /// cleared, halfmove clock and (after Black) fullmove number advance. /// Fails if the side to move is in check. pub(crate) fn play_null(pos: &Chess) -> Result { let mut setup = pos.to_setup(EnPassantMode::Legal); let was_black = setup.turn == Color::Black; setup.swap_turn(); setup.halfmoves = setup.halfmoves.saturating_add(1); if was_black { setup.fullmoves = setup.fullmoves.saturating_add(1); } Chess::from_setup(setup, CastlingMode::Standard).map_err(|e| e.to_string()) } /// A chess game document. #[derive(Clone, Debug)] pub struct Game { pub(crate) tags: Vec<(String, String)>, pub(crate) start: StartPosition, pub(crate) nodes: Vec, pub(crate) result: Option, pub(crate) undo_stack: Vec, pub(crate) redo_stack: Vec, pub(crate) revision: u64, /// Undo-stack depth at the last save; `None` once that state is unreachable /// (a new edit was made after undoing past it). pub(crate) saved_depth: Option, /// Changes outside the undo history (tags, result) since the last save. pub(crate) unsaved_meta: bool, /// Commands collected by an open [`Game::edit_group`]. pub(crate) group: Option>, } impl Default for Game { fn default() -> Self { Self::new() } } const SEVEN_TAG_ROSTER: [(&str, &str); 7] = [ ("Event", "?"), ("Site", "?"), ("Date", "????.??.??"), ("Round", "?"), ("White", "?"), ("Black", "?"), ("Result", "*"), ]; impl Game { /// New game from the standard position with the Seven Tag Roster. pub fn new() -> Self { let mut g = Self::with_start(StartPosition::standard(), Vec::new()); g.tags = SEVEN_TAG_ROSTER .iter() .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) .collect(); g } /// New game from an arbitrary position (adds `SetUp`/`FEN` tags if not standard). pub fn from_start(start: StartPosition) -> Self { let mut g = Self::new(); if let Some(fen) = start.original_fen() { g.tags.push(("SetUp".into(), "1".into())); g.tags.push(("FEN".into(), fen.to_owned())); } g.reset_root(start); g } pub(crate) fn with_start(start: StartPosition, tags: Vec<(String, String)>) -> Self { let root = Node { parent: None, children: Vec::new(), mv: None, position: start.position().clone(), ply: 0, attached: true, nags: Vec::new(), comments_before: Vec::new(), comments_after: Vec::new(), unparsed: Vec::new(), }; Game { tags, start, nodes: vec![root], result: None, undo_stack: Vec::new(), redo_stack: Vec::new(), revision: 0, saved_depth: Some(0), unsaved_meta: false, group: None, } } fn reset_root(&mut self, start: StartPosition) { if let Some(root) = self.nodes.first_mut() { root.position = start.position().clone(); } self.start = start; } // ----- tags ------------------------------------------------------------- /// Tags in source order, including non-standard ones. pub fn tags(&self) -> &[(String, String)] { &self.tags } /// First tag with this name (case-sensitive, as in PGN). pub fn tag(&self, name: &str) -> Option<&str> { self.tags .iter() .find(|(k, _)| k == name) .map(|(_, v)| v.as_str()) } /// Drops a tag (not part of undo history); nothing when it is not there. pub fn remove_tag(&mut self, name: &str) { let before = self.tags.len(); self.tags.retain(|(k, _)| k != name); if self.tags.len() != before { self.unsaved_meta = true; self.touch(); } } /// Sets or appends a tag (not part of undo history). pub fn set_tag(&mut self, name: &str, value: &str) { match self.tags.iter_mut().find(|(k, _)| k == name) { Some(slot) => slot.1 = value.to_owned(), None => self.tags.push((name.to_owned(), value.to_owned())), } self.unsaved_meta = true; self.touch(); } pub fn start(&self) -> &StartPosition { &self.start } /// Termination marker from movetext (falls back to the `Result` tag). pub fn result(&self) -> GameResult { self.result .or_else(|| self.tag("Result").and_then(GameResult::from_pgn)) .unwrap_or(GameResult::Unknown) } pub fn set_result(&mut self, result: GameResult) { self.result = Some(result); self.set_tag("Result", result.as_str()); } /// The seven tags of the PGN standard, first and in their order, with "?" for the /// unknown ones (a game written by hand gets a proper tag roster); the other tags /// follow as they were. Not part of undo history. pub fn order_roster(&mut self) { let result = self.result().as_str().to_owned(); let roster = [ ("Event", "?"), ("Site", "?"), ("Date", "????.??.??"), ("Round", "?"), ("White", "?"), ("Black", "?"), ("Result", result.as_str()), ]; let mut tags: Vec<(String, String)> = Vec::with_capacity(self.tags.len() + 7); for (name, unknown) in roster { let value = self .tags .iter() .find(|(k, _)| k == name) .map_or(unknown, |(_, v)| v.as_str()); tags.push((name.to_owned(), value.to_owned())); } tags.extend( self.tags .iter() .filter(|(k, _)| !roster.iter().any(|(name, _)| k == name)) .cloned(), ); if tags != self.tags { self.tags = tags; self.unsaved_meta = true; self.touch(); } } // ----- node access ------------------------------------------------------ pub fn root(&self) -> NodeId { NodeId::ROOT } pub fn node(&self, id: NodeId) -> Option<&Node> { self.nodes.get(id.index()) } pub(crate) fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> { self.nodes.get_mut(id.index()) } /// Number of nodes in the arena (including detached ones). pub fn arena_len(&self) -> usize { self.nodes.len() } /// Every node ever made, by id (detached ones too: an id never changes and is never /// reused, so it can name a move across edits). pub fn all_nodes(&self) -> impl Iterator + '_ { (0..self.nodes.len()).map(|i| NodeId(i as u32)) } /// Ids of all attached nodes in depth-first PGN order (root first). pub fn attached_nodes(&self) -> Vec { let mut out = Vec::new(); let mut stack = vec![NodeId::ROOT]; while let Some(id) = stack.pop() { out.push(id); if let Some(n) = self.node(id) { stack.extend(n.children.iter().rev().copied()); } } out } pub fn is_attached(&self, id: NodeId) -> bool { self.node(id).is_some_and(|n| n.attached) } /// Position after the node's move (root: start position). pub fn position(&self, id: NodeId) -> Option<&Chess> { self.node(id).map(|n| &n.position) } /// Position before the node's move (root: start position). pub fn position_before(&self, id: NodeId) -> Option<&Chess> { let parent = self.node(id)?.parent.unwrap_or(NodeId::ROOT); self.position(parent) } pub fn fen(&self, id: NodeId) -> Option { self.position(id) .map(|p| Fen::from_position(p, EnPassantMode::Legal).to_string()) } pub fn game_move(&self, id: NodeId) -> Option<&GameMove> { self.node(id)?.mv.as_ref() } /// Move number and the side that made the move, for display (`12.` / `12...`). pub fn move_number(&self, id: NodeId) -> Option<(u32, Color)> { self.node(id)?.mv.as_ref()?; let before = self.position_before(id)?; Some((before.fullmoves().get(), before.turn())) } /// `"12. Nf3"` or `"12... Nf6"`. pub fn move_label(&self, id: NodeId) -> Option { let (n, color) = self.move_number(id)?; let san = &self.game_move(id)?.san; Some(match color { Color::White => format!("{n}. {san}"), Color::Black => format!("{n}... {san}"), }) } // ----- navigation ------------------------------------------------------- pub fn parent(&self, id: NodeId) -> Option { self.node(id)?.parent } pub fn children(&self, id: NodeId) -> &[NodeId] { self.node(id).map(|n| n.children.as_slice()).unwrap_or(&[]) } /// Main continuation (next move). pub fn main_child(&self, id: NodeId) -> Option { self.children(id).first().copied() } /// Alternatives to the main continuation of `id`. pub fn variations(&self, id: NodeId) -> &[NodeId] { self.children(id).get(1..).unwrap_or(&[]) } /// Position of `id` among its siblings (0 = main). pub fn child_index(&self, id: NodeId) -> Option { let parent = self.parent(id)?; self.children(parent).iter().position(|c| *c == id) } /// Next sibling (switch to the next variation at the same move). pub fn next_sibling(&self, id: NodeId) -> Option { let parent = self.parent(id)?; let i = self.child_index(id)?; self.children(parent).get(i + 1).copied() } pub fn prev_sibling(&self, id: NodeId) -> Option { let parent = self.parent(id)?; let i = self.child_index(id)?.checked_sub(1)?; self.children(parent).get(i).copied() } /// Follows main continuations to the end of the current line. pub fn line_end(&self, id: NodeId) -> NodeId { let mut cur = id; while let Some(next) = self.main_child(cur) { cur = next; } cur } /// Path from the root to `id`, inclusive (`[ROOT, …, id]`). pub fn path(&self, id: NodeId) -> Vec { let mut path = Vec::new(); let mut cur = Some(id); while let Some(c) = cur { if self.node(c).is_none() { break; } path.push(c); cur = self.parent(c); } path.reverse(); path } /// Main line nodes, excluding the root. pub fn mainline(&self) -> Vec { let mut out = Vec::new(); let mut cur = NodeId::ROOT; while let Some(next) = self.main_child(cur) { out.push(next); cur = next; } out } /// True if every node on the path is a main continuation. pub fn is_mainline(&self, id: NodeId) -> bool { self.is_attached(id) && self .path(id) .iter() .all(|n| self.child_index(*n).unwrap_or(0) == 0) } /// First node of the innermost variation containing `id` (the child that is /// not a main continuation); `None` if `id` is on the main line. pub fn variation_start(&self, id: NodeId) -> Option { let mut cur = id; loop { match self.child_index(cur) { Some(0) => cur = self.parent(cur)?, Some(_) => return Some(cur), None => return None, } } } /// Number of variation branchings on the path (0 = main line); for indentation. pub fn variation_depth(&self, id: NodeId) -> usize { self.path(id) .iter() .filter(|n| self.child_index(**n).unwrap_or(0) > 0) .count() } // ----- engine ----------------------------------------------------------- /// History for UCI `position [startpos|fen F] moves …`. pub fn engine_history(&self, id: NodeId) -> Option { let node = self.node(id)?; let current_fen = Fen::from_position(&node.position, EnPassantMode::Legal).to_string(); let path = self.path(id); let mut start_fen = if self.start.is_standard() { None } else { Some(self.start.fen()) }; let mut moves = Vec::new(); let mut null_moves = 0; for n in path.iter().skip(1) { let Some(mv) = self.game_move(*n) else { continue; }; match mv.uci() { Some(u) => moves.push(u), None => { null_moves += 1; moves.clear(); start_fen = self.fen(*n); } } } let kind = if null_moves == 0 { HistoryKind::Complete } else { HistoryKind::AfterNullMove { null_moves } }; Some(EngineHistory { start_fen, moves, current_fen, kind, }) } /// SAN for a candidate move in the node's position (e.g. to render an engine PV). pub fn san_for(&self, id: NodeId, m: Move) -> Option { let pos = self.position(id)?; pos.is_legal(m) .then(|| SanPlus::from_move(pos.clone(), m).to_string()) } // ----- revision tracking ------------------------------------------------ /// Incremented on each document change; usable as a cache key by the UI. pub fn revision(&self) -> u64 { self.revision } /// True if the document differs from the last saved (or imported) state. /// Undoing back to the saved state clears it. pub fn is_modified(&self) -> bool { self.unsaved_meta || self.saved_depth != Some(self.undo_stack.len()) } /// Forgets the undo and redo history (the moves of a game played against the /// computer are not edits to undo); whether the game is saved stays as it is. pub fn forget_history(&mut self) { let saved = self.saved_depth == Some(self.undo_stack.len()); self.undo_stack.clear(); self.redo_stack.clear(); self.saved_depth = saved.then_some(0); } pub fn mark_saved(&mut self) { self.saved_depth = Some(self.undo_stack.len()); self.unsaved_meta = false; } pub(crate) fn touch(&mut self) { self.revision = self.revision.wrapping_add(1); } // ----- construction helpers (import) ----------------------------------- /// Appends a new child without dedup (import keeps the source tree as is). pub(crate) fn push_child(&mut self, parent: NodeId, mv: GameMove, position: Chess) -> NodeId { let id = NodeId(u32::try_from(self.nodes.len()).unwrap_or(u32::MAX)); let ply = self.node(parent).map(|p| p.ply + 1).unwrap_or(1); self.nodes.push(Node { parent: Some(parent), children: Vec::new(), mv: Some(mv), position, ply, attached: true, nags: Vec::new(), comments_before: Vec::new(), comments_after: Vec::new(), unparsed: Vec::new(), }); if let Some(p) = self.node_mut(parent) { p.children.push(id); } id } /// Canonical textual dump of the attached tree (moves, NAGs, comments with /// collapsed whitespace, variation structure). Two games with equal dumps /// and equal tags/start are semantically equivalent; used by roundtrip tests. pub fn canonical_tree(&self) -> String { fn norm(s: &str) -> String { s.split_whitespace().collect::>().join(" ") } fn walk(g: &Game, id: NodeId, depth: usize, out: &mut String) { let Some(n) = g.node(id) else { return }; out.push_str(&" ".repeat(depth)); match &n.mv { Some(m) => out.push_str(&m.san), None => out.push_str(""), } for nag in &n.nags { out.push_str(&format!(" ${}", nag.0)); } for c in &n.comments_before { out.push_str(&format!(" B{{{}}}", norm(c))); } for c in &n.comments_after { out.push_str(&format!(" A{{{}}}", norm(c))); } for u in &n.unparsed { out.push_str(&format!(" U[{}]", norm(u))); } out.push('\n'); for c in &n.children { walk(g, *c, depth + 1, out); } } let mut out = String::new(); walk(self, NodeId::ROOT, 0, &mut out); out } } #[cfg(test)] mod tests { use super::*; #[test] fn new_game_has_roster() { let g = Game::new(); assert_eq!(g.tags().len(), 7); assert_eq!(g.tag("Result"), Some("*")); assert!(g.start().is_standard()); assert_eq!(g.mainline(), Vec::::new()); let h = g.engine_history(g.root()).expect("root"); assert_eq!(h.start_fen, None); assert!(h.moves.is_empty()); } }