Review: a piece whose capture loses more at once is no sacrifice; chess.com check set
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

18.Bxa7 (a game against Rodent, 2026-10-27) opens the d-file on the queen:
18...Rxa7 19.Rxd8. chess.com gives it no !!, and neither do the ChessCom rules
now. The games compared with chess.com live in crates/game-review/chesscom/ with
its marks as NAGs; the chesscom_check example runs them all after each change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-28 17:13:10 +03:00
parent 856ffd8f21
commit 0efe794662
6 changed files with 213 additions and 2 deletions

View file

@ -0,0 +1,15 @@
# Партии со сверкой по chess.com
Партии, в которых отметки нашего разбора (!! и !) сверены с Game Review chess.com. После
каждой калибровки правил (`src/features.rs`, `src/report.rs`) прогонять **все**:
```
cargo run --release -p game-review --example chesscom_check -- <stockfish> [узлы] [потоки]
```
- Отметки chess.com записаны в партию как NAG: `$3` — !!, `$1` — !. Других NAG здесь нет.
- Тег `ChessComMarks` — какие отметки сверялись: `"!! !"` — обе, `"!!"` — только блестящие
(отметки ! chess.com для этой партии неизвестны, наши ! не считаются расхождением).
- По умолчанию 3 000 000 узлов («Глубоко»). Оценки кэшируются в `target/chesscom-check/`:
повторный прогон после правки правил идёт без движка.
- Новую партию от владельца — сюда же, с источником в теге `Annotator`.

View file

@ -0,0 +1,13 @@
[Event "Berlin casual game"]
[Site "Berlin"]
[Date "1852.??.??"]
[White "Anderssen, Adolf"]
[Black "Dufresne, Jean"]
[Result "1-0"]
[ChessComMarks "!! !"]
[Annotator "chess.com Game Review (owner's screenshots, 2026-10-28)"]
1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d3 8. Qb3
Qf6 $1 9. e5 Qg6 10. Re1 Nge7 $1 11. Ba3 b5 12. Qxb5 Rb8 13. Qa4 $1 Bb6 14. Nbd2
Bb7 15. Ne4 Qf5 16. Bxd3 Qh5 17. Nf6+ gxf6 18. exf6 Rg8 $1 19. Rad1 Qxf3 20.
Rxe7+ $1 Nxe7 21. Qxd7+ $3 Kxd7 22. Bf5+ $1 Ke8 23. Bd7+ $1 Kf8 24. Bxe7# 1-0

View file

@ -0,0 +1,18 @@
[Event "Партия с компьютером"]
[Site "ChessPenguin"]
[Date "2026.10.27"]
[White "Rodent IV 2200 (Spassky)"]
[Black "Roman"]
[Result "0-1"]
[ChessComMarks "!!"]
[Annotator "chess.com Game Review (owner, 2026-10-28): only !! compared; 18.Bxa7 is no !!"]
1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 Qa5 8.
O-O O-O 9. Bb3 d6 10. f3 Bd7 11. Qe1 Nxd4 12. Bxd4 Bc6 13. Nd5 Qd8 14. Nxf6+
exf6 15. Qc3 d5 16. Rad1 dxe4 17. fxe4 Bxe4 18. Bxa7 Qc8 19. Bd4 Qg4 20. Rd2
Rad8 21. h3 Qg5 22. Rff2 Rxd4 $3 23. Rxd4 f5 24. Qd2 Qg3 25. Rd8 Qc7 26. Rxf8+
Bxf8 27. Kf1 Bc5 28. Qc3 Qd6 29. Rd2 Qf4+ 30. Ke1 Bxg2 $3 31. Rd8+ Bf8 32. Ke2
Qf1+ 33. Kd2 Qf4+ 34. Qe3 Qxe3+ 35. Kxe3 Bxh3 36. Kf4 Kg7 37. Rd7 Kh6 38. Bxf7
g5+ 39. Kg3 Bf1 40. Rxb7 g4 41. Bg8 Kg5 42. Kf2 Bh3 43. Rb5 Kh4 44. Bxh7 g3+ 45.
Kg1 f4 46. Be4 Kg4 47. Bf5+ Kh4 48. Bxh3 Kxh3 49. Rf5 Bd6 50. a4 Kg4 51. Rd5 Bb8
52. c4 f3 53. b4 g2 54. c5 Kh3 55. b5 Bh2+ 56. Kf2 g1=Q+ 0-1

