diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b0792e..bcc129a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https Calibrated on chess.com's marks of the Evergreen game: a sacrifice is a piece the move itself gives up, every move of a combination is marked, and a piece saving itself on the only good square or the only good move in an equal position is great too. + The first rules stay in the code beside these (to compare them and go back). In + Russian ! is now «Замечательный ход». - The review's mark in the notation stands right after the move, the move in its color (Qg7?? in red), as on Lichess, instead of a colored pill at the edge of the cell; the author's own sign, when there is one, stands instead. diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index c663ce9..ea49bdc 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -255,9 +255,9 @@ Неточности Ошибки Зевки - Отличный ход + Замечательный ход Блестящий ход - Отличные ходы + Замечательные ходы Блестящие ходы Без оценки: %d Анализ прервался diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 7fb9a86..c020f7a 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -10025,7 +10025,7 @@ const ROWS: &[[&str; 9]] = &[ ], [ "Great move", - "Отличный ход", + "Замечательный ход", "Excellent coup", "Starker Zug", "Gran jugada", @@ -10047,7 +10047,7 @@ const ROWS: &[[&str; 9]] = &[ ], [ "Great moves", - "Отличные ходы", + "Замечательные ходы", "Excellents coups", "Starke Züge", "Grandes jugadas", diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs index b6e5196..08773aa 100644 --- a/crates/game-review/src/features.rs +++ b/crates/game-review/src/features.rs @@ -21,6 +21,24 @@ pub struct MoveFeatures { pub sacrifice: bool, /// A capture that wins two points or more. pub winning_capture: bool, + /// The first rules' sacrifice ([`Rules::Strict`]): any piece the opponent can win + /// after the move, also one that hung before it. + pub sacrifice_any: bool, + /// A piece (not the king) under attack moves away without loss. + pub escape: bool, +} + +/// Which rules decide !! and !. Both stay, to compare them and to go back. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Rules { + /// The first rules (docs/research/brilliant-moves.md §3–4): any piece left to be won + /// is a sacrifice; the move must change the outcome to be great; a piece saving + /// itself is never great; one mark a combination. + Strict, + /// Calibrated on chess.com's marks (2026-10-28): only what the move gives up is a + /// sacrifice; the only good move is great; every move of a combination counts. + #[default] + ChessCom, } impl MoveFeatures { @@ -40,13 +58,19 @@ impl MoveFeatures { .iter() .filter(|t| t.2 == m.to() || pseudo_threat(before.board(), t.2, mover.other()) < t.0) .collect(); - let threat = given.iter().map(|t| t.0).max().unwrap_or(0); - let offered = given - .iter() - .filter(|t| t.0 == threat) - .map(|t| t.1) - .max() - .unwrap_or(0); + // The heaviest loss among `pieces` and the value of the piece lost there. + let worst = |pieces: &[&(i32, i32, Square)]| { + let threat = pieces.iter().map(|t| t.0).max().unwrap_or(0); + let offered = pieces + .iter() + .filter(|t| t.0 == threat) + .map(|t| t.1) + .max() + .unwrap_or(0); + (threat, offered) + }; + let (threat, offered) = worst(&given); + let (threat_any, offered_any) = worst(&threats.iter().collect::>()); // The moved piece was hanging where it stood: losing it is no sacrifice. let from_threat = m .from() @@ -62,23 +86,37 @@ impl MoveFeatures { recapture: m.is_capture() && prev.is_some_and(|p| p.is_capture() && p.to() == m.to()), sacrifice: offered >= 3 && taken - threat <= -2 && !lost_anyway, 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, } } /// Could be brilliant: a sacrifice by choice. - pub fn brilliant_shape(&self) -> bool { - self.sacrifice && self.legal > 1 && !self.check && !self.promotion + pub fn brilliant_shape(&self, rules: Rules) -> bool { + let sacrifice = match rules { + Rules::Strict => self.sacrifice_any, + Rules::ChessCom => self.sacrifice, + }; + sacrifice && self.legal > 1 && !self.check && !self.promotion } - /// Could be great: not a forced, obvious or finishing move. A piece saving itself on - /// the only good square can be (chess.com: 13.Qa4 of the Evergreen game). - pub fn great_shape(&self) -> bool { - self.legal > 1 && !self.mates && !self.recapture && !self.winning_capture + /// 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). + pub fn great_shape(&self, rules: Rules) -> bool { + self.legal > 1 + && !self.mates + && !self.recapture + && !self.winning_capture + && !(rules == Rules::Strict && self.escape) } /// Worth asking the engine for the best other move. + /// (Under either rules: one analysis serves both.) pub fn candidate(&self) -> bool { - self.brilliant_shape() || self.great_shape() + [Rules::Strict, Rules::ChessCom] + .into_iter() + .any(|r| self.brilliant_shape(r) || self.great_shape(r)) } } @@ -202,11 +240,11 @@ mod tests { #[test] fn a_queen_offered_for_mate_is_a_sacrifice() { let f = last(Chess::default(), OPERA); - assert!(f.sacrifice && f.brilliant_shape(), "{f:?}"); + assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); assert!(!f.mates && f.candidate()); // 15.Bxd7+ Nxd7: taken back, not a move of note. let f = last(Chess::default(), &OPERA[..OPERA.find(" 16.").unwrap()]); - assert!(f.recapture && !f.great_shape(), "{f:?}"); + assert!(f.recapture && !f.great_shape(Rules::ChessCom), "{f:?}"); } #[test] @@ -219,7 +257,7 @@ mod tests { // A free knight taken: a winning capture, never !. let f = features("4k3/8/8/3n4/8/8/8/3QK3 w - - 0 1", "Qxd5"); assert!( - f.winning_capture && !f.great_shape() && !f.sacrifice, + f.winning_capture && !f.great_shape(Rules::ChessCom) && !f.sacrifice, "{f:?}" ); } @@ -229,7 +267,7 @@ mod tests { // The bishop on c4 attacked by the pawn on d5: Bb3 saves it, which can be the only // good move (great), never a sacrifice. let f = features("4k3/8/8/3p4/2B5/8/8/4K3 w - - 0 1", "Bb3"); - assert!(f.great_shape() && !f.sacrifice, "{f:?}"); + assert!(f.great_shape(Rules::ChessCom) && !f.sacrifice, "{f:?}"); // Taking the pawn instead, into the knight: it was lost anyway (desperado). let f = features("4k3/8/5n2/3p4/2B5/8/8/4K3 w - - 0 1", "Bxd5"); assert!(!f.sacrifice, "{f:?}"); @@ -251,7 +289,7 @@ mod tests { let f = features("4k3/3r4/8/8/B7/2N5/8/4K3 w - - 0 1", "Nd5"); assert!(!f.sacrifice, "{f:?}"); let f = features("4k3/3r4/8/8/8/2N5/8/4K3 w - - 0 1", "Nd5"); - assert!(f.sacrifice && f.brilliant_shape(), "{f:?}"); + assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); } #[test] diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index 43d087a..9af96f9 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -21,7 +21,7 @@ mod features; mod job; pub mod report; -pub use features::MoveFeatures; +pub use features::{MoveFeatures, Rules}; pub use job::{JobEvent, JobFailure, JobSettings, Target, run}; pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats}; @@ -100,6 +100,8 @@ pub struct GameAnalysis { played: Vec>, pub report: Report, pub marks: HashMap, + /// The rules of !! and ! the report follows. + rules: Rules, } impl GameAnalysis { @@ -121,6 +123,7 @@ impl GameAnalysis { played: Vec::new(), report: Report::default(), marks: HashMap::new(), + rules: Rules::default(), }; a.rebuild(game); if cache_dir.is_some_and(|d| a.load_cache(d)) || a.load_pgn_evals(game) { @@ -177,6 +180,15 @@ impl GameAnalysis { self.positions() + candidates / 2 } + /// Follows `rules` for !! and ! from the next [`Self::refresh`] on (the evaluations + /// serve both). + pub fn set_rules(&mut self, rules: Rules) { + if self.rules != rules { + self.rules = rules; + self.dirty = true; + } + } + /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. pub fn refresh(&mut self, game: &Game) { if self.dirty || self.built_rev != Some(game.revision()) { @@ -346,7 +358,8 @@ impl GameAnalysis { }); } self.movers = plies.iter().map(|p| p.mover).collect(); - self.report = Report::build(&self.values, &plies, Phases::divide(&positions)); + self.report = + Report::build_with(&self.values, &plies, Phases::divide(&positions), self.rules); self.marks.clear(); for (i, j) in self.report.judgements.iter().enumerate() { let Some(judgement) = *j else { continue }; diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index d3b3ae3..e797627 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -8,6 +8,8 @@ use chess_core::shakmaty::{Bitboard, Chess, Color, Position, Rank}; use serde::{Deserialize, Serialize}; +use crate::Rules; + /// Engine evaluation from White's point of view. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Eval { @@ -146,6 +148,12 @@ 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::Strict`]: lost below, won above; a great move changes which. + pub const LOST: f64 = 33.0; + pub const WON: f64 = 67.0; + /// [`Rules::Strict`]: an opponent's move losing this much (or judged a mistake or a + /// blunder) starts a new combination. + pub const OPPONENT_ERROR: f64 = 10.0; /// Below this the mover's position is too bad for either mark: no second search. /// (The lower of the two floors after the move, !'s, less the step from the best.) pub const SECOND_FROM: f64 = GREAT_AFTER - NEAR_BEST; @@ -157,15 +165,27 @@ pub fn worth_second(eval: Eval, mover: Color) -> bool { eval.win_percent(mover) >= good::SECOND_FROM } -/// Brilliant or great, from the evaluations around the move. -fn note(before: Eval, after: Eval, ply: &Ply) -> Option { +/// Lost, equal, won (0, 1, 2), for [`Rules::Strict`]. +fn outcome(win: f64) -> u8 { + if win < good::LOST { + 0 + } else if win > good::WON { + 2 + } else { + 1 + } +} + +/// Brilliant or great, from the evaluations around the move (before the combination rule +/// of [`Rules::Strict`]). +fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules) -> Option { let f = ply.features?; let (wb, wa) = (before.win_percent(ply.mover), after.win_percent(ply.mover)); let loss = wb - wa; let second = ply.second.map(|e| e.win_percent(ply.mover)); // Without the move: the best other move, or the best move when another was played. let without = if ply.best { second } else { Some(wb) }; - if f.brilliant_shape() + if f.brilliant_shape(rules) && (ply.best || loss <= good::NEAR_BEST) && wa >= good::SOUND_AFTER && without.is_some_and(|w| w < good::WON_ANYWAY) @@ -173,10 +193,11 @@ fn note(before: Eval, after: Eval, ply: &Ply) -> Option { return Some(Judgement::Brilliant); } let w2 = second?; - (f.great_shape() + (f.great_shape(rules) && ply.best && loss <= good::NEAR_BEST && wb - w2 >= good::GAP + && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) && wa >= good::GREAT_AFTER && w2 < good::GREAT_ALT) .then_some(Judgement::Great) @@ -325,6 +346,16 @@ impl Report { /// `evals[i]` belongs to the position before ply `i`; `evals.len() == plies.len() + 1`. pub fn build(evals: &[Option], plies: &[Ply], phases: Phases) -> Report { + Self::build_with(evals, plies, phases, Rules::default()) + } + + /// [`Report::build`] with these rules for !! and !. + pub fn build_with( + evals: &[Option], + plies: &[Ply], + phases: Phases, + rules: Rules, + ) -> Report { let n = plies.len().min(evals.len().saturating_sub(1)); let mut report = Report { judgements: vec![None; plies.len()], @@ -333,6 +364,10 @@ impl Report { ..Report::default() }; let mut losses: [Vec; 2] = [Vec::new(), Vec::new()]; + // For the combination rule of [`Rules::Strict`]: the moves that passed !! or !, + // and each move's loss. + let mut noted = vec![false; n]; + let mut lost = vec![0.0; n]; for i in 0..n { let ply = plies[i]; let (Some(before), Some(after)) = (evals[i], evals[i + 1]) else { @@ -341,19 +376,30 @@ impl Report { if ply.null { continue; } + lost[i] = before.win_percent(ply.mover) - after.win_percent(ply.mover); let error = if ply.best { None } else { judge(before, after, ply.mover) }; let good = if error.is_none() { - note(before, after, &ply) + note(before, after, &ply, rules) } else { None }; - // Every move of a combination is marked on its own, as on chess.com - // (21.Qxd7+!! 22.Bf5+! 23.Bd7+! in the Evergreen game). - let j = error.or(good); + noted[i] = good.is_some(); + // [`Rules::ChessCom`] marks every move of a combination on its own (21.Qxd7+!! + // 22.Bf5+! 23.Bd7+! in the Evergreen game); [`Rules::Strict`] the first one, + // unless the opponent erred in between. + let erred = |k: usize| { + lost[k] >= good::OPPONENT_ERROR + || matches!( + report.judgements[k], + Some(Judgement::Mistake | Judgement::Blunder) + ) + }; + let goes_on = rules == Rules::Strict && i >= 2 && noted[i - 2] && !erred(i - 1); + let j = error.or(good.filter(|_| !goes_on)); report.judgements[i] = j; let stats = match ply.mover { Color::White => &mut report.white, @@ -737,4 +783,26 @@ mod tests { let r = Report::build(&evals, &[close], Phases::default()); assert_eq!(r.judgements[0], None); } + + #[test] + fn the_strict_rules_want_a_turn_of_the_game_and_one_mark_a_combination() { + let (w, b) = (Color::White, Color::Black); + // The only good move of an equal position: great by chess.com, not by the first rules. + let equal = [Some(Eval::Cp(0)), Some(Eval::Cp(0))]; + let only = || noted(w, false, Some(Eval::Cp(-150))); + let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::ChessCom); + assert_eq!(r.judgements[0], Some(Judgement::Great)); + let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::Strict); + assert_eq!(r.judgements[0], None); + // A combination: marked once by the first rules. + let great = || noted(w, false, Some(Eval::Cp(-300))); + let evals = [Some(Eval::Cp(300)); 4]; + let r = Report::build_with( + &evals, + &[great(), ply(b), great()], + Phases::default(), + Rules::Strict, + ); + assert_eq!(r.judgements, vec![Some(Judgement::Great), None, None]); + } } diff --git a/docs/decisions.md b/docs/decisions.md index bee73f6..521a372 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -175,5 +175,5 @@ - **Калибровка по chess.com (2026-10-28, владелец прислал разметку «Вечнозелёной»):** жертва — только фигура, отданная самим ходом (а не висевшая и раньше: 18…Rg8 — «!», не «!!»); правила «одна отметка на комбинацию», «уход атакованной фигуры» и «ход меняет исход» убраны (22.Bf5+! 23.Bd7+!, 13.Qa4!, 8…Qf6!). Совпало 7 из 8 отметок chess.com; 10…Nge7 (разрыв 9 % при пороге 10) — нет. Дальше калибровать по присылаемым партиям, а не подгонять порог под одну. - Второй поиск движка (лучший ход, кроме сыгранного) — **всегда**, только для подходящих ходов: разбор примерно на треть дольше. Старые разборы дозаполняются кнопкой «Обновить» без пересчёта оценок. - Для оценок из PGN (`[%eval]`) !! и ! нет: в отчёте прочерк и пояснение. -- В PGN — `$3`/`$1` с комментарием, только если у хода нет оценки автора. Русское имя `$3` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» — это теперь !. +- В PGN — `$3`/`$1` с комментарием, только если у хода нет оценки автора. Русское имя `$3` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» стал !, затем переименован в «Замечательный ход» (владелец, 2026-10-28).