diff --git a/CHANGELOG.md b/CHANGELOG.md index 29467e2..7dbb249 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Game review marks brilliant moves (!!, a sound piece sacrifice) and great moves (!, the + only good move that turns the game), next to inaccuracies, mistakes and blunders: in the + report, the notation, the graph and on the board; written to the game as $3 and $1. The + 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). +- Android: the board shows the move's mark in the corner of its square, as on the desktop: + the review's ?!, ?, ??, !, !! or the author's own sign. + ## [1.9.4] — 2026-10-27 - Desktop: the database cards show how many games each holds instead of «not loaded»: diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt index 7aaaf39..ff67d7c 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt @@ -156,6 +156,10 @@ data class BoardArrow(val from: String, val to: String, val color: Color, val we /// A marked square of a comment (`[%csl]`), drawn as a ring. data class BoardMark(val square: String, val color: Color) +/// A round label over the corner of the square a move went to: the move's assessment +/// (`!!`, `?`, …) or the review's judgement, as on the desktop (board.rs `Badge`). +data class BoardBadge(val square: String, val text: String, val color: Color) + /// The comment colors of the desktop app (game_view.rs `shape_color`). fun markColor(letter: String): Color = when (letter) { "R" -> Color(136, 32, 32, 170) @@ -192,6 +196,7 @@ fun Board( alert: Pair? = null, /// The files and ranks along the edges (none on a small board that only shows). coordinates: Boolean = true, + badge: BoardBadge? = null, ) { val colors = LocalChessColors.current val context = LocalContext.current @@ -389,6 +394,25 @@ fun Board( val t = squareIndex(a.to) ?: continue drawArrow(cell(f) + Offset(sq / 2, sq / 2), cell(t) + Offset(sq / 2, sq / 2), sq, a) } + badge?.let { b -> + val i = squareIndex(b.square) ?: return@let + val c = cell(i) + // Readable on a small board too (a split screen). + val r = maxOf(sq * 0.21f, with(density) { 9.dp.toPx() }) + // Over the corner of the square, kept inside the board. + val center = Offset( + (c.x + sq - r * 0.35f).coerceAtMost(size.width - r - 1f), + (c.y + r * 0.35f).coerceAtLeast(r + 1f), + ) + drawCircle(Color(0, 0, 0, 90), r, center + Offset(0f, sq * 0.015f)) + drawCircle(b.color, r, center) + drawCircle(Color.White, r, center, style = Stroke(width = sq * 0.025f)) + val label = measurer.measure( + b.text, + TextStyle(color = Color.White, fontWeight = FontWeight.Bold, fontSize = with(density) { (r * 1.05f).toSp() }), + ) + drawText(label, topLeft = center - Offset(label.size.width / 2f, label.size.height / 2f)) + } // The dragged piece: bigger and lifted above the finger, a shade on the square // under it so that one sees where it goes. val held = dragAt diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt index 078116c..6c8d480 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -128,6 +128,7 @@ import uniffi.mobile_api.EngineLine import uniffi.mobile_api.Edited import uniffi.mobile_api.GameData import uniffi.mobile_api.GameSession +import io.github.vrubelroman.chesspenguin.theme.nagColor import uniffi.mobile_api.MoveJudgement import uniffi.mobile_api.MoveNode @@ -887,7 +888,8 @@ fun GameScreen( val description = when { step != null -> stringResource(R.string.board_description, step.label) node == null || current == 0 -> stringResource(R.string.board_start) - else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san) + else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san + node.nagSymbols) + + (currentMark?.let { ", " + judgementName(it.judgement) } ?: "") } val arrows = buildList { if (p != null) { @@ -913,6 +915,17 @@ fun GameScreen( } val marks = if (p == null) node?.marks?.filter { it.to == null }?.map { BoardMark(it.from, markColor(it.color)) }.orEmpty() else emptyList() val check = (step?.label ?: node?.san ?: "").let { it.endsWith("+") || it.endsWith("#") } + // The review's judgement of the move, else the move's own assessment in the game. + // The bright colors of the dark theme on every board, as on the desktop. + val badge = node?.toSquare?.takeIf { p == null }?.let { to -> + currentMark?.let { BoardBadge(to, judgementSymbol(it.judgement), judgementColor(it.judgement, true)) } + ?: node.nags.asList().firstNotNullOfOrNull { b -> + val n = b.toInt() and 0xFF + val sym = assessmentSymbol(n) + val c = nagColor(n, true) + if (sym != null && c != null) BoardBadge(to, sym, c) else null + } + } Board( fen = fen, flipped = flipped, @@ -924,6 +937,7 @@ fun GameScreen( description = description, arrows = arrows, marks = marks, + badge = badge, check = check, animated = prefs.animation, // A touch during a preview of an engine line closes it; no move is made (§29.5). diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt index 7c136f6..ab2e8a8 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt @@ -83,20 +83,35 @@ import uniffi.mobile_api.SideReview import kotlin.math.ceil import kotlin.math.roundToInt -/// The NAG of the same sign: $6 ?!, $2 ?, $4 ??. +/// The NAG of the same sign: $3 !!, $1 !, $6 ?!, $2 ?, $4 ??. fun judgementNag(j: MoveJudgement): Int = when (j) { MoveJudgement.INACCURACY -> 6 MoveJudgement.MISTAKE -> 2 MoveJudgement.BLUNDER -> 4 + MoveJudgement.GREAT -> 1 + MoveJudgement.BRILLIANT -> 3 } -/// The colors of the NAGs ?!, ? and ?? (§21.4). +/// The colors of the NAGs !!, !, ?!, ? and ?? (§21.4). fun judgementColor(j: MoveJudgement, dark: Boolean): Color = nagColor(judgementNag(j), dark) ?: Color.Unspecified +/// The sign of a move assessment NAG ($1–$6), `null` for others. +fun assessmentSymbol(nag: Int): String? = when (nag) { + 1 -> "!" + 2 -> "?" + 3 -> "!!" + 4 -> "??" + 5 -> "!?" + 6 -> "?!" + else -> null +} + fun judgementSymbol(j: MoveJudgement): String = when (j) { MoveJudgement.INACCURACY -> "?!" MoveJudgement.MISTAKE -> "?" MoveJudgement.BLUNDER -> "??" + MoveJudgement.GREAT -> "!" + MoveJudgement.BRILLIANT -> "!!" } @Composable @@ -105,15 +120,27 @@ fun judgementName(j: MoveJudgement): String = stringResource( MoveJudgement.INACCURACY -> R.string.review_inaccuracy MoveJudgement.MISTAKE -> R.string.review_mistake MoveJudgement.BLUNDER -> R.string.review_blunder + MoveJudgement.GREAT -> R.string.review_great + MoveJudgement.BRILLIANT -> R.string.review_brilliant }, ) +/// Why a move of note is one (none for an error). +@Composable +fun judgementReason(j: MoveJudgement): String? = when (j) { + MoveJudgement.BRILLIANT -> stringResource(R.string.review_why_brilliant) + MoveJudgement.GREAT -> stringResource(R.string.review_why_great) + else -> null +} + @Composable private fun judgementPlural(j: MoveJudgement): String = stringResource( when (j) { MoveJudgement.INACCURACY -> R.string.review_inaccuracies MoveJudgement.MISTAKE -> R.string.review_mistakes MoveJudgement.BLUNDER -> R.string.review_blunders + MoveJudgement.GREAT -> R.string.review_greats + MoveJudgement.BRILLIANT -> R.string.review_brilliants }, ) @@ -201,6 +228,7 @@ fun ReviewPanel( val link = MaterialTheme.colorScheme.primary val text = buildAnnotatedString { withStyle(SpanStyle(color = c, fontWeight = FontWeight.Bold)) { append(judgementSymbol(mark.judgement) + " " + name) } + judgementReason(mark.judgement)?.let { append(" · "); append(it) } if (better != null && betterText != null) { append(" · ") append(betterText.first()) @@ -225,9 +253,10 @@ fun ReviewPanel( TextButton(onClick = onResume) { Text(stringResource(R.string.review_resume)) } report() } - state.missing > 0u -> { + state.missing > 0u || state.secondsMissing > 0u -> { Text( - stringResource(R.string.review_missing, state.missing.toInt()), + // An analysis from before !! and !: filling in looks for them only. + if (state.missing > 0u) stringResource(R.string.review_missing, state.missing.toInt()) else stringResource(R.string.review_no_seconds), style = textStyle.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), @@ -447,7 +476,9 @@ fun ReviewStartSheet( // "Fill in" keeps the quality of the first run; the choice is for starting over. val nodes = (if (partial) state.nodes else REVIEW_NODES[quality.coerceIn(0, REVIEW_NODES.size - 1)]).toDouble() val nps = (if (npsPerThread > 0) npsPerThread else GUESS_NPS_PER_THREAD).toDouble() * threads.coerceAtLeast(1) - val secs = ceil(positions * nodes / nps).toInt().coerceAtLeast(1) + // A full run also searches again for moves that could be !! or ! (about a third more). + val searches = if (partial) positions else (state?.searches?.toInt() ?: positions) + val secs = ceil(searches * nodes / nps).toInt().coerceAtLeast(1) val time = if (secs < 60) stringResource(R.string.review_seconds, secs) else stringResource(R.string.review_minutes, (secs + 59) / 60) Text( pluralStringResource(R.plurals.review_estimate, positions, positions, time), @@ -510,11 +541,20 @@ fun ReviewSheet( black = { ReportNumber(percent(state.black.accuracy), MaterialTheme.typography.headlineSmall) }, ) val next = stringResource(R.string.review_next) - listOf(MoveJudgement.INACCURACY, MoveJudgement.MISTAKE, MoveJudgement.BLUNDER).forEach { j -> + listOf( + MoveJudgement.BRILLIANT, + MoveJudgement.GREAT, + MoveJudgement.INACCURACY, + MoveJudgement.MISTAKE, + MoveJudgement.BLUNDER, + ).forEach { j -> val c = judgementColor(j, dark) val label = judgementPlural(j) + // From the PGN's evaluations alone !! and ! are not known: a dash, not a zero. + val unknown = state.nodes == 0UL && (j == MoveJudgement.BRILLIANT || j == MoveJudgement.GREAT) val cell: @Composable (Boolean, UInt, String) -> Unit = { isWhite, count, side -> - val active = count > 0u + val active = count > 0u && !unknown + val shown = if (unknown) "\u2014" else count.toString() Row( Modifier .fillMaxWidth() @@ -528,14 +568,14 @@ fun ReviewSheet( contentDescription = "$label, $side, $count" } } else { - Modifier.clearAndSetSemantics { contentDescription = "$label, $side, $count" } + Modifier.clearAndSetSemantics { contentDescription = "$label, $side, $shown" } }, ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.End, ) { Text( - count.toString(), + shown, style = MaterialTheme.typography.titleMedium.merge(Tabular), color = if (active) c else variant, ) @@ -585,6 +625,9 @@ fun ReviewSheet( style = MaterialTheme.typography.bodySmall, color = variant, ) + if (state.nodes == 0UL) { + Text(stringResource(R.string.review_no_notes), style = MaterialTheme.typography.bodySmall, color = variant) + } Spacer(Modifier.height(20.dp)) // With a large font the two buttons go on two lines instead of breaking words. FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { @@ -599,6 +642,8 @@ private fun SideReview.inaccuraciesOf(j: MoveJudgement): UInt = when (j) { MoveJudgement.INACCURACY -> inaccuracies MoveJudgement.MISTAKE -> mistakes MoveJudgement.BLUNDER -> blunders + MoveJudgement.GREAT -> great + MoveJudgement.BRILLIANT -> brilliant } /// A row of the report: its label, then White's and Black's cells, 96 dp each. diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index 860d5bf..8391b12 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -247,6 +247,12 @@ Ungenauigkeiten Fehler Grobe Fehler + Starker Zug + Brillanter Zug + Starke Züge + Brillante Züge + Ein korrektes Opfer + Der einzige gute Zug Ohne Bewertung: %d Die Analyse wurde unterbrochen Fortsetzen @@ -256,6 +262,8 @@ Endspiel %1$s · %2$s Knoten pro Zug Bewertungen aus der PGN ([%eval]) + !! und ! braucht die Engine: die PGN enthält nur Bewertungen + In dieser Analyse wurde noch nicht nach !! und ! gesucht Analyse ausblenden Bewertungsgrafik Pausiert: Partie wird analysiert diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 500b7fc..7a4e8ee 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -251,6 +251,12 @@ Imprecisiones Errores Errores graves + Gran jugada + Jugada brillante + Grandes jugadas + Jugadas brillantes + Un sacrificio correcto + La única buena jugada Sin evaluar: %d El análisis se interrumpió Continuar @@ -260,6 +266,8 @@ Final %1$s · %2$s nodos por jugada Evaluaciones del PGN ([%eval]) + !! y ! requieren el motor: el PGN solo trae evaluaciones + Este análisis aún no buscó !! ni ! Ocultar el análisis Gráfico de evaluación En pausa: se está analizando la partida diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 2f4d49a..1fc78fa 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -251,6 +251,12 @@ Imprécisions Erreurs Gaffes + Excellent coup + Coup brillant + Excellents coups + Coups brillants + Un sacrifice correct + Le seul bon coup Non évaluées : %d L\'analyse s\'est interrompue Continuer @@ -260,6 +266,8 @@ Finale %1$s · %2$s nœuds par coup Évaluations issues du PGN ([%eval]) + !! et ! demandent le moteur : le PGN ne contient que des évaluations + Cette analyse n’a pas encore cherché les !! et ! Masquer l\'analyse Graphique d\'évaluation En pause : analyse de la partie en cours diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 473a184..4c7820f 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -251,6 +251,12 @@ Imprecisioni Errori Svarioni + Ottima mossa + Mossa brillante + Ottime mosse + Mosse brillanti + Un sacrificio corretto + L\'unica buona mossa Non valutate: %d L\'analisi si è interrotta Continua @@ -260,6 +266,8 @@ Finale %1$s · %2$s nodi per mossa Valutazioni dal PGN ([%eval]) + !! e ! richiedono il motore: il PGN contiene solo valutazioni + Questa analisi non ha ancora cercato !! e ! Nascondi l\'analisi Grafico di valutazione In pausa: analisi della partita in corso diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 9ced3c8..f4a1b38 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -247,6 +247,12 @@ Дәлсіздіктер Қателер Өрескел қателер + Мықты жүріс + Тамаша жүріс + Мықты жүрістер + Тамаша жүрістер + Дұрыс құрбандық + Жалғыз жақсы жүріс Бағаланбаған: %d Талдау тоқтап қалды Жалғастыру @@ -256,6 +262,8 @@ Эндшпиль %1$s · жүріске %2$s түйін PGN-дағы бағалар ([%eval]) + !! және ! тек қозғалтқышпен: PGN-да тек бағалар бар + Бұл талдауда !! мен ! әлі ізделмеген Талдауды жасыру Бағалау графигі Кідіртілді: партия талдануда diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 82b4780..410b0fb 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -251,6 +251,12 @@ Imprecisões Erros Erros graves + Ótimo lance + Lance brilhante + Ótimos lances + Lances brilhantes + Um sacrifício correto + O único lance bom Não avaliadas: %d A análise parou Continuar @@ -260,6 +266,8 @@ Final %1$s · %2$s nós por lance Avaliações do PGN ([%eval]) + !! e ! exigem o motor: o PGN traz só avaliações + Esta análise ainda não procurou !! e ! Ocultar análise Gráfico de avaliação Em pausa: a partida está sendo analisada diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index c464039..ae71ff9 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -255,6 +255,12 @@ Неточности Ошибки Зевки + Отличный ход + Блестящий ход + Отличные ходы + Блестящие ходы + Корректная жертва + Единственный хороший ход Без оценки: %d Анализ прервался Продолжить @@ -264,6 +270,8 @@ Эндшпиль %1$s · %2$s узлов на ход Оценки из PGN ([%eval]) + !! и ! ставит только движок: в PGN есть лишь оценки + В этом анализе !! и ! ещё не искали Скрыть анализ График оценки Пауза: идёт анализ партии diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index 77fcd83..4471c11 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -247,6 +247,12 @@ Noaniqliklar Xatolar Qoʻpol xatolar + Kuchli yurish + Ajoyib yurish + Kuchli yurishlar + Ajoyib yurishlar + Toʻgʻri qurbonlik + Yagona yaxshi yurish Baholanmagan: %d Tahlil toʻxtadi Davom etish @@ -256,6 +262,8 @@ Endshpil %1$s · har yurishga %2$s tugun PGNdagi baholar ([%eval]) + !! va ! faqat dvigatel bilan: PGNda faqat baholar bor + Bu tahlilda !! va ! hali qidirilmagan Tahlilni yashirish Baho grafigi Pauza: partiya tahlil qilinmoqda diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index a0c7b5e..c79144b 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -250,6 +250,12 @@ Inaccuracies Mistakes Blunders + Great move + Brilliant move + Great moves + Brilliant moves + A sound sacrifice + The only good move Not evaluated: %d The analysis stopped Continue @@ -259,6 +265,8 @@ Endgame %1$s · %2$s nodes per move Evaluations from the PGN ([%eval]) + !! and ! need the engine: the PGN has evaluations only + !! and ! were not looked for in this analysis Hide analysis Evaluation graph Paused: the game is being analysed diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 48b3af1..ba98228 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -7915,15 +7915,15 @@ const ROWS: &[[&str; 9]] = &[ "Талдауды партияға жазу", ], [ - "Adds evaluations, ?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", - "Добавляет в партию оценки, знаки ?!/?/??, комментарии и лучшие варианты (Ctrl+Z — отменить)", - "Ajoute à la partie les évaluations, les signes ?!/?/??, des commentaires et les meilleures lignes (Ctrl+Z pour annuler)", - "Fügt der Partie Bewertungen, ?!/?/??-Zeichen, Kommentare und bessere Varianten hinzu (Strg+Z zum Rückgängigmachen)", - "Añade a la partida evaluaciones, signos ?!/?/??, comentarios y mejores líneas (Ctrl+Z para deshacer)", - "Aggiunge alla partita valutazioni, segni ?!/?/??, commenti e linee migliori (Ctrl+Z per annullare)", - "Adiciona avaliações, marcas ?!/?/??, comentários e linhas melhores à partida (Ctrl+Z para desfazer)", - "Partiyaga baholar, ?!/?/?? belgilari, izohlar va yaxshiroq liniyalarni qo‘shadi (bekor qilish: Ctrl+Z)", - "Партияға бағаларды, ?!/?/?? белгілерін, түсініктемелер мен жақсырақ варианттарды қосады (болдырмау — Ctrl+Z)", + "Adds evaluations, !!/!/?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", + "Добавляет в партию оценки, знаки !!/!/?!/?/??, комментарии и лучшие варианты (Ctrl+Z — отменить)", + "Ajoute à la partie les évaluations, les signes !!/!/?!/?/??, des commentaires et les meilleures lignes (Ctrl+Z pour annuler)", + "Fügt der Partie Bewertungen, !!/!/?!/?/??-Zeichen, Kommentare und bessere Varianten hinzu (Strg+Z zum Rückgängigmachen)", + "Añade a la partida evaluaciones, signos !!/!/?!/?/??, comentarios y mejores líneas (Ctrl+Z para deshacer)", + "Aggiunge alla partita valutazioni, segni !!/!/?!/?/??, commenti e linee migliori (Ctrl+Z per annullare)", + "Adiciona avaliações, marcas !!/!/?!/?/??, comentários e linhas melhores à partida (Ctrl+Z para desfazer)", + "Partiyaga baholar, !!/!/?!/?/?? belgilari, izohlar va yaxshiroq liniyalarni qo‘shadi (bekor qilish: Ctrl+Z)", + "Партияға бағаларды, !!/!/?!/?/?? белгілерін, түсініктемелер мен жақсырақ варианттарды қосады (болдырмау — Ctrl+Z)", ], [ "Analyse again…", @@ -10023,6 +10023,83 @@ const ROWS: &[[&str; 9]] = &[ "⇄ Siz aslini tahrirlayapsiz; uning tarjimasi o‘chiriladi", "⇄ Сіз түпнұсқаны өңдеп жатырсыз; оның аудармасы жойылады", ], + [ + "Great move", + "Отличный ход", + "Excellent coup", + "Starker Zug", + "Gran jugada", + "Ottima mossa", + "Ótimo lance", + "Kuchli yurish", + "Мықты жүріс", + ], + [ + "Brilliant moves", + "Блестящие ходы", + "Coups brillants", + "Brillante Züge", + "Jugadas brillantes", + "Mosse brillanti", + "Lances brilhantes", + "Ajoyib yurishlar", + "Тамаша жүрістер", + ], + [ + "Great moves", + "Отличные ходы", + "Excellents coups", + "Starke Züge", + "Grandes jugadas", + "Ottime mosse", + "Ótimos lances", + "Kuchli yurishlar", + "Мықты жүрістер", + ], + [ + "!! and ! need the engine: the PGN has evaluations only", + "!! и ! ставит только движок: в PGN есть лишь оценки", + "!! et ! demandent le moteur : le PGN ne contient que des évaluations", + "!! und ! braucht die Engine: die PGN enthält nur Bewertungen", + "!! y ! requieren el motor: el PGN solo trae evaluaciones", + "!! e ! richiedono il motore: il PGN contiene solo valutazioni", + "!! e ! exigem o motor: o PGN traz só avaliações", + "!! va ! faqat dvigatel bilan: PGNda faqat baholar bor", + "!! және ! тек қозғалтқышпен: PGN-да тек бағалар бар", + ], + [ + "!! and ! were not looked for in this analysis", + "В этом анализе !! и ! ещё не искали", + "Cette analyse n’a pas encore cherché les !! et !", + "In dieser Analyse wurde noch nicht nach !! und ! gesucht", + "Este análisis aún no buscó !! ni !", + "Questa analisi non ha ancora cercato !! e !", + "Esta análise ainda não procurou !! e !", + "Bu tahlilda !! va ! hali qidirilmagan", + "Бұл талдауда !! мен ! әлі ізделмеген", + ], + [ + "A sound sacrifice.", + "Корректная жертва.", + "Un sacrifice correct.", + "Ein korrektes Opfer.", + "Un sacrificio correcto.", + "Un sacrificio corretto.", + "Um sacrifício correto.", + "To‘g‘ri qurbonlik.", + "Дұрыс құрбандық.", + ], + [ + "The only good move.", + "Единственный хороший ход.", + "Le seul bon coup.", + "Der einzige gute Zug.", + "La única buena jugada.", + "L'unica buona mossa.", + "O único lance bom.", + "Yagona yaxshi yurish.", + "Жалғыз жақсы жүріс.", + ], [ "Good move", "Хороший ход", @@ -10036,7 +10113,7 @@ const ROWS: &[[&str; 9]] = &[ ], [ "Brilliant move", - "Отличный ход", + "Блестящий ход", "Coup brillant", "Brillanter Zug", "Jugada brillante", diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 189ce06..099496d 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -4,7 +4,9 @@ use std::collections::HashMap; use crate::i18n::tr; -use crate::review::{Mark, judgement_color, judgement_name, judgement_symbol}; +use crate::review::{ + Mark, judgement_color, judgement_name, judgement_reason, judgement_symbol, judgement_text_color, +}; use crate::translate_ui::Mark as Translated; use chess_core::shakmaty::{Color, Position}; use chess_core::{Game, Nag, NodeId}; @@ -608,7 +610,7 @@ fn paint_badge(ui: &Ui, cell: egui::Rect, mark: &Mark) { /// "Mistake. Best: 23…Nf6 24.Nd5 …" under a marked main-line move. Each move opens the line /// on the board up to it; the move shown on the board is highlighted like the game cursor. fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut NotationResponse) { - let color = judgement_color(mark.judgement); + let color = judgement_text_color(mark.judgement, ui.visuals().dark_mode); let start = n .game .position(mark.base) @@ -635,6 +637,9 @@ fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut Nota .color(color) .strong(), ); + if let Some(why) = judgement_reason(mark.judgement) { + ui.label(RichText::new(why).weak()); + } if mark.best_san.is_empty() { return; } diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index f295aa6..e6471c3 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -245,9 +245,9 @@ impl Review { // ----- writing into the game ------------------------------------------------- - /// Adds `[%eval]` to every main-line move and, for errors, a move-assessment NAG - /// (unless the author gave one), a comment and the better line as a variation. - /// One undo step. Returns the number of annotated errors. + /// Adds `[%eval]` to every main-line move and, for marked moves, a move-assessment + /// NAG (unless the author gave one) and a comment; for errors also the better line as + /// a variation. One undo step. Returns the number of marked moves. pub fn write_to_game(&self, game: &mut Game) -> usize { game.edit_group(|g| { let mut errors = 0; @@ -267,12 +267,20 @@ impl Review { comments.insert(0, format!("[%eval {}]", e.pgn())); } if let Some(mark) = self.analysis.marks.get(&id) { + // The author's own sign stands; praise over it would contradict it. + let authored = nags.iter().any(|n| n.is_move_assessment()); + if !mark.judgement.is_error() && authored { + let _ = g.annotate(id, nags, comments); + continue; + } errors += 1; - if !nags.iter().any(|n| n.is_move_assessment()) { + if !authored { nags.push(match mark.judgement { Judgement::Inaccuracy => Nag::DUBIOUS_MOVE, Judgement::Mistake => Nag::MISTAKE, Judgement::Blunder => Nag::BLUNDER, + Judgement::Great => Nag::GOOD_MOVE, + Judgement::Brilliant => Nag::BRILLIANT_MOVE, }); } let name = judgement_name(mark.judgement); @@ -282,7 +290,10 @@ impl Review { // Written into the game: Latin, as PGN always is. &[("judgement", &name), ("best", best)], ), - None => format!("{name}."), + None => match judgement_reason(mark.judgement) { + Some(why) => format!("{name}. {why}"), + None => format!("{name}."), + }, }; if !comments.contains(&text) { comments.push(text); @@ -472,7 +483,10 @@ impl Review { ui.label(RichText::new(label).strong()); ui.label(eval); if let Some(j) = mark { - ui.label(RichText::new(judgement_name(j)).color(judgement_color(j))); + ui.label( + RichText::new(judgement_name(j)) + .color(judgement_text_color(j, ui.visuals().dark_mode)), + ); } }); }); @@ -517,17 +531,28 @@ impl Review { ) }; ui.label(RichText::new(source).small().weak()); + if meta.nodes == 0 { + ui.label( + RichText::new(tr("!! and ! need the engine: the PGN has evaluations only")) + .small() + .weak(), + ); + } } if let Some(e) = &self.error { ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); } let missing = self.missing(); - if missing > 0 && !self.running() { + // An analysis from before !! and !: "Update" looks for them, nothing else. + let seconds = self.analysis.seconds_missing(); + if (missing > 0 || seconds > 0) && !self.running() { ui.horizontal_wrapped(|ui| { - ui.label( - RichText::new(trf("Positions without evaluation: {n}", &[("n", &missing)])) - .color(ui.visuals().warn_fg_color), - ); + let text = if missing > 0 { + trf("Positions without evaluation: {n}", &[("n", &missing)]) + } else { + tr("!! and ! were not looked for in this analysis").to_string() + }; + ui.label(RichText::new(text).color(ui.visuals().warn_fg_color)); let can_update = self.analysis.meta.as_ref().is_some_and(|m| m.nodes > 0); if can_update && ui.button(tr("Update")).clicked() { action = Some(ReportAction::Update); @@ -542,7 +567,7 @@ impl Review { egui::Button::new(tr("Write analysis to the game")), ) .on_hover_text(tr( - "Adds evaluations, ?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", + "Adds evaluations, !!/!/?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", )) .clicked() { @@ -586,23 +611,33 @@ impl Review { ui.label(RichText::new(name).strong().size(16.0)); }); let s = self.analysis.report.side(color).clone(); + let pgn_only = self.analysis.meta.as_ref().is_some_and(|m| m.nodes == 0); egui::Grid::new(("review_side", color as u8)) .num_columns(2) .spacing(vec2(10.0, 3.0)) .show(ui, |ui| { for (j, count) in [ + (Judgement::Brilliant, s.brilliant), + (Judgement::Great, s.great), (Judgement::Inaccuracy, s.inaccuracies), (Judgement::Mistake, s.mistakes), (Judgement::Blunder, s.blunders), ] { - let c = judgement_color(j); + // From the PGN's evaluations alone !! and ! are not known: a dash, + // not a zero. A row with nothing in it stays quiet. + let unknown = !j.is_error() && pgn_only; + let c = if count > 0 { + judgement_text_color(j, ui.visuals().dark_mode) + } else { + ui.visuals().weak_text_color() + }; + let shown = if unknown { + "—".to_string() + } else { + count.to_string() + }; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label( - RichText::new(count.to_string()) - .strong() - .size(15.0) - .color(c), - ); + ui.label(RichText::new(shown).strong().size(15.0).color(c)); }); let text = RichText::new(judgement_plural(j)).size(15.0).color(c); if count > 0 { @@ -759,7 +794,8 @@ impl Review { ui.add_space(6.0); let positions = self.analysis.positions(); let per_thread = self.nps_per_thread.unwrap_or(700_000.0); - let secs = positions as f64 * rs.nodes() as f64 / (per_thread * f64::from(rs.threads)); + let searches = self.analysis.searches(); + let secs = searches as f64 * rs.nodes() as f64 / (per_thread * f64::from(rs.threads)); ui.label(trf( "{n} positions, about {time}", &[("n", &positions), ("time", &format_duration(secs))], @@ -831,6 +867,33 @@ pub fn judgement_color(j: Judgement) -> Color32 { Judgement::Inaccuracy => Color32::from_rgb(0x56, 0xb4, 0xe9), Judgement::Mistake => Color32::from_rgb(0xe6, 0x8f, 0x00), Judgement::Blunder => Color32::from_rgb(0xdf, 0x53, 0x53), + // The colors of the signs ! and !! in the notation. + Judgement::Great => Color32::from_rgb(0x62, 0x9c, 0x2e), + Judgement::Brilliant => Color32::from_rgb(0x22, 0xac, 0x9a), + } +} + +/// The color of a judgement as text: on a light background darker than the bright one +/// of the badges, as on Android. +pub fn judgement_text_color(j: Judgement, dark: bool) -> Color32 { + if dark { + return judgement_color(j); + } + match j { + Judgement::Inaccuracy => Color32::from_rgb(0x1f, 0x72, 0xa8), + Judgement::Mistake => Color32::from_rgb(0xa3, 0x5f, 0x00), + Judgement::Blunder => Color32::from_rgb(0xc2, 0x3b, 0x3b), + Judgement::Great => Color32::from_rgb(0x4e, 0x7f, 0x22), + Judgement::Brilliant => Color32::from_rgb(0x12, 0x80, 0x6f), + } +} + +/// Why a move of note is one, under it in the notation and in the game's comment. +pub fn judgement_reason(j: Judgement) -> Option<&'static str> { + match j { + Judgement::Brilliant => Some(tr("A sound sacrifice.")), + Judgement::Great => Some(tr("The only good move.")), + _ => None, } } @@ -839,6 +902,8 @@ pub fn judgement_symbol(j: Judgement) -> &'static str { Judgement::Inaccuracy => "?!", Judgement::Mistake => "?", Judgement::Blunder => "??", + Judgement::Great => "!", + Judgement::Brilliant => "!!", } } @@ -847,6 +912,8 @@ pub fn judgement_name(j: Judgement) -> &'static str { Judgement::Inaccuracy => tr("Inaccuracy"), Judgement::Mistake => tr("Mistake"), Judgement::Blunder => tr("Blunder"), + Judgement::Great => tr("Great move"), + Judgement::Brilliant => tr("Brilliant move"), } } @@ -855,6 +922,8 @@ fn judgement_plural(j: Judgement) -> &'static str { Judgement::Inaccuracy => tr("Inaccuracies"), Judgement::Mistake => tr("Mistakes"), Judgement::Blunder => tr("Blunders"), + Judgement::Great => tr("Great moves"), + Judgement::Brilliant => tr("Brilliant moves"), } } diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs new file mode 100644 index 0000000..e4747fc --- /dev/null +++ b/crates/game-review/src/features.rs @@ -0,0 +1,249 @@ +//! What a move does on the board, without an engine: a piece offered (a sacrifice), a +//! piece taken back or saved, a mate (docs/research/brilliant-moves.md §3.1, §4). The +//! engine's evaluations then say whether it was brilliant (!!) or great (!). + +use chess_core::shakmaty::{Bitboard, Board, Chess, Color, Move, Position, Role, Square}; + +/// The move as the rules of !! and ! see it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MoveFeatures { + /// Legal moves in the position: one is a forced move, never marked. + pub legal: usize, + /// The mover was in check. + pub check: bool, + pub promotion: bool, + /// The move mates. + pub mates: bool, + /// 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. + 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, +} + +impl MoveFeatures { + /// `prev`: the opponent's move just before (for a recapture). + pub fn of(before: &Chess, m: &Move, prev: Option<&Move>) -> MoveFeatures { + let mover = before.turn(); + let mut after = before.clone(); + after.play_unchecked(*m); + 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 + .iter() + .filter(|t| t.0 == threat) + .map(|t| t.1) + .max() + .unwrap_or(0); + // The moved piece was hanging where it stood: losing it is no sacrifice. + let from_threat = m + .from() + .map_or(0, |f| pseudo_threat(before.board(), f, mover.other())); + let lost_anyway = from_threat >= 2; + let on_target = threats.iter().find(|t| t.2 == m.to()).map_or(0, |t| t.0); + let gain = taken - on_target; + MoveFeatures { + legal: before.legal_moves().len(), + check: before.is_check(), + 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, + escape: lost_anyway && from_threat < 900 && gain >= 0, + winning_capture: m.is_capture() && gain >= 2, + } + } + + /// Could be brilliant: a sacrifice by choice. + pub fn brilliant_shape(&self) -> bool { + self.sacrifice && self.legal > 1 && !self.check && !self.promotion + } + + /// Could be great: not a forced, obvious or finishing move. + pub fn great_shape(&self) -> bool { + self.legal > 1 && !self.mates && !self.escape && !self.recapture && !self.winning_capture + } + + /// Worth asking the engine for the best other move. + pub fn candidate(&self) -> bool { + self.brilliant_shape() || self.great_shape() + } +} + +/// Exchange values; the king's makes taking into a defended square never pay. +fn value(r: Role) -> i32 { + match r { + Role::Pawn => 1, + Role::Knight | Role::Bishop => 3, + Role::Rook => 5, + Role::Queen => 9, + Role::King => 1000, + } +} + +/// Static exchange on `sq`: what `side` gains taking first with the piece on `first`, +/// both sides then taking with their cheapest piece and free to stop (x-rays count). +fn see(board: &Board, sq: Square, first: Square, side: Color) -> i32 { + let (Some(target), Some(attacker)) = (board.role_at(sq), board.role_at(first)) else { + return 0; + }; + let mut gains = vec![value(target)]; + let mut occupied = board.occupied() ^ Bitboard::from_square(first); + let mut on_square = value(attacker); + let mut turn = side.other(); + loop { + let cheapest = (board.attacks_to(sq, turn, occupied) & occupied) + .into_iter() + .filter_map(|a| Some((value(board.role_at(a)?), a))) + .min(); + let Some((v, a)) = cheapest else { break }; + let last = gains[gains.len() - 1]; + gains.push(on_square - last); + on_square = v; + occupied ^= Bitboard::from_square(a); + turn = turn.other(); + } + for d in (1..gains.len()).rev() { + gains[d - 1] = -(-gains[d - 1]).max(gains[d]); + } + gains[0] +} + +/// The pieces (a knight or more) the side to move can win, with legal first captures: +/// (gain, value of the piece, its square). +fn threats(pos: &Chess) -> Vec<(i32, i32, Square)> { + let us = pos.turn(); + let board = pos.board(); + let legal = pos.legal_moves(); + let mut out = Vec::new(); + for sq in board.by_color(us.other()) { + let Some(r) = board.role_at(sq) else { continue }; + if matches!(r, Role::King | Role::Pawn) { + continue; + } + let first = legal + .iter() + .filter(|m| m.to() == sq && m.is_capture() && !m.is_en_passant()) + .filter_map(|m| Some((value(m.role()), m.from()?))) + .min(); + if let Some((_, from)) = first { + let g = see(board, sq, from, us); + if g > 0 { + out.push((g, value(r), sq)); + } + } + } + out +} + +/// 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 + .attacks_to(sq, by, board.occupied()) + .into_iter() + .filter_map(|a| Some((value(board.role_at(a)?), a))) + .min(); + first.map_or(0, |(_, a)| see(board, sq, a, by).max(0)) +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::shakmaty::fen::Fen; + use chess_core::shakmaty::san::San; + use chess_core::shakmaty::{CastlingMode, Chess}; + + fn position(fen: &str) -> Chess { + fen.parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap() + } + + /// The features of the last of `moves` (SAN) played from `start`. + fn last(start: Chess, moves: &str) -> MoveFeatures { + let mut pos = start; + let mut prev = None; + let sans: Vec<&str> = moves + .split_whitespace() + .filter(|t| !t.ends_with('.')) + .collect(); + for (i, san) in sans.iter().enumerate() { + let m = san.parse::().unwrap().to_move(&pos).unwrap(); + if i + 1 == sans.len() { + return MoveFeatures::of(&pos, &m, prev.as_ref()); + } + pos.play_unchecked(m); + prev = Some(m); + } + unreachable!() + } + + fn features(fen: &str, san: &str) -> MoveFeatures { + last(position(fen), san) + } + + const OPERA: &str = "1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 \ + 7. Qb3 Qe7 8. Nc3 c6 9. Bg5 b5 10. Nxb5 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 \ + 13. Rxd7 Rxd7 14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+"; + + #[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.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:?}"); + } + + #[test] + fn trades_and_good_captures_are_not_sacrifices() { + let f = last( + Chess::default(), + "1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nxd4", + ); + assert!(!f.sacrifice && f.recapture, "{f:?}"); + // 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:?}" + ); + } + + #[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. + let f = features("4k3/8/8/3p4/2B5/8/8/4K3 w - - 0 1", "Bb3"); + assert!(f.escape && !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 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. + 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:?}"); + } + + #[test] + fn exchanges_follow_the_cheapest_piece_and_x_rays() { + // Rook takes a pawn defended by a pawn: loses four. + let b = position("4k3/8/2p5/3p4/8/8/8/3RK3 w - - 0 1"); + assert_eq!(see(b.board(), Square::D5, Square::D1, Color::White), -4); + // Two rooks behind each other against one defender: the pawn is won. + let b = position("3rk3/8/8/3p4/8/8/3R4/3RK3 w - - 0 1"); + assert_eq!(see(b.board(), Square::D5, Square::D2, Color::White), 1); + } +} diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs index 1e98c4d..a937703 100644 --- a/crates/game-review/src/job.rs +++ b/crates/game-review/src/job.rs @@ -7,7 +7,7 @@ use std::time::{Duration, Instant}; use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; -use crate::{Eval, PosEval}; +use crate::{Eval, PosEval, Second}; /// A node-limited search should never take this long; stop it if it does. const SEARCH_GUARD: Duration = Duration::from_secs(300); @@ -18,6 +18,13 @@ pub struct Target { pub key: String, pub pos: EnginePosition, pub turn: Side, + /// The move played here (UCI), when it could be brilliant or great: if it is the + /// engine's best, a second search among `others` finds the best of the rest. + pub played: Option, + /// The other legal moves (UCI). + pub others: Vec, + /// The evaluation already there: only the second search is left. + pub known: Option, } /// How the engine searches. @@ -79,68 +86,132 @@ pub fn run( let _ = handle.set_hash_mb(settings.hash_mb.max(1)); let _ = handle.set_multipv(1); let _ = handle.new_game(); - for (i, t) in targets.into_iter().enumerate() { - let id = SearchId(i as u64 + 1); - handle - .search(t.pos.clone(), id, SearchLimits::Nodes(settings.nodes)) - .map_err(|e| JobFailure::Engine(e.to_string()))?; - let started = Instant::now(); - let mut stopping = false; - let mut last: Option = None; - loop { - if cancel.load(Ordering::Relaxed) { - handle.quit(); - return Ok(()); - } - if !stopping && started.elapsed() > SEARCH_GUARD { - let _ = handle.stop(); - stopping = true; - } - match handle.recv_timeout(Duration::from_millis(100)) { - Some(EngineEvent::Info { search_id, info }) if search_id == id => { - if info.multipv_index() == 1 && info.score.is_some() { - let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); - if exact || last.is_none() { - last = Some(info); - } + let mut next_id = 0; + let mut search = |pos: &EnginePosition, among: Vec| { + next_id += 1; + search_once( + &handle, + pos, + SearchId(next_id), + among, + settings.nodes, + cancel, + ) + }; + for t in targets { + let (mut eval, nps) = match t.known { + Some(e) => (e, 0), + None => { + let Some((info, best)) = search(&t.pos, Vec::new())? else { + if cancel.load(Ordering::Relaxed) { + handle.quit(); + return Ok(()); } + continue; + }; + let Some(score) = info.score else { continue }; + let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); + if let Some(b) = best + && pv.first() != Some(&b) + { + pv = vec![b]; } - Some(EngineEvent::BestMove { - search_id, best, .. - }) if search_id == id => { - if let Some(info) = last.take() - && let Some(score) = info.score - { - let eval = Eval::from_white_eval(score.to_white(t.turn).eval); - let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); - if let Some(b) = best - && pv.first() != Some(&b) - { - pv = vec![b]; - } - on_event(JobEvent::Eval { - key: t.key, - eval: PosEval { - eval, - pv, - depth: info.depth.unwrap_or(0), - }, - nps: info.nps.unwrap_or(0), + let eval = PosEval { + eval: Eval::from_white_eval(score.to_white(t.turn).eval), + pv, + depth: info.depth.unwrap_or(0), + second: None, + }; + (eval, info.nps.unwrap_or(0)) + } + }; + // The move played is the engine's best: what the best of the others gives says + // whether it was the only good move, or a sacrifice when nothing else won. + let mover = match t.turn { + Side::White => chess_core::shakmaty::Color::White, + Side::Black => chess_core::shakmaty::Color::Black, + }; + if let Some(played) = &t.played + && eval.pv.first() == Some(played) + && !t.others.is_empty() + && crate::report::worth_second(eval.eval, mover) + { + match search(&t.pos, t.others.clone())? { + // An engine that ignores `searchmoves` answers with the move played: + // no second move then. + Some((info, best)) + if best.as_ref() != Some(played) && info.pv.first() != Some(played) => + { + if let Some(score) = info.score { + eval.second = Some(Second { + without: played.clone(), + eval: Eval::from_white_eval(score.to_white(t.turn).eval), }); } - break; } - Some(EngineEvent::Terminated(reason)) => { - return Err(JobFailure::Terminated(reason)); + None if cancel.load(Ordering::Relaxed) => { + handle.quit(); + return Ok(()); } _ => {} } } + on_event(JobEvent::Eval { + key: t.key, + eval, + nps, + }); } handle.quit(); Ok(()) } +/// One node-limited search: its last full line and the best move. `None` when it gave +/// no line or `cancel` was set. +fn search_once( + handle: &uci::EngineHandle, + pos: &EnginePosition, + id: SearchId, + among: Vec, + nodes: u64, + cancel: &AtomicBool, +) -> Result)>, JobFailure> { + handle + .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) + .map_err(|e| JobFailure::Engine(e.to_string()))?; + let started = Instant::now(); + let mut stopping = false; + let mut last: Option = None; + loop { + if cancel.load(Ordering::Relaxed) { + return Ok(None); + } + if !stopping && started.elapsed() > SEARCH_GUARD { + let _ = handle.stop(); + stopping = true; + } + match handle.recv_timeout(Duration::from_millis(100)) { + Some(EngineEvent::Info { search_id, info }) if search_id == id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || last.is_none() { + last = Some(info); + } + } + } + Some(EngineEvent::BestMove { + search_id, best, .. + }) if search_id == id => { + return Ok(last.map(|info| (info, best.map(|b| b.to_string())))); + } + Some(EngineEvent::Terminated(reason)) => { + return Err(JobFailure::Terminated(reason)); + } + _ => {} + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index 70f0702..43d087a 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -12,14 +12,16 @@ use std::path::{Path, PathBuf}; use chess_core::shakmaty::san::SanPlus; use chess_core::shakmaty::uci::UciMove; -use chess_core::shakmaty::{Chess, Color, Move, Position}; +use chess_core::shakmaty::{CastlingMode, Chess, Color, Move, Position}; use chess_core::{Annotation, CommentPart, Game, NodeId, parse_comment}; use serde::{Deserialize, Serialize}; use uci::{EnginePosition, Side}; +mod features; mod job; pub mod report; +pub use features::MoveFeatures; pub use job::{JobEvent, JobFailure, JobSettings, Target, run}; pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats}; @@ -32,6 +34,18 @@ pub struct PosEval { pub pv: Vec, #[serde(default)] pub depth: u32, + /// The best move but the one played, when that one was the engine's best and could + /// be brilliant or great (older analyses have none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub second: Option, +} + +/// The best of the other moves: how the position stood without the move played. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Second { + /// The move left out (UCI). + pub without: String, + pub eval: Eval, } /// Where the evaluations came from. @@ -51,7 +65,7 @@ struct CacheFile { const CACHE_VERSION: u32 = 1; -/// An engine assessment of a main-line move. +/// An engine assessment of a main-line move: an error, or a move of note (!!, !). #[derive(Clone, Debug)] pub struct Mark { pub judgement: Judgement, @@ -79,6 +93,11 @@ pub struct GameAnalysis { values: Vec>, /// Positions without legal moves (mate, stalemate): no engine needed. terminal: Vec, + /// What each move of the line does on the board (`features[i]`: the move from + /// position `i`); `None` for a null move. + features: Vec>, + /// The move played from each position of the line (UCI; `None` for a null move). + played: Vec>, pub report: Report, pub marks: HashMap, } @@ -98,6 +117,8 @@ impl GameAnalysis { movers: Vec::new(), values: Vec::new(), terminal: Vec::new(), + features: Vec::new(), + played: Vec::new(), report: Report::default(), marks: HashMap::new(), }; @@ -143,6 +164,19 @@ impl GameAnalysis { self.terminal.iter().filter(|t| !**t).count() } + /// Engine searches a full analysis is expected to make, for its time: one per + /// position, and a second one for about half of the moves that could be brilliant or + /// great (those the engine finds best too). + pub fn searches(&self) -> usize { + let candidates = self + .features + .iter() + .flatten() + .filter(|f| f.candidate()) + .count(); + self.positions() + candidates / 2 + } + /// 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()) { @@ -165,18 +199,78 @@ impl GameAnalysis { self.meta = Some(ReviewMeta { nodes, ..meta }); self.rebuild(game); (0..self.line.len()) - .filter(|i| self.values[*i].is_none()) .filter_map(|i| { + let known = self.evals.get(&self.keys[i]).cloned(); + // Already evaluated: only a missing second search can be left. + if known.is_some() && !self.second_missing(i) + || known.is_none() && self.values[i].is_some() + { + return None; + } + let here = game.position(self.line[i])?; + // The move played, when it could be brilliant or great. + let played = self + .features + .get(i) + .copied() + .flatten() + .filter(|f| f.candidate()) + .and_then(|_| self.played.get(i).cloned().flatten()); + let others = match &played { + Some(p) => here + .legal_moves() + .iter() + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + .filter(|u| u != p) + .collect(), + None => Vec::new(), + }; let (key, pos) = position_key(game, self.line[i])?; - let turn = match game.position(self.line[i])?.turn() { + let turn = match here.turn() { Color::White => Side::White, Color::Black => Side::Black, }; - Some(Target { key, pos, turn }) + Some(Target { + key, + pos, + turn, + played, + others, + known, + }) }) .collect() } + /// Position `i` is evaluated, its move could be brilliant or great and was the + /// engine's best, but the best other move was never searched for (an analysis from + /// before !! and !). + fn second_missing(&self, i: usize) -> bool { + let (Some(e), Some(Some(played)), Some(Some(f))) = ( + self.evals.get(&self.keys[i]), + self.played.get(i), + self.features.get(i), + ) else { + return false; + }; + f.candidate() + && e.pv.first() == Some(played) + && report::worth_second(e.eval, self.movers[i]) + && e.second.as_ref().map(|s| &s.without) != Some(played) + } + + /// Positions whose evaluation is there but which still want the second search of + /// !! and ! ("Update" fills them in without evaluating anything again). None for + /// evaluations from the PGN, which have no engine lines. + pub fn seconds_missing(&self) -> usize { + if self.meta.as_ref().is_none_or(|m| m.nodes == 0) { + return 0; + } + (0..self.played.len()) + .filter(|i| self.second_missing(*i)) + .count() + } + /// Takes in what the engine job reported. pub fn apply(&mut self, event: JobEvent) { match event { @@ -217,14 +311,38 @@ impl GameAnalysis { .or_else(|| positions.get(i).and_then(terminal_eval)) }) .collect(); + let moves: Vec> = (1..self.line.len()) + .map(|i| match game.game_move(self.line[i]).map(|m| m.kind) { + Some(chess_core::MoveKind::Normal(m)) => Some(m), + _ => None, + }) + .collect(); + self.features = (0..moves.len()) + .map(|i| { + let (m, before) = (moves[i].as_ref()?, positions.get(i)?); + let prev = i.checked_sub(1).and_then(|p| moves[p].as_ref()); + Some(MoveFeatures::of(before, m, prev)) + }) + .collect(); + self.played = (1..self.line.len()) + .map(|i| game.game_move(self.line[i]).and_then(|m| m.uci())) + .collect(); let mut plies = Vec::with_capacity(self.line.len().saturating_sub(1)); for i in 1..self.line.len() { let mv = game.game_move(self.line[i]); - let best = self.evals.get(&self.keys[i - 1]).and_then(|e| e.pv.first()); + let e = self.evals.get(&self.keys[i - 1]); + let best = e.and_then(|e| e.pv.first()); + let played = mv.and_then(|m| m.uci()); plies.push(Ply { mover: positions.get(i - 1).map_or(Color::White, |p| p.turn()), null: mv.is_none_or(|m| m.is_null()), - best: best.is_some() && mv.and_then(|m| m.uci()).as_ref() == best, + best: best.is_some() && played.as_ref() == best, + features: self.features[i - 1], + // Only for the move played now (the line may have changed since). + second: e + .and_then(|e| e.second.as_ref()) + .filter(|s| Some(&s.without) == played.as_ref()) + .map(|s| s.eval), }); } self.movers = plies.iter().map(|p| p.mover).collect(); @@ -233,8 +351,9 @@ impl GameAnalysis { for (i, j) in self.report.judgements.iter().enumerate() { let Some(judgement) = *j else { continue }; let (base, node) = (self.line[i], self.line[i + 1]); + // A better line only for an error: a good move was the best one. let (best, best_san) = match (self.evals.get(&self.keys[i]), positions.get(i)) { - (Some(e), Some(root)) => parse_pv(root, &e.pv), + (Some(e), Some(root)) if judgement.is_error() => parse_pv(root, &e.pv), _ => (Vec::new(), Vec::new()), }; let best_label = best_san.first().and_then(|san| { @@ -263,7 +382,11 @@ impl GameAnalysis { /// the player best answers, the first two moves of the engine line from the position /// after the move (shown as arrows, as on Lichess). pub fn refutation(&self, node: NodeId, game: &Game) -> Vec { - if !self.marks.contains_key(&node) { + if !self + .marks + .get(&node) + .is_some_and(|m| m.judgement.is_error()) + { return Vec::new(); } let (Some(i), Some(pos)) = ( @@ -397,6 +520,7 @@ impl GameAnalysis { eval, pv: Vec::new(), depth: 0, + second: None, }, ); } @@ -521,6 +645,7 @@ mod tests { eval: Eval::Cp(20 - i as i32 * 300), pv: vec!["e2e4".into()], depth: 10, + second: None, }, nps: 0, }); @@ -541,7 +666,13 @@ mod tests { engine: "Fake".into(), nodes: 250, }; - assert!(c.begin(&g, fast.clone(), false).is_empty()); + // Nothing left to evaluate; 1.e4, the engine's best, still wants the best other + // move (an analysis from before !! and !). + assert_eq!(c.seconds_missing(), 1); + let left = c.begin(&g, fast.clone(), false); + assert_eq!(left.len(), 1); + assert!(left[0].known.is_some() && left[0].played.as_deref() == Some("e2e4")); + assert!(!left[0].others.is_empty() && !left[0].others.contains(&"e2e4".to_string())); assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(1000)); c.begin(&g, fast, true); assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(250)); @@ -563,6 +694,7 @@ mod tests { eval: Eval::Cp(20), pv: vec![], depth: 1, + second: None, }, nps: 0, }); diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index ae3c180..fe2c3a5 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -117,6 +117,87 @@ pub enum Judgement { Inaccuracy, Mistake, Blunder, + /// The only good move, or one that turned the game (!). + Great, + /// A sound sacrifice of a piece (!!). + Brilliant, +} + +impl Judgement { + /// An error (?!, ?, ??), not a move of note. + pub fn is_error(self) -> bool { + matches!( + self, + Judgement::Inaccuracy | Judgement::Mistake | Judgement::Blunder + ) + } +} + +/// The thresholds of !! and ! in the mover's win % (docs/research/brilliant-moves.md §10). +mod good { + /// At most this behind the engine's best move. + pub const NEAR_BEST: f64 = 2.0; + /// !!: the position after the sacrifice is at least this good. + pub const SOUND_AFTER: f64 = 45.0; + /// !!: without the move the game was not won anyway. + 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; +} + +/// Whether the best other move is worth searching for: the move played was the engine's +/// best (`eval` the position's evaluation), and the position is good enough for !! or !. +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). +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)); + 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() + && (ply.best || loss <= good::NEAR_BEST) + && wa >= good::SOUND_AFTER + && without.is_some_and(|w| w < good::WON_ANYWAY) + { + return Some(Judgement::Brilliant); + } + let w2 = second?; + (f.great_shape() + && 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) } /// Judgement of a move from the evaluations before and after it. @@ -221,6 +302,10 @@ pub struct Ply { pub null: bool, /// The move played equals the engine's best move (never judged as an error). pub best: bool, + /// What the move does on the board (`None`: not known, never !! or !). + pub features: Option, + /// The best other move's evaluation, when the move played was the best. + pub second: Option, } #[derive(Clone, Debug, Default, PartialEq)] @@ -228,6 +313,8 @@ pub struct SideStats { pub inaccuracies: u32, pub mistakes: u32, pub blunders: u32, + pub great: u32, + pub brilliant: u32, /// Average centipawn loss. pub acpl: Option, pub accuracy: Option, @@ -264,6 +351,9 @@ 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 { @@ -272,11 +362,29 @@ impl Report { if ply.null { continue; } - let j = if ply.best { + 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) + } 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)); report.judgements[i] = j; let stats = match ply.mover { Color::White => &mut report.white, @@ -286,6 +394,8 @@ impl Report { Some(Judgement::Inaccuracy) => stats.inaccuracies += 1, Some(Judgement::Mistake) => stats.mistakes += 1, Some(Judgement::Blunder) => stats.blunders += 1, + Some(Judgement::Great) => stats.great += 1, + Some(Judgement::Brilliant) => stats.brilliant += 1, None => {} } let loss = (before.cp_for(ply.mover) - after.cp_for(ply.mover)).max(0); @@ -398,6 +508,8 @@ mod tests { mover, null: false, best: false, + features: None, + second: None, } } @@ -566,4 +678,114 @@ mod tests { assert_eq!(p.of(0), Phase::Opening); assert_eq!(p.of(mid), Phase::Middlegame); } + + fn noted(mover: Color, sacrifice: bool, second: Option) -> Ply { + Ply { + mover, + null: false, + best: true, + features: Some(crate::MoveFeatures { + legal: 30, + sacrifice, + ..Default::default() + }), + second, + } + } + + #[test] + fn a_sound_sacrifice_is_brilliant_unless_the_game_was_won_anyway() { + let w = Color::White; + let evals = [Some(Eval::Cp(100)), Some(Eval::Cp(100))]; + let r = Report::build( + &evals, + &[noted(w, true, Some(Eval::Cp(-100)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], Some(Judgement::Brilliant)); + assert_eq!(r.white.brilliant, 1); + // Another move won as well: no !!. + let r = Report::build( + &evals, + &[noted(w, true, Some(Eval::Cp(800)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], None); + // No best other move known (an older analysis): nothing said. + let r = Report::build(&evals, &[noted(w, true, None)], Phases::default()); + assert_eq!(r.judgements[0], None); + // Unsound: the position after it is bad. + let bad = [Some(Eval::Cp(-200)), Some(Eval::Cp(-200))]; + let r = Report::build( + &bad, + &[noted(w, true, Some(Eval::Cp(-400)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], None); + } + + #[test] + fn the_only_move_that_turns_the_game_is_great() { + let w = Color::White; + let evals = [Some(Eval::Cp(300)), Some(Eval::Cp(300))]; + let r = Report::build( + &evals, + &[noted(w, false, Some(Eval::Cp(-300)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], Some(Judgement::Great)); + assert_eq!(r.white.great, 1); + // Others are worse but still win: not great. + let r = Report::build( + &evals, + &[noted(w, false, Some(Eval::Cp(250)))], + Phases::default(), + ); + assert_eq!(r.judgements[0], None); + // Not the engine's move: never great. + let mut p = noted(w, false, Some(Eval::Cp(-300))); + p.best = false; + assert_eq!( + Report::build(&evals, &[p], Phases::default()).judgements[0], + None + ); + } + + #[test] + fn a_combination_is_marked_once_unless_the_opponent_errs() { + 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)); + } } diff --git a/crates/mobile-api/src/review.rs b/crates/mobile-api/src/review.rs index e2af865..822408f 100644 --- a/crates/mobile-api/src/review.rs +++ b/crates/mobile-api/src/review.rs @@ -22,12 +22,16 @@ use shakmaty::Color; use crate::EngineLine; use crate::engine::{line_with, pawns}; -/// How bad a move was. +/// How bad a move was, or that it was of note. #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] pub enum MoveJudgement { Inaccuracy, Mistake, Blunder, + /// The only good move, or one that turned the game (!). + Great, + /// A sound sacrifice of a piece (!!). + Brilliant, } impl From for MoveJudgement { @@ -36,6 +40,8 @@ impl From for MoveJudgement { Judgement::Inaccuracy => MoveJudgement::Inaccuracy, Judgement::Mistake => MoveJudgement::Mistake, Judgement::Blunder => MoveJudgement::Blunder, + Judgement::Great => MoveJudgement::Great, + Judgement::Brilliant => MoveJudgement::Brilliant, } } } @@ -59,6 +65,8 @@ pub struct SideReview { pub inaccuracies: u32, pub mistakes: u32, pub blunders: u32, + pub great: u32, + pub brilliant: u32, /// Average centipawn loss. pub acpl: Option, /// Accuracy 0..100 (only when every position is evaluated). @@ -68,7 +76,8 @@ pub struct SideReview { pub endgame: Option, } -/// An inaccuracy, mistake or blunder of the main line. +/// A marked move of the main line: an inaccuracy, mistake or blunder, or a great or +/// brilliant move (these have no better line and no reply). #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct ReviewMove { /// The node of the move. @@ -104,8 +113,14 @@ pub struct ReviewState { pub nodes: u64, /// Positions of the main line without an evaluation. pub missing: u32, + /// Evaluated positions still waiting for the second search of !! and ! (an analysis + /// from before them): "fill in" does it. + pub seconds_missing: u32, /// Positions a full analysis looks at (for the time estimate). pub positions: u32, + /// Engine searches a full analysis is expected to make (for the time estimate: a + /// second search for moves that could be brilliant or great). + pub searches: u32, /// The engine's speed in the last run, per thread (0 when unknown). pub nps_per_thread: u64, /// The start position and the position after every main-line move. @@ -115,7 +130,7 @@ pub struct ReviewState { pub endgame: Option, pub white: SideReview, pub black: SideReview, - /// The errors, in the order of the game. + /// The marked moves, in the order of the game. pub moves: Vec, } @@ -347,6 +362,8 @@ fn side(s: &SideStats) -> SideReview { inaccuracies: s.inaccuracies, mistakes: s.mistakes, blunders: s.blunders, + great: s.great, + brilliant: s.brilliant, acpl: s.acpl, accuracy: s.accuracy, opening: s.phase_accuracy[0], @@ -380,17 +397,20 @@ fn snapshot(st: &Inner) -> ReviewState { let Some(mark) = a.marks.get(id) else { continue; }; - let best = a.eval_at(i - 1).filter(|e| !e.pv.is_empty()).and_then(|e| { - let root = st.game.position(mark.base)?; - let (cp, mate) = match e.eval { - Eval::Cp(cp) => (Some(cp), None), - Eval::Mate { white, moves } => ( - None, - Some(if white { moves as i32 } else { -(moves as i32) }), - ), - }; - Some(line_with(root, 1, cp, mate, &e.pv)) - }); + let best = a + .eval_at(i - 1) + .filter(|e| !e.pv.is_empty() && mark.judgement.is_error()) + .and_then(|e| { + let root = st.game.position(mark.base)?; + let (cp, mate) = match e.eval { + Eval::Cp(cp) => (Some(cp), None), + Eval::Mate { white, moves } => ( + None, + Some(if white { moves as i32 } else { -(moves as i32) }), + ), + }; + Some(line_with(root, 1, cp, mate, &e.pv)) + }); // The reply is the first move of the engine line after the bad move. let reply = a .eval_at(i) @@ -418,7 +438,9 @@ fn snapshot(st: &Inner) -> ReviewState { engine: meta.engine, nodes: meta.nodes, missing: a.missing() as u32, + seconds_missing: a.seconds_missing() as u32, positions: a.positions() as u32, + searches: a.searches() as u32, nps_per_thread: st.nps_per_thread, points, middlegame: a.report.phases.middlegame.map(|i| i as u32), diff --git a/crates/uci/src/engine.rs b/crates/uci/src/engine.rs index 6377e6e..6a4b726 100644 --- a/crates/uci/src/engine.rs +++ b/crates/uci/src/engine.rs @@ -137,6 +137,7 @@ enum Cmd { position: EnginePosition, id: SearchId, limits: SearchLimits, + among: Vec, }, Stop, /// A complete `setoption ...` / `ucinewgame` line, applied while idle. @@ -219,12 +220,28 @@ impl EngineHandle { position: EnginePosition, search_id: SearchId, limits: SearchLimits, + ) -> Result<(), EngineError> { + self.search_among(position, search_id, limits, Vec::new()) + } + + /// A search among these moves only (`go … searchmoves`, UCI moves of `position`); + /// empty: all of them. A move that is not a UCI move is refused. + pub fn search_among( + &self, + position: EnginePosition, + search_id: SearchId, + limits: SearchLimits, + among: Vec, ) -> Result<(), EngineError> { position.validate()?; + if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) { + return Err(EngineError::InvalidInput(format!("not a move: {bad:?}"))); + } self.send(Cmd::Search { position, id: search_id, limits, + among, }) } @@ -707,6 +724,7 @@ struct PendingSearch { position: EnginePosition, id: SearchId, limits: SearchLimits, + among: Vec, } struct Supervisor { @@ -828,11 +846,13 @@ impl Supervisor { position, id, limits, + among, } => { if let Some(old) = self.pending.replace(PendingSearch { position, id, limits, + among, }) { self.emit(EngineEvent::Superseded { search_id: old.id }); } @@ -934,7 +954,12 @@ impl Supervisor { match self.pending.take() { Some(p) => { self.write(&p.position.to_command())?; - self.write(&p.limits.to_command())?; + let mut go = p.limits.to_command(); + if !p.among.is_empty() { + go += " searchmoves "; + go += &p.among.join(" "); + } + self.write(&go)?; self.state = State::Searching { id: p.id }; self.emit(EngineEvent::SearchStarted { search_id: p.id }); } diff --git a/crates/uci/src/types.rs b/crates/uci/src/types.rs index 72c4fc2..148354f 100644 --- a/crates/uci/src/types.rs +++ b/crates/uci/src/types.rs @@ -269,7 +269,7 @@ impl EnginePosition { } } -fn is_uci_move(m: &str) -> bool { +pub(crate) fn is_uci_move(m: &str) -> bool { let b = m.as_bytes(); let sq = |f: u8, r: u8| (b'a'..=b'h').contains(&f) && (b'1'..=b'8').contains(&r); match b.len() { diff --git a/docs/decisions.md b/docs/decisions.md index 0c7a3e5..ac3bf48 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -166,3 +166,14 @@ - **Только полная сборка** (Stockfish внутри): лёгкая для `rustore` отключена. - **Тот же пакет и тот же ключ**, что у сайта: одно и то же приложение, ставится поверх с сохранением баз и настроек в обе стороны. - **Собирается на GitHub при каждом выпуске** (`androidApp/scripts/release.sh` → `androidApp/dist-rustore/ChessPenguin-<версия>-rustore.apk`): артефакт `rustore` прогона «Release», **не файл выпуска** — на сайте и в списке скачиваний его нет; в RuStore загружается вручную. Скрипт проверяет, что разрешения на установку в нём нет. + +## Блестящий и отличный ход (2026-10-28) + +Владелец: «как на chess.com» отмечать в разборе блестящий (!!) и отличный (!) ход, везде, где отмечаются ошибки, включая значок на доске — и на телефоне тоже (там значков на доске раньше не было). Правила — по `research/brilliant-moves.md`; на открытые вопросы аналитика приняты его рекомендации (владелец может пересмотреть): +- **!!** — корректная жертва фигуры не дешевле лёгкой (по расчёту размена соперник выигрывает ≥ 2 очков сверх взятого), ход лучший или почти лучший, после него не хуже ≈ −0,5, без него партия не была выиграна и так (лучший другой ход < 90 %). Конь за две пешки — не !!. +- **!** — ход движка №1, все остальные хуже не меньше чем на «ошибку», и ход меняет исход (проигрыш → равенство → выигрыш). Взятие обратно, выгодное взятие, уход атакованной фигуры и мат не отмечаются. +- **Одна отметка на комбинацию**, и для !! тоже; ошибка соперника начинает новую. +- Второй поиск движка (лучший ход, кроме сыгранного) — **всегда**, только для подходящих ходов: разбор примерно на треть дольше. Старые разборы дозаполняются кнопкой «Обновить» без пересчёта оценок. +- Для оценок из PGN (`[%eval]`) !! и ! нет: в отчёте прочерк и пояснение. +- В PGN — `$3`/`$1` с комментарием, только если у хода нет оценки автора. Русское имя `$3` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» — это теперь !. + diff --git a/docs/design/user-comments.md b/docs/design/user-comments.md index 0da2049..dca1160 100644 --- a/docs/design/user-comments.md +++ b/docs/design/user-comments.md @@ -218,7 +218,7 @@ |---|---|---|---| | ! | 1 | Хороший ход / Good move | Ctrl+1 | | ? | 2 | Ошибка / Mistake | Ctrl+2 | -| !! | 3 | Отличный ход / Brilliant move | Ctrl+3 | +| !! | 3 | Блестящий ход / Brilliant move | Ctrl+3 | | ?? | 4 | Грубая ошибка / Blunder | Ctrl+4 | | !? | 5 | Интересный ход / Interesting move | Ctrl+5 | | ?! | 6 | Сомнительный ход / Dubious move | Ctrl+6 | diff --git a/docs/research/brilliant-moves.md b/docs/research/brilliant-moves.md new file mode 100644 index 0000000..d791b7e --- /dev/null +++ b/docs/research/brilliant-moves.md @@ -0,0 +1,232 @@ +# Блестящий (!!) и отличный (!) ход в разборе партии + +Статус: исследование аналитика, 2026-10-28; **реализовано** (см. `docs/decisions.md`, «Блестящий и отличный ход»). Отступления реализации от текста ниже: второй поиск не делается, если позиция ходящего хуже 38 % (ни !!, ни ! там невозможны); комбинацию прерывает и ход соперника, оценённый как ошибка или зевок (у мата win % почти не меняется); ответ движка, проигнорировавшего `searchmoves`, отбрасывается. Запрос владельца: в «Разборе партии», как на chess.com, отмечать **блестящий ход (!!)**, то есть хорошую жертву фигуры, и **отличный ход (!)**, то есть ход, решающий исход: единственный хороший или переводящий проигранную позицию в равную. Отметки нужны везде, где сейчас есть ?! / ? / ??: в нотации, в счётчиках отчёта и значком на доске (desktop и Android). + +Ниже сначала проверенные факты, потом предложение. Пороги проверены прототипом на реальных партиях (§9), но это рекомендация, а не утверждённое решение. + +## 1. Проверенные факты + +### 1.1. chess.com (официальный текст) + +Источник: , проверено 2026-10-28. + +- Brilliant: «a Brilliant move is when you find a good piece sacrifice»; «always the best or nearly best move»; «You should not be in a bad position after a Brilliant move»; «You should not be completely winning even if you hadn't found the move»; к новичкам критерий жертвы мягче. +- Great: «critical to the outcome of the game», например «turning a losing position into an equal one, an equal position into a winning one» или нахождение единственного хорошего хода; к новичкам тоже мягче. +- Полосы потери ожидаемых очков: Best 0; Excellent ≤ 0,02; Good ≤ 0,05; Inaccuracy ≤ 0,10; Mistake ≤ 0,20; Blunder > 0,20. Ожидаемые очки там зависят от рейтинга. +- Точный алгоритм закрыт. + +### 1.2. Открытый аналог (только идеи, код не брать) + +Проект WintrCat/freechess (, `src/lib/analysis.ts`) повторяет классификацию chess.com. GitHub API показывает лицензию `NOASSERTION` («Other»), поэтому код **не заимствуем**, только сверяем идеи: +- Brilliant: ход лучший; оценка после него ≥ 0; второй ход не ≥ +7,00 («winningAnyways»); не превращение; ход не из-под шаха; после хода «висит» фигура дороже взятой. Короли и пешки не жертвы. Если взять жертву нельзя (связка), это не brilliant. Для лёгких фигур отдельно: если взятие допускает мат в 1, это тоже не brilliant. +- Great: ход лучший, предыдущий ход соперника — зевок, разрыв между первой и второй линией ≥ 150 cp, фигура на поле назначения не висит. + +### 1.3. Наш код (проверено чтением, коммит fb4e7ba) + +- `crates/game-review/src/report.rs`: `win_percent` — формула Lichess, `50 + 50·(2/(1+e^(−0.00368208·cp)) − 1)`; cp обрезаются до ±1000, мат тоже считается ±1000 (≈ 97,5 %). `judge()` считает падение winning chances: Inaccuracy ≥ 0,1, Mistake ≥ 0,2, Blunder ≥ 0,3. **В пунктах win% это 5 / 10 / 15**: winning chances = (win% − 50)/50. Ход, совпавший с лучшим ходом движка (`Ply.best`, сравнение UCI), ошибкой не считается. +- `job.rs`: MultiPV 1 (`set_multipv(1)`), один поиск `go nodes N` на позицию, PV хранится до 12 полуходов. N берётся из `REVIEW_QUALITY` (`apps/desktop/src/settings.rs`): Fast 250 000, Normal 1 000 000, Deep 3 000 000. Потоков по умолчанию — половина ядер. +- `lib.rs`: `PosEval { eval, pv, depth }` по ключу позиции, кэш `CACHE_VERSION = 1`. Если оценки взяты из `[%eval]` PGN, PV нет (`pv: Vec::new()`), то есть **неизвестен лучший ход и вторая линия**. В этом режиме !! и ! вычислить нельзя. +- `crates/uci`: `SearchLimits` = Infinite / Depth / MoveTime / Nodes. **`searchmoves` нет**, а для второго прохода (§6) его нужно добавить. +- `shakmaty 0.30.2` (workspace): есть `Board::attacks_to(sq, color, occupied)`, `attacks::*`, `legal_moves()`, `is_checkmate()`. **SEE нет**, его пишем сами (≈ 40 строк, §3.1). +- `chess-core/src/nag.rs`: `Nag::GOOD_MOVE = $1`, `Nag::BRILLIANT_MOVE = $3` уже есть. `apps/desktop/src/review.rs::write_to_game` ставит NAG только если у хода нет другой оценки хода (`is_move_assessment`). + +## 2. Обозначения (все величины с точки зрения ходящего) + +| Имя | Что это | Откуда | +|---|---|---| +| `Wb` | win% лучшего хода = оценка позиции до хода | `values[i]` | +| `Wa` | win% после сыгранного хода | `values[i+1]` | +| `loss` | `Wb − Wa` (может быть < 0 из-за шума) | | +| `W2` | win% лучшего хода **кроме** хода движка №1 | новый второй проход (§6) | +| `Walt` | лучшее, что было **без** сыгранного хода: `W2`, если сыгран ход №1, иначе `Wb` | | +| `best` | сыгранный ход = PV[0] движка | `Ply.best` | + +Опорные значения win% ↔ cp: 45 ≈ −0,54; 33 ≈ −1,96; 67 ≈ +1,96; 75 ≈ +3,0; 85 ≈ +4,7; 90 ≈ +6,0; 97,5 = потолок (+10 или мат). + +## 3. Блестящий ход (!!) — предлагаемое правило + +Ход получает !!, если выполнены **все** условия: + +1. Обычный ход: не `--`, в позиции больше одного легального хода, ходящий **не под шахом**, ход **не превращение**. +2. **Жертва** (§3.1): материальный дефицит `D ≥ 2` при отданной фигуре не дешевле лёгкой. +3. **Лучший или почти лучший**: `best` или `loss ≤ 2,0` (полоса Excellent chess.com; наша неточность начинается с 5). +4. **После хода позиция не плохая**: `Wa ≥ 45` (не хуже ≈ −0,5). +5. **Без этого хода позиция не выиграна полностью**: `Walt < 90` (меньше ≈ +6). Если `W2` нет, !! не ставим. + +Маты: сам матующий ход жертвой быть не может, потому что брать нечем. Если матует и запасной ход, то `Walt = 97,5 ≥ 90` и !! нет. Так отсеивается 22.Qf6+ в «Бессмертной», где мат был и без жертвы. + +### 3.1. Жертва: SEE после хода + +Стоимость: P 1, N 3, B 3, R 5, Q 9; король в размене — 1000. + +1. `A` — позиция после хода (ходит соперник). Для каждой своей фигуры X не дешевле 3 (не король, не пешка) на поле s ищем **легальные** взятия соперника на s (`A.legal_moves()`, так абсолютная связка и шах учитываются сами). Если взятий нет, фигура не предложена. +2. Первым бьёт самый дешёвый из легально берущих. Дальше идёт стандартный swap-off: следующие взятия через `attacks_to(s, color, occ) & occ` с обновлением `occ`, так что рентген учитывается; легальность следующих взятий и превращения не проверяем. Минимакс с правом остановиться: `g[d] = v[d−1] − g[d−1]`, затем `g[d−1] = −max(−g[d−1], g[d])`. +3. `T` = максимум выигрыша соперника по всем таким s (только > 0), `P` — стоимость фигуры на этом поле. +4. `C` — стоимость взятого самим ходом (взятие на проходе = 1). +5. `D = T − C`. **Жертва, если `D ≥ 2` и `P ≥ 3`.** Учитываются и сама сходившая фигура, и фигура, оставленная под боем в другом месте. Так 11.Rg1 в «Бессмертной» засчитывается: слон b5 оставлен под пешкой, хотя его можно было увести. +6. **Отчаянная фигура (desperado) и бегство не жертва.** Если сходившая фигура уже стояла под боем до хода (тот же SEE на поле `from` в позиции до хода, соперник бьёт без учёта очереди хода, ≥ 2), жертвы нет: фигура пропадала и так. Пример: в джеромовском гамбите (вилка 6.d4) 6...Bxd4 — по SEE «жертва», а по сути возврат материала, который всё равно терялся. + +Что этим исключается без отдельных правил: +- **Размен** и взятие защищённой фигуры равной стоимости: `D ≤ 0`. +- **Взятие с отыгрышем** (Qxd8+ Kxd8): `D = 0`. +- **Конь за две пешки** (`D = 1`) — не !!. Так 10.Nxb5 в «Опере» получает ! (§9), а не !!. Это вопрос к владельцу (§11). +- **Пешечные жертвы**: P < 3. +- **Невозможность взять** из-за абсолютной связки: легального взятия нет. + +**Соперник не взял (в PV движка жертва не принята), но легально мог — это всё равно жертва.** Так и у chess.com: учитывается **предложенная** фигура. Пример — 8.O-O-O в партии Рети — Тартаковер (конь e4 под боем, движок считает ход лучшим). Связку «взять нельзя, потому что тогда мат» отдельно **не исключаем**, в отличие от freechess: такие жертвы и есть красота (16.Qb8+ Nxb8 17.Rd8#), а корректность проверяют условия 3–5. + +## 4. Отличный ход (!) — предлагаемое правило + +Все условия: + +1. Сыгран **ход движка №1** (`best`), в позиции больше одного легального хода, `loss ≤ 2` (страховка от шума между поисками). +2. Известна `W2`, и **разрыв** `Wb − W2 ≥ 10`: любой другой ход по нашей же шкале как минимум ошибка (?). +3. **Ход меняет исход**: `класс(Wa) > класс(W2)`, где класс — проигрыш при win% < 33, равенство при 33…67, выигрыш при > 67 (≈ ±2,0). Это и есть «из проигранной в равную» или «из равной в выигранную» по chess.com. Если без хода было бы +3, а с ним +6, ! нет: выигрыш и так был. +4. Исключения, то есть тривиальные «единственные ходы»: + - ход **ставит мат**; + - **взятие обратно** на поле, где соперник только что взял; + - **очевидный выигрыш материала**: ход — взятие с SEE-выигрышем ≥ 2; + - **бегство атакованной фигуры** (не короля): сходившая фигура стояла под боем (SEE ≥ 2 на `from`), а ход не взятие с потерей (`C − T_to ≥ 0`, где `T_to` — угроза на поле назначения). Без этого увод слона из-под пешки в дебюте получал бы ! (Трейбал — Алехин, 7.Bb3). Король под это правило **не попадает**: единственный уход из-под шаха — нормальный кандидат в ! (20.Ke2! в «Бессмертной»). Обратная сторона: 9.Nf5 там же (единственное хорошее поле для атакованного коня) тоже не получает !. +5. Если ход проходит и как !!, ставим **!!** (старшинство !! > !). + +Форсированный ход (единственный легальный) не отмечается ни !, ни !!. Ход из-под шаха может получить ! (условие 1 для ! этого не запрещает), но не !!. + +### 4.1. Одна отметка на комбинацию (рекомендую) + +Без этого правила за выигрышной жертвой идёт цепочка «единственных» ходов: 16.Qb8+!! Nxb8 17.Rd8#, 21.Qxd7+!! Kxd7 22.Bf5+ и т. д. Правило: если **предыдущий ход этой же стороны** прошёл условия !! или ! (до подавления), а **ход соперника между ними** не был ошибкой (потеря < 10 win%, то есть не Mistake/Blunder по нашей шкале), текущая отметка не ставится. Ошибка соперника начинает новую комбинацию: в партии Рети — Тартаковер после 8.O-O-O!! 8...Nxe4?? снова ставится 9.Qd8+!!. + +Побочный эффект: в Каспаров — Топалов остаются 24.Rxd4!! и 30.Rxb7!!, а 25.Re7+ и 26.Qxd4 подавляются. Это вопрос к владельцу (§11). + +### 4.2. Дебют + +Отдельного книжного фильтра **не предлагаю**: дебютной базы в разборе нет, а пешечные гамбиты под !! не попадают по правилу «P ≥ 3». На прогонах ниже (§9) в первых 6 ходах отметок не было. Самая ранняя — 7.Qb3! в «Опере» (в нашем образце PGN там тоже `$1`). + +## 5. Рейтинги + +chess.com смягчает критерии для слабых игроков. Предлагаю **фиксированное правило без рейтингов**: у большинства наших партий (учебные PGN, свои партии, позиции из FEN) рейтинга нет или он несопоставим, а одинаковое правило предсказуемо и тестируемо. Если позже понадобится «щедрый режим», единственный разумный рычаг — `Walt < 90 → < 95` и `D ≥ 2 → D ≥ 1`, но не сейчас. + +## 6. Вторая линия: как получить `W2` и сколько это стоит + +`W2` нужна для !! (условие 5 при сыгранном ходе №1) и для ! (условия 2–3). Сейчас её нет. + +Измерено прототипом (§9) на Stockfish 19, 8 потоков, 1 000 000 узлов (качество «Normal»), 156 позиций из двух обычных партий Алехина: + +| Вариант | Время | Средняя глубина линии №1 | +|---|---|---| +| Сейчас: MultiPV 1 | 14,2 с | 19,7 | +| MultiPV 2 на все позиции, те же узлы | 21,0 с (**+48 %**) | 16,4 (**−3,3 полухода**) | +| Отдельный поиск `go nodes N searchmoves <все ходы, кроме №1>` | 14,5 с на 155 позиций (≈ **1,0×** основного поиска на позицию) | — | + +MultiPV 2 «для всех» **не рекомендую**. Он дороже, а главное, при тех же узлах снижает глубину основной линии, и тогда изменятся уже существующие ?!/?/?? и точность. Чтобы сохранить глубину, узлов нужно примерно вдвое больше. + +**Рекомендация: второй проход только по кандидатам**, после основного, тем же движком и с теми же узлами, `searchmoves` = все легальные ходы, кроме PV[0]. Кандидат — позиция, где: +- сыгран ход №1 (`Ply.best`), легальных ходов > 1, ход не матует; +- и либо ход — жертва по §3.1 (SEE считается без движка), +- либо (для !) это не взятие обратно, не бегство, не взятие с SEE ≥ 2, и `Wb ≥ 33`. + +Если сыгран не ход №1, `Walt = Wb` и второй проход не нужен. + +Доля кандидатов на прогонах: **30 %** полуходов (8 партий Алехина) и **36 %** (сборник классики). Значит, **+30…36 % ко времени разбора**. Оценку времени в диалоге (`review.rs`, «{n} positions, about {time}») нужно умножить примерно на 1,35 или считать по факту. + +Данные и кэш: +- `PosEval` дополнить полем `second: Option` (`eval`, первый ход линии) с `#[serde(default)]`. Старые кэши читаются, но в них нет `second`, и тогда !!/! не ставятся. «Дополнить анализ» запускает только второй проход по кандидатам без `second`. Номер версии кэша поднимать не обязательно. +- В `uci` добавить `searchmoves`: поле в `search(...)` или вариант лимита. Результат приходит обычным `info … multipv 1`. +- Для оценок из `[%eval]` PGN (`meta.nodes == 0`) отметок !!/! нет. В отчёте это стоит честно показывать («без движка — только ошибки»). +- Шум: при Threads > 1 Stockfish недетерминирован. Между двумя одинаковыми прогонами состав ! менялся на 1–3 хода на партию, !! — на 0–1 (§9.3). + +## 7. Запись в PGN + +Как сейчас для ошибок (`write_to_game`): +- `!!` → `$3` (`Nag::BRILLIANT_MOVE`), `!` → `$1` (`Nag::GOOD_MOVE`), только если у хода **нет** оценки хода от автора (`is_move_assessment`). Авторский `$2`/`$4` и т. п. не трогаем. +- `[%eval …]` пишется как раньше. +- Комментарий по образцу ошибок, латиницей: «Brilliant move.» / «Great move.». **Лучшую линию вариантом не добавлять**: ход и так лучший. +- `write_to_game` сейчас возвращает число ошибок. Хорошие ходы нужно либо считать отдельно, либо переименовать результат, чтобы сообщение о записи не врало. +- Повторное открытие: `$1`/`$3` в файле — обычные NAG автора, и показываются как авторские. Отметки разбора без движка не восстанавливаются (§6). + +## 8. Где это затрагивает код (для разработчика, кратко) + +- `report.rs`: `Judgement` получает `Great`, `Brilliant` (или отдельный enum отметок: ошибки и хорошие ходы взаимоисключающие, потому что хорошим ходам нужен `loss ≤ 2 < 5`). В `Ply` добавить данные SEE и признаки кандидата, в `Report::build` — `W2`. `SideStats` дополнить счётчиками `great` и `brilliant`. +- `lib.rs`: `Mark` сейчас означает ошибку (`best`, `best_san`, `refutation`). Для !!/! лучшей линии и стрелок опровержения нет. `errors()` используется для навигации по ошибкам. +- desktop `review.rs`: цвет, символ (`!!`, `!`), названия и счётчики, `write_to_game`; `board.rs` `Badge`. +- `crates/mobile-api/src/review.rs` `MoveJudgement` и Kotlin (`GameScreen`, `ReviewViews`, `Notation`, `Board`). +- SEE и признаки жертвы — чистая функция над `shakmaty::Chess` в `game-review`, тестируется без движка. +- Тесты: SEE на позициях §9.2 (без движка); `Report::build` на синтетических оценках (как `judgements_follow_win_chance_drop`); правило комбинации; запись NAG (`$3`/`$1` не перекрывает авторский NAG). + +## 9. Тестовый оракул и результаты прототипа + +Прототип: `target/analyst-brilliant/` (в .gitignore). `src/main.rs` извлекает признаки и считает SEE на shakmaty 0.30.2, гоняет Stockfish 19 с MultiPV 2 и замером стоимости. `classify.py` применяет правила §3–4. Входные данные — `oracle.pgn`: копия `website/shots/classic-games.pgn` и четыре партии ниже, а также `pgnFilesforExample/Alekhin.pgn` (только чтение, партии 41–48). 1 000 000 узлов, 8 потоков. Повтор: + +``` +target/analyst-brilliant/target/release/analyst-brilliant target/analyst-brilliant/oracle.pgn 1000000 8 20 nocost > oracle2.tsv +python3 target/analyst-brilliant/classify.py oracle2.tsv +``` + +`W2` в прототипе берётся из MultiPV 2. В реализации §6 это будет `searchmoves`, а цифры будут чуть другими: глубже и точнее. + +### 9.1. Партии оракула (основные линии) + +- «Опера», Морфи 1858, «Бессмертная» (Андерсен — Кизерицкий 1851), «Вечнозелёная» (Андерсен — Дюфрен 1852), этюд на оппозицию (FEN `4k3/8/4K3/4P3/8/8/8/8 w - - 0 1`), Рети — Тартаковер 1910 — все из `website/shots/classic-games.pgn`. +- Бирн — Фишер 1956: `1.Nf3 Nf6 2.c4 g6 3.Nc3 Bg7 4.d4 O-O 5.Bf4 d5 6.Qb3 dxc4 7.Qxc4 c6 8.e4 Nbd7 9.Rd1 Nb6 10.Qc5 Bg4 11.Bg5 Na4 12.Qa3 Nxc3 13.bxc3 Nxe4 14.Bxe7 Qb6 15.Bc4 Nxc3 16.Bc5 Rfe8+ 17.Kf1 Be6 18.Bxb6 Bxc4+ …` (полностью — в `oracle.pgn`). +- Каспаров — Топалов 1999: `1.e4 d6 2.d4 Nf6 3.Nc3 g6 4.Be3 Bg7 5.Qd2 c6 6.f3 b5 7.Nge2 Nbd7 8.Bh6 Bxh6 9.Qxh6 Bb7 10.a3 e5 11.O-O-O Qe7 12.Kb1 a6 13.Nc1 O-O-O 14.Nb3 exd4 15.Rxd4 c5 16.Rd1 Nb6 17.g3 Kb8 18.Na5 Ba8 19.Bh3 d5 20.Qf4+ Ka7 21.Rhe1 d4 22.Nd5 Nbxd5 23.exd5 Qd6 24.Rxd4 cxd4 25.Re7+ Kb6 26.Qxd4+ Kxa5 27.b4+ Ka4 28.Qc3 Qxd5 29.Ra7 Bb7 30.Rxb7 Qc4 …`. +- Отрицательные: «Джеромовский гамбит» `1.e4 e5 2.Nf3 Nc6 3.Bc4 Bc5 4.Bxf7+ Kxf7 5.Nxe5+ Nxe5 6.d4 Bxd4 7.Qxd4 d6` (некорректная жертва и desperado) и «Размены» `1.e4 e5 2.Nf3 Nc6 3.d4 exd4 4.Nxd4 Nxd4 5.Qxd4 Qf6 6.Qxf6 Nxf6 7.Nc3 Bb4 8.Bd2 Bxc3 9.Bxc3 Nxe4 10.Bxg7 Rg8 11.Bd4 d5`. + +### 9.2. Результат по правилам §3–4 (второй прогон) + +| Позиция | Ожидание | Получено | Данные (`Wb / W2 / Wa`, D) | +|---|---|---|---| +| Опера 16.Qb8+ | !! | **!!** ✓ | 97,5 / 83,6 / 97,5, D=9 | +| Опера 10.Nxb5 | !! (владелец) или ! | **!** | 86,9 / 62,2 / 86,8, D=1 → не жертва | +| Опера 13.Rxd7 | ! в образце | нет | `Walt` = 90,4 ≥ 90: и так выиграно (на границе) | +| Опера 17.Rd8# | нет (мат, продолжение) | нет ✓ | | +| Бессмертная 11.Rg1 | !! / ! | **!!** ✓ | 44,0 / 41,4 / 45,2; слон b5 оставлен под боем, D=3 | +| Бессмертная 18.Bd6 (`$3` в образце) | — | нет | движок: `loss` 32 (лучше Re1); оценка по движку, как у chess.com | +| Бессмертная 22.Qf6+ | нет (мат и без жертвы) | нет ✓ | `W2` = 97,5 | +| Вечнозелёная 21.Qxd7+ | !! | **!!** ✓ | 97,5 / 2,5 / 97,5, D=8 | +| Вечнозелёная 20.Rxe7+ | ! | **!** ✓ | 84,7 / 10,6 / 87,3 | +| Вечнозелёная 17.Nf6+ / 19.Rad1 (`$1`/`$3` в образце) | — | нет | движок: 17.Nf6+ теряет 37 win%; 19.Rad1 не ход №1 и не жертва по SEE (f3 защищён) | +| Вечнозелёная 18...Rg8 | ? | **!!** | 45,9 / 18,9 / 46,6: единственный ход, конь e7 оставлен под пешкой f6; неожиданно, но по правилу корректно | +| Этюд 1.Kd6 | нет (1.Kf6 тоже выигрывает) | нет ✓ | | +| Этюд 3.e7 | ! (единственный выигрывающий) | **!** ✓ | 97,5 / 50,0 / 97,5 | +| Рети 8.O-O-O | !! (предложен конь e4) | **!!** | 60,0 / 50,0 / 65,3, D=3 | +| Рети 9.Qd8+ | !! | **!!** ✓ | 97,5 / 59,9 / 97,5, D=9 | +| Фишер 11...Na4 | !! | **!!** ✓ | 73,2 / 50,3 / 75,5 | +| Фишер 15...Nxc3 | !/!! | **!!** | 74,5 / 69,2 / 75,9 | +| Фишер 17...Be6 | !! | **!!** ✓ | 74,1 / 44,5 / 75,0, D=6 | +| Каспаров 24.Rxd4 | !! | **!!** ✓ | 47,7 / 41,1 / 47,9, D=3 | +| Каспаров 25.Re7+, 26.Qxd4 | !!/! | подавлены правилом комбинации | без §4.1 были бы !! | +| Каспаров 30.Rxb7 | не ясно | **!!** | 56,7 / 50,0 / 56,0, D=2 | +| Джером 4.Bxf7+ | нет (некорректная жертва) | нет ✓ | `loss` 31 | +| Джером 6...Bxd4 | нет (desperado) | нет ✓ | без правила §3.1 п. 6 было бы !! | +| Размены: вся партия | нет | нет ✓ | 10.Bxg7 (берёт пешку) не ! | + +Итого: все однозначные !! найдены (Qb8+, Qxd7+, Qd8+, Be6, Na4, Rxd4, Rg1). Отрицательные тесты чистые. Спорными остаются 10.Nxb5 (! вместо !!), 13.Rxd7 (граница 90) и цепочки в Каспаров — Топалов. + +### 9.3. Частота и стабильность + +- 8 партий Алехина (637 полуходов, атакующий стиль): 5 × !! и 8 × ! (≈ 0,6 и 1,0 на партию). Примеры: 28...Qxh3!! (Торрес — Алехин), 31...c2!! (Боголюбов — Алехин), ! на единственных выигрывающих ходах в эндшпиле с Рубинштейном. +- Сборник классики: 11 × !! и 13 × ! на 9 партий (подборка из жертв). ! по партиям: «Опера» 7.Qb3, 10.Nxb5; «Бессмертная» 12.h4, 16.Nc3, 20.Ke2; «Вечнозелёная» 20.Rxe7+; этюд 3.e7; Фишер 13...Nxe4; Каспаров — Топалов 20...Ka7, 22...Nbxd5, 25...Kb6, 28...Qxd5, 33.c3. +- В первых 6 ходах отметок нет ни в одной партии. +- Стабильность: два одинаковых прогона (8 потоков, 1 млн узлов) заметно расходятся в отдельных числах. В «Бессмертной» у 20.Ke2 `W2` было 29,5 и 45,4, у 12.h4 `Wb` — 66,2 и 68,4 (по разные стороны границы класса 67). Ход 28.Qc3 у Каспарова в одном прогоне был ходом №1, в другом — нет (`loss` 17). Значит, граничные ! «мигают» между прогонами, а !! устойчивее, потому что требует явной материальной жертвы. Это свойство движкового разбора, и ?!/?/?? устроены так же. + +## 10. Сводка порогов (единицы `report.rs`) + +| Параметр | Значение | ≈ cp | +|---|---|---| +| !! «почти лучший» `loss ≤` | 2,0 win% | — | +| !! «не плохо после» `Wa ≥` | 45 | −54 | +| !! «без хода не выиграно» `Walt <` | 90 | +597 | +| !! дефицит SEE `D ≥` | 2 очка, фигура ≥ 3 | — | +| ! разрыв `Wb − W2 ≥` | 10 win% (= наша Mistake) | — | +| ! классы исхода | < 33 / 33…67 / > 67 | ∓196 | +| ! «шумовая» страховка `loss ≤` | 2,0 | — | +| Комбинация: ошибка соперника рвёт цепочку, если его `loss ≥` | 10 | — | + +## 11. Риски и вопросы владельцу + +1. **10.Nxb5 в «Опере»** (конь за две пешки, D=1): по правилу это !, а не !!. Сделать жертвой и D=1 при отданной фигуре? Тогда добавятся ложные !! вроде 22.Nd5 у Каспарова: там фактически отдана пешка (конь за коня), а SEE даёт D=1. +2. **Правило «одна отметка на комбинацию»** (§4.1): подавлять ли и !!? Сейчас подавляется (Каспаров 25.Re7+). Альтернатива — подавлять только !. +3. **Порог «и так выиграно» 90 %** (+6): 13.Rxd7 в «Опере» (90,4) не проходит, Qb8+ (83,6) проходит. При 85 отпадёт и Qb8+ на части прогонов. +4. **Стоимость**: +30…36 % ко времени разбора на дополнительный проход. Делать его всегда или опцией («искать блестящие ходы»)? Рекомендую всегда: иначе отчёт меняется от галочки. +5. **Оценки из `[%eval]` PGN**: без движка !!/! невозможны (нет лучшего хода и второй линии). Показывать пометку в отчёте? +6. **Шум**: отдельные ! «мигают» между прогонами из-за многопоточности. Кэш делает результат стабильным для одной партии. Для тестов брать синтетические оценки, а не живой движок. +7. **Расхождение с классическими примечаниями**: правила движковые, поэтому исторические «!!» вроде 18.Bd6 в «Бессмертной» и 17.Nf6+ в «Вечнозелёной» не отмечаются: движок находит лучше. chess.com делает так же, но пользователь может удивиться.