diff --git a/Cargo.lock b/Cargo.lock index 05a4567..e33a577 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -789,6 +789,15 @@ dependencies = [ "zip", ] +[[package]] +name = "chess-openings" +version = "2.0.0" +dependencies = [ + "chess-import", + "serde", + "shakmaty", +] + [[package]] name = "chesspenguin" version = "2.0.0" @@ -1672,6 +1681,7 @@ name = "game-review" version = "2.0.0" dependencies = [ "chess-core", + "chess-openings", "serde", "serde_json", "shakmaty", @@ -3434,6 +3444,7 @@ version = "2.0.0" dependencies = [ "chess-core", "chess-import", + "chess-openings", "game-review", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index ca8aa65..884239a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "crates/chess-core", "crates/chess-import", "crates/uci", + "crates/openings", "crates/game-review", "crates/online-games", "crates/releases", @@ -44,6 +45,7 @@ chess-import = { path = "crates/chess-import" } uci = { path = "crates/uci" } maia = { path = "crates/maia" } game-review = { path = "crates/game-review" } +chess-openings = { path = "crates/openings" } online-games = { path = "crates/online-games" } releases = { path = "crates/releases" } trainer = { path = "crates/trainer" } diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index d6eee6c..231f0d4 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -151,7 +151,7 @@ platform into the user's data directory and checks its SHA-256 (pinned in ## Opening names (preparing against an opponent) -`crates/prep/data/a.tsv` … `e.tsv` are the five files of the Lichess opening table +`crates/openings/data/a.tsv` … `e.tsv` are the five files of the Lichess opening table https://github.com/lichess-org/chess-openings (the lichess.org contributors), downloaded unmodified at revision `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27) on 2026-10-28 and embedded in the program. Its README: "As a collection of facts, this data set is in the public diff --git a/crates/game-review/Cargo.toml b/crates/game-review/Cargo.toml index 44a1452..568aa81 100644 --- a/crates/game-review/Cargo.toml +++ b/crates/game-review/Cargo.toml @@ -12,5 +12,6 @@ publish = false chess-core.workspace = true shakmaty.workspace = true uci.workspace = true +chess-openings.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs index f49f320..a981260 100644 --- a/crates/game-review/src/features.rs +++ b/crates/game-review/src/features.rs @@ -28,6 +28,8 @@ pub struct MoveFeatures { pub sacrifice_any: bool, /// A piece (not the king) under attack moves away without loss. pub escape: bool, + /// The move goes into a position of the opening table (chess.com's «book»). + pub book: bool, } /// Which rules decide !! and !. Both stay, to compare them and to go back. @@ -96,6 +98,7 @@ impl MoveFeatures { winning_capture: m.is_capture() && gain >= 2, sacrifice_any: offered_any >= 3 && taken - threat_any <= -2 && !lost_anyway, escape: lost_anyway && from_threat < 900 && gain >= 0, + book: chess_openings::in_book(chess_openings::key(&after)), } } @@ -105,14 +108,19 @@ impl MoveFeatures { Rules::Strict => self.sacrifice_any, Rules::ChessCom => self.sacrifice, }; - sacrifice && self.legal > 1 && !self.check && !self.promotion + sacrifice + && self.legal > 1 + && !self.check + && !self.promotion + && !(rules == Rules::ChessCom && self.book) } /// Could be great: not a forced, obvious or finishing move. With [`Rules::ChessCom`] /// a piece saving itself on the only good square can be (13.Qa4 of the Evergreen - /// game). + /// game), a book move cannot (6…Bb4+ of Steinitz — von Bardeleben). pub fn great_shape(&self, rules: Rules) -> bool { self.legal > 1 + && !(rules == Rules::ChessCom && self.book) && !self.mates && !self.recapture && !self.winning_capture diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index cae4158..8a9ea15 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -148,6 +148,10 @@ mod good { /// !: the position after the move is not lost, and the best other move did not win. pub const GREAT_AFTER: f64 = 40.0; pub const GREAT_ALT: f64 = 75.0; + /// [`Rules::ChessCom`]: nor keep a clear edge. chess.com's ! in the check set + /// (`chesscom/`, 2026-10-28) all have the best other move at 59 % or less; above it + /// it gives none (18.Nd4, 23.Rf7+, 25.Rxh7+ of Steinitz — von Bardeleben). + pub const GREAT_ALT_CHESSCOM: f64 = 60.0; /// [`Rules::Strict`]: lost below, won above; a great move changes which. pub const LOST: f64 = 33.0; pub const WON: f64 = 67.0; @@ -210,7 +214,11 @@ fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules) -> Option && wb - w2 >= good::GAP && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) && wa >= good::GREAT_AFTER - && w2 < good::GREAT_ALT) + && w2 + < match rules { + Rules::Strict => good::GREAT_ALT, + Rules::ChessCom => good::GREAT_ALT_CHESSCOM, + }) .then_some(Judgement::Great) } diff --git a/crates/openings/Cargo.toml b/crates/openings/Cargo.toml new file mode 100644 index 0000000..d54a971 --- /dev/null +++ b/crates/openings/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "chess-openings" +description = "Opening names of ChessPenguin: the Lichess chess-openings table (CC0), looked up by position; also tells a book move" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +shakmaty.workspace = true +serde.workspace = true + +[dev-dependencies] +chess-import.workspace = true diff --git a/crates/prep/data/a.tsv b/crates/openings/data/a.tsv similarity index 100% rename from crates/prep/data/a.tsv rename to crates/openings/data/a.tsv diff --git a/crates/prep/data/b.tsv b/crates/openings/data/b.tsv similarity index 100% rename from crates/prep/data/b.tsv rename to crates/openings/data/b.tsv diff --git a/crates/prep/data/c.tsv b/crates/openings/data/c.tsv similarity index 100% rename from crates/prep/data/c.tsv rename to crates/openings/data/c.tsv diff --git a/crates/prep/data/d.tsv b/crates/openings/data/d.tsv similarity index 100% rename from crates/prep/data/d.tsv rename to crates/openings/data/d.tsv diff --git a/crates/prep/data/e.tsv b/crates/openings/data/e.tsv similarity index 100% rename from crates/prep/data/e.tsv rename to crates/openings/data/e.tsv diff --git a/crates/openings/src/lib.rs b/crates/openings/src/lib.rs new file mode 100644 index 0000000..14f5d5b --- /dev/null +++ b/crates/openings/src/lib.rs @@ -0,0 +1,248 @@ +//! Opening names from the Lichess `chess-openings` table: a position's ECO code and +//! name, looked up by the position itself, so a line reaching a named position by +//! another move order gets its name too. A line is named by its deepest named +//! position, as the table's README says ("go back through the moves until a named +//! position is found"). +//! +//! The five TSV files in `data/` (`eco`, `name`, `pgn`) were downloaded unmodified from +//! at revision +//! `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27), on 2026-10-28; the data set is +//! in the public domain (CC0 1.0). Their SHA-256 sums are in `THIRD_PARTY_NOTICES.md`. +//! The table is parsed on first use (3 865 lines, a fraction of a second). +//! +//! Every position on the way to a named one is a book position: the game review gives +//! no !! or ! for a move into it (chess.com's «book» moves). + +use std::collections::{HashMap, HashSet}; +use std::sync::OnceLock; + +use serde::{Deserialize, Serialize}; +use shakmaty::san::SanPlus; +use shakmaty::zobrist::Zobrist64; +use shakmaty::{Chess, EnPassantMode, Position}; + +const FILES: [&str; 5] = [ + include_str!("../data/a.tsv"), + include_str!("../data/b.tsv"), + include_str!("../data/c.tsv"), + include_str!("../data/d.tsv"), + include_str!("../data/e.tsv"), +]; + +/// A named opening position of the table. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Opening { + /// "B30". + pub eco: String, + /// "Sicilian Defense: Nyezhmetdinov-Rossolimo Attack". + pub name: String, + /// The table's moves to the position, in SAN ("1. e4 c5 2. Nf3 Nc6 3. Bb5"). + pub line: String, + /// Half-moves of `line`. + pub plies: u8, +} + +impl Opening { + /// The part of the name before the colon ("Sicilian Defense"). + pub fn family(&self) -> &str { + self.name.split(':').next().unwrap_or(&self.name).trim() + } + + /// The part after the colon ("Nyezhmetdinov-Rossolimo Attack"), if any. + pub fn variation(&self) -> Option<&str> { + self.name.split_once(':').map(|(_, v)| v.trim()) + } +} + +/// The key of a position for the table: the same as `chess_import::position::key` +/// (Zobrist, en passant only when legal), so keys from either side match. +pub fn key(pos: &Chess) -> u64 { + pos.zobrist_hash::(EnPassantMode::Legal).0 +} + +struct Table { + entries: Vec, + /// Position key → entry. A position reached by two lines of the table keeps the + /// first (the files are in ECO order). + by_key: HashMap, + /// Every position of every line after its first move, named or not. + book: HashSet, +} + +fn table() -> &'static Table { + static TABLE: OnceLock = OnceLock::new(); + TABLE.get_or_init(|| { + let mut t = Table { + entries: Vec::with_capacity(4000), + by_key: HashMap::with_capacity(4000), + book: HashSet::with_capacity(20000), + }; + for text in FILES { + for line in text.lines().skip(1) { + let mut cols = line.split('\t'); + let (Some(eco), Some(name), Some(pgn)) = (cols.next(), cols.next(), cols.next()) + else { + continue; + }; + let Some((pos, plies)) = play(pgn, &mut t.book) else { + continue; + }; + let k = key(&pos); + if t.by_key.contains_key(&k) { + continue; + } + t.by_key.insert(k, t.entries.len()); + t.entries.push(Opening { + eco: eco.to_owned(), + name: name.to_owned(), + line: pgn.to_owned(), + plies, + }); + } + } + t + }) +} + +/// Plays a table line ("1. e4 c5 2. Nf3"), adding its positions to `book`; `None` if a +/// move is not legal. +fn play(pgn: &str, book: &mut HashSet) -> Option<(Chess, u8)> { + let mut pos = Chess::default(); + let mut plies = 0u8; + for tok in pgn.split_whitespace() { + if tok.ends_with('.') { + continue; + } + let m = tok.parse::().ok()?.san.to_move(&pos).ok()?; + pos.play_unchecked(m); + book.insert(key(&pos)); + plies = plies.checked_add(1)?; + } + Some((pos, plies)) +} + +/// Number of named positions. +pub fn count() -> usize { + table().entries.len() +} + +/// The entry of a named position (by its [`key`]). +pub fn by_position(k: u64) -> Option { + table().by_key.get(&k).copied() +} + +/// The position (by its [`key`]) lies on a line of the table: a move into it is a book +/// move. +pub fn in_book(k: u64) -> bool { + table().book.contains(&k) +} + +/// Entry `id` (from [`by_position`] or [`deepest`]). +pub fn get(id: usize) -> &'static Opening { + &table().entries[id] +} + +/// The name of a line (the positions `keys`, in order): its deepest named position, +/// its index in `keys` and its entry — but a deeper position whose name is only a +/// more general one ("Sicilian Defense" after 3.d4 in the "Modern Variations") does +/// not take the name back: the most precise name met stays. +pub fn deepest(keys: &[u64]) -> Option<(usize, usize)> { + let mut out: Option<(usize, usize)> = None; + for (i, k) in keys.iter().enumerate() { + if let Some(id) = by_position(*k) + && out.is_none_or(|(_, cur)| !more_general(id, cur)) + { + out = Some((i, id)); + } + } + out +} + +/// Entry `a`'s name is a more general form of entry `b`'s ("Sicilian Defense" of +/// "Sicilian Defense: Modern Variations"; "…: Najdorf Variation" of "…: Najdorf +/// Variation, English Attack"). +pub fn more_general(a: usize, b: usize) -> bool { + is_prefix_name(&get(a).name, &get(b).name) +} + +/// `general` names a family or a variation `precise` is part of. +pub fn is_prefix_name(general: &str, precise: &str) -> bool { + precise.len() > general.len() + && precise.starts_with(general) + && matches!(precise[general.len()..].chars().next(), Some(':' | ',')) +} + +#[cfg(test)] +mod tests { + use super::*; + use shakmaty::san::San; + + fn keys(moves: &[&str]) -> Vec { + let mut pos = Chess::default(); + let mut out = vec![key(&pos)]; + for s in moves { + let m = s.parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(m); + out.push(key(&pos)); + } + out + } + + #[test] + fn the_table_loads() { + // 3 865 lines; a few positions are reached by two lines of the table. + assert!(count() > 3800, "{}", count()); + let start = by_position(key(&Chess::default())); + assert!(start.is_none(), "the start position has no name"); + } + + #[test] + fn the_deepest_named_position_names_the_line_whatever_the_move_order() { + // 1.e4 c5 2.Nf3 Nc6 3.Bb5: the Rossolimo; 3...g6 is named too, 4.O-O is not. + let k = keys(&["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O"]); + let (at, id) = deepest(&k).expect("named"); + let o = get(id); + assert_eq!(o.eco, "B31"); + assert!(o.name.starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), "{}", o.name); + assert_eq!(at, 6, "the position after 3...g6"); + assert_eq!(o.family(), "Sicilian Defense"); + assert!(o.variation().is_some_and(|v| v.starts_with("Nyezhmetdinov"))); + assert_eq!(o.plies, 6); + assert_eq!(o.line, "1. e4 c5 2. Nf3 Nc6 3. Bb5 g6"); + // A transposition: 1.Nf3 d5 2.d4 reaches the table's 1.d4 d5 2.Nf3. + let a = deepest(&keys(&["Nf3", "d5", "d4"])).expect("named"); + let b = deepest(&keys(&["d4", "d5", "Nf3"])).expect("named"); + assert_eq!(a.1, b.1); + assert_eq!(get(a.1).line, "1. d4 d5 2. Nf3"); + // A family without a variation. + let o = get(deepest(&keys(&["e4", "c5"])).expect("named").1); + assert_eq!(o.name, "Sicilian Defense"); + assert_eq!(o.variation(), None); + // Nothing before the first move. + assert_eq!(deepest(&keys(&[])), None); + // A deeper position with a more general name keeps the precise one: the + // table names 1.e4 c5 2.Nf3 d6 3.d4 just «Sicilian Defense». + let line = keys(&["e4", "c5", "Nf3", "d6", "d4"]); + let after_d4 = by_position(line[5]).map(|id| get(id).name.clone()); + assert_eq!(after_d4.as_deref(), Some("Sicilian Defense")); + let (at, id) = deepest(&line).expect("named"); + assert_eq!((at, get(id).name.as_str()), (4, "Sicilian Defense: Modern Variations")); + assert!(is_prefix_name("Sicilian Defense", "Sicilian Defense: Modern Variations")); + assert!(is_prefix_name("A: B", "A: B, C")); + assert!(!is_prefix_name("Sicilian Defense", "Sicilian Defense")); + assert!(!is_prefix_name("English", "English Opening")); + } + + #[test] + fn book_positions_and_keys() { + // The Greco Gambit lines pass 6...Bb4+; 7...d5 is on none of them. + let k = keys(&["e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+"]); + assert!(in_book(k[12]) && by_position(k[12]).is_none(), "on the way, not named"); + let more = keys(&["e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+", "Nc3", "d5"]); + assert!(in_book(more[13]) && !in_book(more[14])); + assert!(!in_book(k[0]), "the start position is no move into the book"); + // The key is the one the rest of the program uses. + let pos = Chess::default(); + assert_eq!(key(&pos), chess_import::position::key(&pos)); + } +} diff --git a/crates/prep/Cargo.toml b/crates/prep/Cargo.toml index 3d628c3..fc9e7da 100644 --- a/crates/prep/Cargo.toml +++ b/crates/prep/Cargo.toml @@ -13,5 +13,6 @@ chess-core.workspace = true chess-import.workspace = true game-review.workspace = true uci.workspace = true +chess-openings.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/prep/src/openings.rs b/crates/prep/src/openings.rs index 21a8604..7827354 100644 --- a/crates/prep/src/openings.rs +++ b/crates/prep/src/openings.rs @@ -1,156 +1,9 @@ -//! Opening names from the Lichess `chess-openings` table: a position's ECO code and -//! name, looked up by the position itself, so a line reaching a named position by -//! another move order gets its name too. A line is named by its deepest named -//! position, as the table's README says ("go back through the moves until a named -//! position is found"). -//! -//! The five TSV files in `data/` (`eco`, `name`, `pgn`) were downloaded unmodified from -//! at revision -//! `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27), on 2026-10-28; the data set is -//! in the public domain (CC0 1.0). Their SHA-256 sums are in `THIRD_PARTY_NOTICES.md`. -//! The table is parsed on first use (3 865 lines, a fraction of a second). +//! Opening names: the table lives in the `chess-openings` crate (the game review uses it +//! too); here only what a report keeps of it. use std::collections::HashMap; -use std::sync::OnceLock; -use chess_core::shakmaty::san::SanPlus; -use chess_core::shakmaty::{Chess, Position}; -use chess_import::position::key; -use serde::{Deserialize, Serialize}; - -const FILES: [&str; 5] = [ - include_str!("../data/a.tsv"), - include_str!("../data/b.tsv"), - include_str!("../data/c.tsv"), - include_str!("../data/d.tsv"), - include_str!("../data/e.tsv"), -]; - -/// A named opening position of the table. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Opening { - /// "B30". - pub eco: String, - /// "Sicilian Defense: Nyezhmetdinov-Rossolimo Attack". - pub name: String, - /// The table's moves to the position, in SAN ("1. e4 c5 2. Nf3 Nc6 3. Bb5"). - pub line: String, - /// Half-moves of `line`. - pub plies: u8, -} - -impl Opening { - /// The part of the name before the colon ("Sicilian Defense"). - pub fn family(&self) -> &str { - self.name.split(':').next().unwrap_or(&self.name).trim() - } - - /// The part after the colon ("Nyezhmetdinov-Rossolimo Attack"), if any. - pub fn variation(&self) -> Option<&str> { - self.name.split_once(':').map(|(_, v)| v.trim()) - } -} - -struct Table { - entries: Vec, - /// Position key → entry. A position reached by two lines of the table keeps the - /// first (the files are in ECO order). - by_key: HashMap, -} - -fn table() -> &'static Table { - static TABLE: OnceLock
= OnceLock::new(); - TABLE.get_or_init(|| { - let mut t = Table { - entries: Vec::with_capacity(4000), - by_key: HashMap::with_capacity(4000), - }; - for text in FILES { - for line in text.lines().skip(1) { - let mut cols = line.split('\t'); - let (Some(eco), Some(name), Some(pgn)) = (cols.next(), cols.next(), cols.next()) - else { - continue; - }; - let Some((pos, plies)) = play(pgn) else { - continue; - }; - let k = key(&pos); - if t.by_key.contains_key(&k) { - continue; - } - t.by_key.insert(k, t.entries.len()); - t.entries.push(Opening { - eco: eco.to_owned(), - name: name.to_owned(), - line: pgn.to_owned(), - plies, - }); - } - } - t - }) -} - -/// Plays a table line ("1. e4 c5 2. Nf3"); `None` if a move is not legal. -fn play(pgn: &str) -> Option<(Chess, u8)> { - let mut pos = Chess::default(); - let mut plies = 0u8; - for tok in pgn.split_whitespace() { - if tok.ends_with('.') { - continue; - } - let m = tok.parse::().ok()?.san.to_move(&pos).ok()?; - pos.play_unchecked(m); - plies = plies.checked_add(1)?; - } - Some((pos, plies)) -} - -/// Number of named positions. -pub fn count() -> usize { - table().entries.len() -} - -/// The entry of a named position (by its [`key`]). -pub fn by_position(k: u64) -> Option { - table().by_key.get(&k).copied() -} - -/// Entry `id` (from [`by_position`] or [`deepest`]). -pub fn get(id: usize) -> &'static Opening { - &table().entries[id] -} - -/// The name of a line (the positions `keys`, in order): its deepest named position, -/// its index in `keys` and its entry — but a deeper position whose name is only a -/// more general one ("Sicilian Defense" after 3.d4 in the "Modern Variations") does -/// not take the name back: the most precise name met stays. -pub fn deepest(keys: &[u64]) -> Option<(usize, usize)> { - let mut out: Option<(usize, usize)> = None; - for (i, k) in keys.iter().enumerate() { - if let Some(id) = by_position(*k) - && out.is_none_or(|(_, cur)| !more_general(id, cur)) - { - out = Some((i, id)); - } - } - out -} - -/// Entry `a`'s name is a more general form of entry `b`'s ("Sicilian Defense" of -/// "Sicilian Defense: Modern Variations"; "…: Najdorf Variation" of "…: Najdorf -/// Variation, English Attack"). -pub fn more_general(a: usize, b: usize) -> bool { - is_prefix_name(&get(a).name, &get(b).name) -} - -/// `general` names a family or a variation `precise` is part of. -pub fn is_prefix_name(general: &str, precise: &str) -> bool { - precise.len() > general.len() - && precise.starts_with(general) - && matches!(precise[general.len()..].chars().next(), Some(':' | ',')) -} +pub use chess_openings::*; /// The openings a report refers to, each once, in the order they were first met. #[derive(Default)] @@ -174,6 +27,8 @@ impl OpeningSet { #[cfg(test)] mod tests { use super::*; + use chess_core::shakmaty::Chess; + use chess_core::shakmaty::Position; use chess_core::shakmaty::san::San; fn keys(moves: &[&str]) -> Vec { @@ -187,51 +42,6 @@ mod tests { out } - #[test] - fn the_table_loads() { - // 3 865 lines; a few positions are reached by two lines of the table. - assert!(count() > 3800, "{}", count()); - let start = by_position(key(&Chess::default())); - assert!(start.is_none(), "the start position has no name"); - } - - #[test] - fn the_deepest_named_position_names_the_line_whatever_the_move_order() { - // 1.e4 c5 2.Nf3 Nc6 3.Bb5: the Rossolimo; 3...g6 is named too, 4.O-O is not. - let k = keys(&["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O"]); - let (at, id) = deepest(&k).expect("named"); - let o = get(id); - assert_eq!(o.eco, "B31"); - assert!(o.name.starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), "{}", o.name); - assert_eq!(at, 6, "the position after 3...g6"); - assert_eq!(o.family(), "Sicilian Defense"); - assert!(o.variation().is_some_and(|v| v.starts_with("Nyezhmetdinov"))); - assert_eq!(o.plies, 6); - assert_eq!(o.line, "1. e4 c5 2. Nf3 Nc6 3. Bb5 g6"); - // A transposition: 1.Nf3 d5 2.d4 reaches the table's 1.d4 d5 2.Nf3. - let a = deepest(&keys(&["Nf3", "d5", "d4"])).expect("named"); - let b = deepest(&keys(&["d4", "d5", "Nf3"])).expect("named"); - assert_eq!(a.1, b.1); - assert_eq!(get(a.1).line, "1. d4 d5 2. Nf3"); - // A family without a variation. - let o = get(deepest(&keys(&["e4", "c5"])).expect("named").1); - assert_eq!(o.name, "Sicilian Defense"); - assert_eq!(o.variation(), None); - // Nothing before the first move. - assert_eq!(deepest(&keys(&[])), None); - // A deeper position with a more general name keeps the precise one: the - // table names 1.e4 c5 2.Nf3 d6 3.d4 just «Sicilian Defense». - let line = keys(&["e4", "c5", "Nf3", "d6", "d4"]); - let after_d4 = by_position(line[5]).map(|id| get(id).name.clone()); - assert_eq!(after_d4.as_deref(), Some("Sicilian Defense")); - let (at, id) = deepest(&line).expect("named"); - assert_eq!((at, get(id).name.as_str()), (4, "Sicilian Defense: Modern Variations")); - assert!(is_prefix_name("Sicilian Defense", "Sicilian Defense: Modern Variations")); - assert!(is_prefix_name("A: B", "A: B, C")); - assert!(!is_prefix_name("Sicilian Defense", "Sicilian Defense")); - assert!(!is_prefix_name("English", "English Opening")); - } - #[test] fn a_set_keeps_each_opening_once() { let mut set = OpeningSet::default(); diff --git a/docs/decisions.md b/docs/decisions.md index 5a83c05..b94447b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -176,6 +176,7 @@ - **Калибровка 2 (2026-10-28, партия владельца с Rodent IV):** 18.Bxa7 — не жертва: ход вскрывает линию d на ферзя, и взятие слона сразу проигрывает больше (18…Rxa7 19.Rxd8). Правило ChessCom: фигура не считается отданной, если после её взятия ходящий тут же выигрывает не меньше (`taking_loses` в `features.rs`); правило Strict не менялось. **Набор сверки** — `crates/game-review/chesscom/` (партии с отметками chess.com в NAG, README); после каждой калибровки прогонять все: `cargo run --release -p game-review --example chesscom_check -- `. На 2026-10-28: 10 из 10 совпадений («Вечнозелёная» 8, партия с Rodent 2 !!). - **Калибровка 3 (2026-10-28, «Бессмертная» по chess.com):** (а) жертва, которая матует быстрее любого другого хода, — не «и так выиграно»: 22.Qf6+!! (мат в 2), хотя 22.Qf7 тоже матует (в 4) — win % этого не различает (`mates_sooner` в `report.rs`); (б) для «!» лучшего хода движка падение оценки к следующей позиции не учитывается — это шум двух поисков (9.Nf5! и 12.h4! пропадали на оценках владельца: −0,51 → −0,82). Обе правки — только правило ChessCom. Набор: 17 из 17 на наших оценках; на оценках из кэша владельца 16 из 17 — 10…Nge7 «Вечнозелёной» (разрыв 9 % при пороге 10, пограничный случай с первой калибровки; порог под одну партию не двигаем). - **Калибровка 4 (2026-10-28, Стейниц — фон Барделебен по chess.com):** правило калибровки 2 оказалось слишком широким — оно сняло 22.Rxe7+!! и 24.Rg7+!!: после 22…Qxe7 белые отыгрываются 23.Rxc8+, но эту угрозу открыло само взятие (ферзь ушёл с d7). Уточнено: фигура не отдана, только если угроза, отыгрывающая её, стояла уже сразу после хода (18.Bxa7: ферзь d8 под ладьёй до взятия). Оба !! совпали, 18.Bxa7 по-прежнему без !!. Расхождения по «!» в этой партии (у нас лишние 6…Bb4+, 8.exd5, 13.Bxe7, 17.d5, 18.Nd4, 19.Ne6, 23.Rf7+, 25.Rxh7+; нет 18…Kf7) — открыты, см. разбор владельцу. +- **Калибровка 5 (2026-10-28, по предложению, владелец согласился «посмотрим»):** правило ChessCom — (а) книжный ход (позиция после хода лежит на линии таблицы дебютов `chess-openings`, крейт `crates/openings`) не получает ни !, ни !!; (б) ! нет, если лучший другой ход оставляет ≥ 60 % (было 75; у всех ! chess.com в наборе — не больше 59 %, запас мал). Убрало 6…Bb4+, 18.Nd4, 23.Rf7+, 25.Rxh7+. Набор: 23 совпадения, 5 расхождений (8.exd5, 13.Bxe7, 17.d5, 19.Ne6 у нас лишние; 18…Kf7 нет — у чёрных 17 %, ! там не ставим); на оценках владельца ещё 10…Nge7. - Второй поиск движка (лучший ход, кроме сыгранного) — **всегда**, только для подходящих ходов: разбор примерно на треть дольше. Старые разборы дозаполняются кнопкой «Обновить» без пересчёта оценок. - Для оценок из PGN (`[%eval]`) !! и ! нет: в отчёте прочерк и пояснение. - В PGN — `$3`/`$1` с комментарием, только если у хода нет оценки автора. Русское имя `$3` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» стал !, затем переименован в «Замечательный ход» (владелец, 2026-10-28).