View file

@ -0,0 +1,124 @@
//! Our !! and ! against chess.com's on every game of `chesscom/` (see its README): run it
//! after each change of the rules, to see that a fix for one game broke no other.
//!
//! `cargo run --release -p game-review --example chesscom_check -- <engine> [nodes] [threads]`
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use chess_core::{Game, Nag};
use game_review::{GameAnalysis, JobSettings, Judgement, ReviewMeta};
fn main() {
let args: Vec<String> = std::env::args().collect();
let Some(engine) = args.get(1) else {
eprintln!("usage: chesscom_check <engine> [nodes = 3000000] [threads = 8]");
std::process::exit(2);
};
let nodes: u64 = args.get(2).map_or(3_000_000, |n| n.parse().expect("nodes"));
let threads: u32 = args.get(3).map_or(8, |n| n.parse().expect("threads"));
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let cache = root
.join("../../target/chesscom-check")
.join(nodes.to_string());
std::fs::create_dir_all(&cache).expect("cache folder");
let mut files: Vec<PathBuf> = std::fs::read_dir(root.join("chesscom"))
.expect("chesscom/")
.filter_map(|e| Some(e.ok()?.path()))
.filter(|p| p.extension().is_some_and(|x| x == "pgn"))
.collect();
files.sort();
let (mut agree, mut differ) = (0, 0);
for file in files {
let text = std::fs::read_to_string(&file).expect("pgn");
let game = chess_core::parse_str(&text).game;
let mut a = GameAnalysis::new(&game, Some(&cache));
review(&mut a, &game, engine, nodes, threads);
a.save_cache(&cache).expect("cache");
let compared = game.tag("ChessComMarks").unwrap_or("!! !").to_owned();
println!(
"## {} — {} ({}; compared: {compared})",
game.tag("White").unwrap_or("?"),
game.tag("Black").unwrap_or("?"),
file.file_name().unwrap().to_string_lossy(),
);
let line = a.line().to_vec();
for i in 0..line.len() - 1 {
let node = line[i + 1];
let theirs = game.node(node).map_or("", |n| mark_of_nags(n.nags()));
let ours = match a.report.judgements[i] {
Some(Judgement::Brilliant) => "!!",
Some(Judgement::Great) => "!",
_ => "",
};
// Only the marks chess.com was compared on: with "!!" alone our ! says nothing.
let ours_compared = if ours == "!" && !compared.split(' ').any(|m| m == "!") {
""
} else {
ours
};
if theirs.is_empty() && ours_compared.is_empty() {
continue;
}
let label = game.move_label(node).unwrap_or_default();
if theirs == ours_compared {
agree += 1;
println!(" ok {label:<14} {theirs}");
} else {
differ += 1;
println!(
" DIFF {label:<14} chess.com {:<3} ours {}",
or_dash(theirs),
or_dash(ours_compared)
);
}
}
}
println!("\nagree {agree}, differ {differ}");
if differ > 0 {
std::process::exit(1);
}
}
/// Fills in what the cache lacks (all of it the first time) at `nodes`.
fn review(a: &mut GameAnalysis, game: &Game, engine: &str, nodes: u64, threads: u32) {
let meta = ReviewMeta {
engine: "check".into(),
nodes,
};
let targets = a.begin(game, meta, false);
if !targets.is_empty() {
let settings = JobSettings {
threads,
hash_mb: 256,
nodes,
eval_file: None,
};
let cancel = AtomicBool::new(false);
game_review::run(
uci::EngineConfig::new(engine),
&settings,
targets,
&cancel,
&mut |e| a.apply(e),
)
.expect("engine");
}
a.refresh(game);
}
fn mark_of_nags(nags: &[Nag]) -> &'static str {
if nags.contains(&Nag::BRILLIANT_MOVE) {
"!!"
} else if nags.contains(&Nag::GOOD_MOVE) {
"!"
} else {
""
}
}
fn or_dash(mark: &str) -> &str {
if mark.is_empty() { "—" } else { mark }
}

View file

