diff --git a/CHANGELOG.md b/CHANGELOG.md index 609b9ae..4b0792e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https engine searches a second time for the moves that could be such (about a third longer analysis); for an analysis from before, «Update» looks for them without evaluating the game again. With evaluations from the PGN alone there are none (the report says so). + 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 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/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index c523fdf..7927bf7 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -680,7 +680,12 @@ impl Review { .enumerate() { if let Some(a) = s.phase_accuracy[i] { - value_row(ui, percent(a), label, Some(accuracy_color(a, ui.visuals().dark_mode))); + value_row( + ui, + percent(a), + label, + Some(accuracy_color(a, ui.visuals().dark_mode)), + ); } } }); diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs index e4747fc..b6e5196 100644 --- a/crates/game-review/src/features.rs +++ b/crates/game-review/src/features.rs @@ -19,8 +19,6 @@ pub struct MoveFeatures { /// After the move the opponent can win a piece (a knight or more) for at least two /// points more than the move took; a piece that was lost anyway does not count. pub sacrifice: bool, - /// A piece (not the king) under attack moves away without loss. - pub escape: bool, /// A capture that wins two points or more. pub winning_capture: bool, } @@ -34,8 +32,16 @@ impl MoveFeatures { let taken = m.capture().map_or(0, value); // The opponent's best gain on each of the mover's pieces after the move. let threats = threats(&after); - let threat = threats.iter().map(|t| t.0).max().unwrap_or(0); - let offered = threats + // Offered by this move: the piece moved, or one the move left open to a bigger + // loss than before; a piece that hung already was not given by it (chess.com's + // reading: 18…Rg8 of the Evergreen game, the knight on e7 under the pawn on f6 + // before and after, is no sacrifice). + let given: Vec<&(i32, i32, Square)> = threats + .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) @@ -55,7 +61,6 @@ impl MoveFeatures { mates: after.is_checkmate(), recapture: m.is_capture() && prev.is_some_and(|p| p.is_capture() && p.to() == m.to()), sacrifice: offered >= 3 && taken - threat <= -2 && !lost_anyway, - escape: lost_anyway && from_threat < 900 && gain >= 0, winning_capture: m.is_capture() && gain >= 2, } } @@ -65,9 +70,10 @@ impl MoveFeatures { self.sacrifice && self.legal > 1 && !self.check && !self.promotion } - /// Could be great: not a forced, obvious or finishing move. + /// 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.escape && !self.recapture && !self.winning_capture + self.legal > 1 && !self.mates && !self.recapture && !self.winning_capture } /// Worth asking the engine for the best other move. @@ -219,15 +225,26 @@ mod tests { } #[test] - fn a_piece_saved_or_lost_anyway_is_no_move_of_note() { - // The bishop on c4 attacked by the pawn on d5: Bb3 saves it. + fn a_piece_saved_or_lost_anyway_is_no_sacrifice() { + // 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.escape && !f.great_shape() && !f.sacrifice, "{f:?}"); + assert!(f.great_shape() && !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:?}"); } + #[test] + fn only_what_the_move_gives_up_is_offered() { + // The knight on e5 hangs to the pawn on d6 before and after Ra2: not given by it. + let f = features("4k3/8/3p4/4N3/8/8/8/R3K3 w - - 0 1", "Ra2"); + assert!(!f.sacrifice, "{f:?}"); + // The rook on e1 guards it; Ra1 takes the guard away: the knight is given up. + let f = features("4k3/8/3p4/4N3/8/8/8/4RK2 w - - 0 1", "Ra1"); + assert!(f.sacrifice, "{f:?}"); + } + #[test] fn a_piece_no_one_can_legally_take_is_not_offered() { // The rook on d7 is pinned by the bishop: the knight on d5 is no offer to it. diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index fe2c3a5..d3b3ae3 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -143,15 +143,9 @@ mod good { pub const WON_ANYWAY: f64 = 90.0; /// !: every other move loses at least this much. pub const GAP: f64 = 10.0; - /// !: lost below, won above (the move changes which). - pub const LOST: f64 = 33.0; - pub const WON: f64 = 67.0; /// !: 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; - /// An opponent's move losing this much (or judged a mistake or a blunder: near a mate - /// the win % hardly moves) 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; @@ -163,18 +157,7 @@ pub fn worth_second(eval: Eval, mover: Color) -> bool { eval.win_percent(mover) >= good::SECOND_FROM } -/// Lost, equal, won (0, 1, 2). -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). +/// Brilliant or great, from the evaluations around the move. fn note(before: Eval, after: Eval, ply: &Ply) -> Option { let f = ply.features?; let (wb, wa) = (before.win_percent(ply.mover), after.win_percent(ply.mover)); @@ -194,7 +177,6 @@ fn note(before: Eval, after: Eval, ply: &Ply) -> Option { && ply.best && loss <= good::NEAR_BEST && wb - w2 >= good::GAP - && outcome(wa) > outcome(w2) && wa >= good::GREAT_AFTER && w2 < good::GREAT_ALT) .then_some(Judgement::Great) @@ -351,9 +333,6 @@ impl Report { ..Report::default() }; let mut losses: [Vec; 2] = [Vec::new(), Vec::new()]; - // Moves that passed !! or ! before the combination rule, 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 { @@ -362,7 +341,6 @@ 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 { @@ -373,18 +351,9 @@ impl Report { } else { None }; - noted[i] = good.is_some(); - // One mark a combination: the moves that go on with it after a mark are not - // marked again, 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 = i >= 2 && noted[i - 2] && !erred(i - 1); - let j = error.or(good.filter(|_| !goes_on)); + // 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); report.judgements[i] = j; let stats = match ply.mover { Color::White => &mut report.white, @@ -752,40 +721,20 @@ mod tests { } #[test] - fn a_combination_is_marked_once_unless_the_opponent_errs() { + fn every_move_of_a_combination_is_marked() { + // As on chess.com: 21.Qxd7+!! 22.Bf5+! 23.Bd7+! in the Evergreen game. let (w, b) = (Color::White, Color::Black); - let quiet = ply(b); let great = || noted(w, false, Some(Eval::Cp(-300))); let evals = [Some(Eval::Cp(300)); 4]; - let r = Report::build(&evals, &[great(), quiet, great()], Phases::default()); - assert_eq!(r.judgements, vec![Some(Judgement::Great), None, None]); - // Black blunders in between: a new mark. - let evals = [ - Some(Eval::Cp(300)), - Some(Eval::Cp(300)), - Some(Eval::Cp(900)), - Some(Eval::Cp(900)), - ]; - let mut strong = great(); - strong.second = Some(Eval::Cp(-300)); - let r = Report::build(&evals, &[great(), quiet, strong], Phases::default()); - assert_eq!(r.judgements[1], Some(Judgement::Blunder)); - assert_eq!(r.judgements[0], Some(Judgement::Great)); - } - - #[test] - fn an_opponent_letting_a_mate_in_starts_a_new_combination() { - // Near a mate the win % hardly moves: Black's move loses little of it but lets a - // forced mate in, a mistake; White's next move of note is marked again. - let (w, b) = (Color::White, Color::Black); - let mate = Some(Eval::Mate { - white: true, - moves: 3, - }); - let evals = [Some(Eval::Cp(900)), Some(Eval::Cp(900)), mate, mate]; - let great = || noted(w, false, Some(Eval::Cp(-300))); let r = Report::build(&evals, &[great(), ply(b), great()], Phases::default()); - assert_eq!(r.judgements[1], Some(Judgement::Mistake)); - assert_eq!(r.judgements[2], Some(Judgement::Great)); + assert_eq!( + r.judgements, + vec![Some(Judgement::Great), None, Some(Judgement::Great)] + ); + // Only the best move of a position where the others fall clearly behind. + let mut close = great(); + close.second = Some(Eval::Cp(250)); + let r = Report::build(&evals, &[close], Phases::default()); + assert_eq!(r.judgements[0], None); } } diff --git a/docs/decisions.md b/docs/decisions.md index ac3bf48..bee73f6 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -171,8 +171,8 @@ Владелец: «как на chess.com» отмечать в разборе блестящий (!!) и отличный (!) ход, везде, где отмечаются ошибки, включая значок на доске — и на телефоне тоже (там значков на доске раньше не было). Правила — по `research/brilliant-moves.md`; на открытые вопросы аналитика приняты его рекомендации (владелец может пересмотреть): - **!!** — корректная жертва фигуры не дешевле лёгкой (по расчёту размена соперник выигрывает ≥ 2 очков сверх взятого), ход лучший или почти лучший, после него не хуже ≈ −0,5, без него партия не была выиграна и так (лучший другой ход < 90 %). Конь за две пешки — не !!. -- **!** — ход движка №1, все остальные хуже не меньше чем на «ошибку», и ход меняет исход (проигрыш → равенство → выигрыш). Взятие обратно, выгодное взятие, уход атакованной фигуры и мат не отмечаются. -- **Одна отметка на комбинацию**, и для !! тоже; ошибка соперника начинает новую. +- **!** — ход движка №1, все остальные хуже не меньше чем на 10 % шанса (наша «ошибка»), после него не хуже ≈ −0,2 и без него не было уже выиграно. Взятие обратно, выгодное взятие и мат не отмечаются. +- **Калибровка по 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` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» — это теперь !.