@ -17,7 +17,9 @@ pub struct MoveFeatures {
/// Takes back on the square where the opponent has just taken.
pub recapture: bool,
/// 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.
/// points more than the move took; a piece that was lost anyway does not count, nor
/// one whose capture loses as much back at once (the move uncovered an attack on a
/// bigger piece: taking is no answer to it).
pub sacrifice: bool,
/// A capture that wins two points or more.
pub winning_capture: bool,
@ -70,6 +72,12 @@ impl MoveFeatures {
(threat, offered)
};
let (threat, offered) = worst(&given);
// Taking the offered piece loses at least as much straight away: 18.Bxa7 opening
// the d-file on the queen (18…Rxa7 19.Rxd8) offers nothing — chess.com gives no !!.
let taking_loses = given
.iter()
.filter(|t| t.0 == threat && t.1 == offered)
.any(|t| taking_loses(&after, t.2, threat));
let (threat_any, offered_any) = worst(&threats.iter().collect::<Vec<_>>());
// The moved piece was hanging where it stood: losing it is no sacrifice.
let from_threat = m
@ -84,7 +92,7 @@ impl MoveFeatures {
promotion: m.is_promotion(),
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,
sacrifice: offered >= 3 && taken - threat <= -2 && !lost_anyway && !taking_loses,
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,
@ -186,6 +194,24 @@ fn threats(pos: &Chess) -> Vec<(i32, i32, Square)> {
out
}
/// In `pos` (the opponent to move), taking on `sq` with the cheapest piece lets the
/// mover win at least `threat` elsewhere at once.
fn taking_loses(pos: &Chess, sq: Square, threat: i32) -> bool {
let Some(take) = pos
.legal_moves()
.into_iter()
.filter(|m| m.to() == sq && m.is_capture())
.min_by_key(|m| value(m.role()))
else {
return false;
};
let mut after = pos.clone();
after.play_unchecked(take);
threats(&after)
.iter()
.any(|t| t.2 != sq && t.0 >= threat)
}
/// What `by` would win taking on `sq`, whoever is to move (a piece already hanging).
fn pseudo_threat(board: &Board, sq: Square, by: Color) -> i32 {
let first = board
@ -283,6 +309,20 @@ mod tests {
assert!(f.sacrifice, "{f:?}");
}
#[test]
fn a_piece_whose_capture_loses_more_is_not_offered() {
// 18.Bxa7 (a game against Rodent, 2026-10-27): the bishop under the rook on a8, but
// the move opens the d-file on the queen: 18…Rxa7 19.Rxd8. chess.com: no !!.
let f = last(
Chess::default(),
"1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 Qa5 \
8. O-O O-O 9. Bb3 d6 10. f3 Bd7 11. Qe1 Nxd4 12. Bxd4 Bc6 13. Nd5 Qd8 \
14. Nxf6+ exf6 15. Qc3 d5 16. Rad1 dxe4 17. fxe4 Bxe4 18. Bxa7",
);
assert!(!f.sacrifice && !f.brilliant_shape(Rules::ChessCom), "{f:?}");
assert!(f.sacrifice_any, "the first rules stay as they were: {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.

View file

@ -173,6 +173,7 @@
- **!!** — корректная жертва фигуры не дешевле лёгкой (по расчёту размена соперник выигрывает ≥ 2 очков сверх взятого), ход лучший или почти лучший, после него не хуже ≈ −0,5, без него партия не была выиграна и так (лучший другой ход < 90 %). Конь за две пешки — не !!.
- **!** — ход движка №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) — нет. Дальше калибровать по присылаемым партиям, а не подгонять порог под одну.
- **Калибровка 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 -- <stockfish>`. На 2026-10-28: 10 из 10 совпадений («Вечнозелёная» 8, партия с Rodent 2 !!).
- Второй поиск движка (лучший ход, кроме сыгранного) — **всегда**, только для подходящих ходов: разбор примерно на треть дольше. Старые разборы дозаполняются кнопкой «Обновить» без пересчёта оценок.
- Для оценок из PGN (`[%eval]`) !! и ! нет: в отчёте прочерк и пояснение.
- В PGN — `$3`/`$1` с комментарием, только если у хода нет оценки автора. Русское имя `$3` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» стал !, затем переименован в «Замечательный ход» (владелец, 2026-10-28).