diff --git a/CHANGELOG.md b/CHANGELOG.md index f512922..1983a94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Offer Maia a draw (desktop and Android): she accepts when she is clearly worse, or + when the position is about level (at most +0.2 for her) and has kept its character for + her last three moves; after a refusal, again two of her moves later. She judges with + Stockfish, as for her resignation. + ## [1.5.0] — 2026-10-26 - Play against Maia: the large model (79M parameters, 316 MB, downloaded once from the 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 8e4d2bf..2ea9411 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 @@ -524,6 +524,21 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o } } var resigning by remember { mutableStateOf(false) } + val drawDeclined = stringResource(R.string.play_draw_declined) + val drawLater = stringResource(R.string.play_draw_later) + val drawNoEngine = stringResource(R.string.play_draw_no_engine) + // A draw offered (§31.3): Maia answers by her judge's scores of her last turns. + fun offerDraw() { + val r = run ?: return + val j = r.judge + val say = { text: String -> scope.launch { snackbar.currentSnackbarData?.dismiss(); snackbar.showSnackbar(text) } } + when { + j == null -> say(drawNoEngine) + !j.mayOfferDraw() -> say(drawLater) + j.offerDraw() -> finishGame(PlayOver("1/2-1/2", R.string.play_draw, R.string.end_agreement)) + else -> say(drawDeclined) + } + } // The result card closed with ×: until the next game. var resultClosed by remember(run) { mutableStateOf(false) } // A change after the end (a variation, an undo): the card's result may not hold. @@ -578,6 +593,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o r.thinking.value = false r.offer.value = false r.judge?.forget() + r.judge?.forgetScores() r.hopeless = 0u runCatching { e.deleteFrom(from.toUInt()) }.getOrNull()?.let { apply(it) @@ -740,6 +756,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o canForward = canForward, onTakeBack = ::takeBack, onResign = { resigning = true }, + onDraw = ::offerDraw, onAbort = { app.maiaGames.clear() onBack() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt index cf766a9..23dafec 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt @@ -13,6 +13,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.Undo import androidx.compose.material.icons.rounded.Close import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.Handshake import androidx.compose.material.icons.rounded.PlayArrow import androidx.compose.material.icons.rounded.SwapVert import androidx.compose.material3.Button @@ -109,6 +110,7 @@ fun PlayControls( canForward: Boolean, onTakeBack: () -> Unit, onResign: () -> Unit, + onDraw: () -> Unit, onAbort: () -> Unit, onFlip: () -> Unit, onBack: () -> Unit, @@ -121,6 +123,7 @@ fun PlayControls( LabeledButton(Icons.AutoMirrored.Rounded.Undo, stringResource(R.string.play_take_back).removePrefix("↶ "), canTakeBack, Modifier.weight(1f), onTakeBack) if (started) { LabeledButton(Icons.Rounded.Flag, stringResource(R.string.play_resign).removePrefix("⚑ "), true, Modifier.weight(1f), onResign) + LabeledButton(Icons.Rounded.Handshake, stringResource(R.string.play_offer_draw), true, Modifier.weight(1f), onDraw) } else { LabeledButton(Icons.Rounded.Close, stringResource(R.string.play_abort), true, Modifier.weight(1f), onAbort) } @@ -137,10 +140,11 @@ fun PlayControls( @Composable private fun LabeledButton(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, enabled: Boolean, modifier: Modifier, onClick: () -> Unit) { - androidx.compose.material3.TextButton(onClick = onClick, enabled = enabled, modifier = modifier.height(64.dp)) { + androidx.compose.material3.TextButton(onClick = onClick, enabled = enabled, modifier = modifier.height(64.dp), contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 2.dp)) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon(icon, null) - Text(label, style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = TextOverflow.Ellipsis) + // Six buttons in a row: a long word goes to a second line, not cut. + Text(label, style = MaterialTheme.typography.labelSmall, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = androidx.compose.ui.text.style.TextAlign.Center) } } } diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index 0eb5c3f..f231948 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -527,4 +527,9 @@ Fortsetzen Neue beginnen Eine neue Partie ersetzt sie. + Remis + durch Einigung + Maia lehnt das Remis ab + Maia hat abgelehnt; nach zwei ihrer Züge wieder anbieten + Maia beantwortet Remis mit Stockfish: über „Engine“ herunterladen diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 66f1d8b..e4b56db 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -535,4 +535,9 @@ Continuarla Empezar una nueva Una partida nueva la sustituye. + Tablas + por acuerdo + Maia rechaza las tablas + Maia lo rechazó; ofrece de nuevo tras dos de sus jugadas + Maia responde a las tablas con Stockfish: descárgalo con «Motor» diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index dd0a1c8..6949078 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -535,4 +535,9 @@ La continuer En commencer une nouvelle Une nouvelle partie la remplace. + Nulle + par accord mutuel + Maia refuse la nulle + Maia a refusé ; reproposez après deux de ses coups + Maia répond à la nulle avec Stockfish : téléchargez-le avec « Moteur » diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 7148936..acf42b3 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -535,4 +535,9 @@ Continuala Iniziarne una nuova Una nuova partita la sostituisce. + Patta + per accordo + Maia rifiuta la patta + Maia ha rifiutato; riproponi dopo due sue mosse + Maia risponde alla patta con Stockfish: scaricalo con «Motore» diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 716cbbf..67cc7a7 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -528,4 +528,9 @@ Жалғастыру Жаңасын бастау Жаңа ойын оның орнын басады. + Тең + келісім бойынша + Maia тең ойыннан бас тартады + Maia бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз + Maia тең ойынға Stockfish арқылы жауап береді: оны «Қозғалтқыш» батырмасымен жүктеңіз diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 642fe32..0ef5259 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -536,4 +536,9 @@ Continuá-la Começar uma nova Uma nova partida a substitui. + Empate + por acordo + A Maia recusa o empate + A Maia recusou; ofereça de novo após dois lances dela + A Maia responde ao empate com o Stockfish: baixe-o com «Motor» diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 99519ef..eef2e1a 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -543,4 +543,9 @@ Продолжить её Начать новую Новая партия заменит её. + Ничья + по соглашению + Maia отказывается от ничьей + Maia отказалась; снова можно предложить через два её хода + Maia отвечает на ничью с помощью Stockfish: скачайте его кнопкой «Движок» diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index afc1323..5ae4d99 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -526,4 +526,9 @@ Davom ettirish Yangisini boshlash Yangi o‘yin uning o‘rnini oladi. + Durang + kelishuv bo‘yicha + Maia durangdan bosh tortadi + Maia rad etdi; uning ikki yurishidan keyin yana taklif qiling + Maia durangga Stockfish bilan javob beradi: uni «Dvigatel» tugmasi bilan yuklab oling diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index a3855ef..7d167bc 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -531,4 +531,9 @@ Continue it Start a new one A new game replaces it. + Draw + by agreement + Maia declines the draw + Maia declined; offer again after two of her moves + Maia answers a draw offer with Stockfish: download it in the game screen («Engine») diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 4d2a1ee..8477bdd 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -2691,6 +2691,7 @@ impl GameView { s.hopeless = 0; if let Some(j) = s.judge.as_mut() { j.forget(); + j.forget_scores(); } s.opponent.forget(); let user = s.user; @@ -3105,6 +3106,36 @@ impl GameView { { s.resign_asked = true; } + // A draw offered: Maia answers by the judge's scores of her last turns (no + // judge, no answer: the button says why). + if self.play_started() { + let judge = self.play.as_ref().and_then(|s| s.judge.as_ref()); + let may = judge.is_some_and(|j| j.may_offer_draw()); + let hint = match judge { + None => { + tr("Maia answers a draw offer with Stockfish's help: none is installed") + } + Some(_) if !may => tr("Maia declined; offer again after two of her moves"), + Some(_) => tr("Maia accepts when her position is no better and has settled"), + }; + if ui + .add_enabled(may, word(tr("½ Offer a draw"))) + .on_hover_text(hint) + .on_disabled_hover_text(hint) + .clicked() + { + let yes = self + .play + .as_mut() + .and_then(|s| s.judge.as_mut()) + .is_some_and(|j| j.offer_draw()); + if yes { + self.finish_play(crate::play::Ending::DrawAgreed, actions); + } else { + actions.push(GameAction::Toast(tr("Maia declines the draw").into())); + } + } + } }); ui.add_space(4.0); } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 558c3c9..0084d7c 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -10891,6 +10891,72 @@ const ROWS: &[[&str; 9]] = &[ "{elo} dan kuchliroq katta Maia o‘ynaydi: {mb} MB, bir marta yuklab olinadi.", "{elo}-ден күштірек үлкен Maia ойнайды: {mb} МБ, бір рет жүктеледі.", ], + [ + "by agreement", + "по соглашению", + "par accord mutuel", + "durch Einigung", + "por acuerdo", + "per accordo", + "por acordo", + "kelishuv bo‘yicha", + "келісім бойынша", + ], + [ + "½ Offer a draw", + "½ Предложить ничью", + "½ Proposer nulle", + "½ Remis anbieten", + "½ Ofrecer tablas", + "½ Proponi patta", + "½ Propor empate", + "½ Durang taklif qilish", + "½ Тең ойын ұсыну", + ], + [ + "Maia answers a draw offer with Stockfish's help: none is installed", + "Maia отвечает на предложение ничьей с помощью Stockfish, а он не установлен", + "Maia répond à une proposition de nulle avec l’aide de Stockfish, qui n’est pas installé", + "Maia beantwortet Remisangebote mit Hilfe von Stockfish, der nicht installiert ist", + "Maia responde a las tablas con ayuda de Stockfish, que no está instalado", + "Maia risponde alla patta con l’aiuto di Stockfish, che non è installato", + "A Maia responde ao empate com a ajuda do Stockfish, que não está instalado", + "Maia durang taklifiga Stockfish yordamida javob beradi, u o‘rnatilmagan", + "Maia тең ойын ұсынысына Stockfish көмегімен жауап береді, ол орнатылмаған", + ], + [ + "Maia declined; offer again after two of her moves", + "Maia отказалась; снова можно предложить через два её хода", + "Maia a refusé ; reproposez après deux de ses coups", + "Maia hat abgelehnt; nach zwei ihrer Züge wieder anbieten", + "Maia lo rechazó; ofrece de nuevo tras dos de sus jugadas", + "Maia ha rifiutato; riproponi dopo due sue mosse", + "A Maia recusou; ofereça de novo após dois lances dela", + "Maia rad etdi; uning ikki yurishidan keyin yana taklif qiling", + "Maia бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз", + ], + [ + "Maia accepts when her position is no better and has settled", + "Maia соглашается, когда её позиция не лучше и уже не меняется", + "Maia accepte quand sa position n’est pas meilleure et s’est stabilisée", + "Maia nimmt an, wenn ihre Stellung nicht besser ist und sich beruhigt hat", + "Maia acepta cuando su posición no es mejor y se ha estabilizado", + "Maia accetta quando la sua posizione non è migliore e si è stabilizzata", + "A Maia aceita quando a posição dela não é melhor e se estabilizou", + "Maia pozitsiyasi yaxshi bo‘lmasa va o‘zgarmay qolsa, rozi bo‘ladi", + "Maia позициясы жақсы болмаса және өзгермей қалса, келіседі", + ], + [ + "Maia declines the draw", + "Maia отказывается от ничьей", + "Maia refuse la nulle", + "Maia lehnt das Remis ab", + "Maia rechaza las tablas", + "Maia rifiuta la patta", + "A Maia recusa o empate", + "Maia durangdan bosh tortadi", + "Maia тең ойыннан бас тартады", + ], [ "Maia resigned", "Maia сдалась", diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 59fa061..6e83a84 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -1165,6 +1165,7 @@ impl End { Ending::Time { .. } => tr("time is up"), Ending::Resigned { loser } if loser == self.user => "", Ending::Resigned { .. } => tr("Maia resigned"), + Ending::DrawAgreed => tr("by agreement"), } } } diff --git a/crates/mobile-api/src/play.rs b/crates/mobile-api/src/play.rs index 40cf86b..7527e05 100644 --- a/crates/mobile-api/src/play.rs +++ b/crates/mobile-api/src/play.rs @@ -48,7 +48,9 @@ impl GameSession { ::play::Ending::Threefold => GameEnding::Threefold, ::play::Ending::FiftyMoves => GameEnding::FiftyMoves, // No clocks and no resignations here: the app knows those itself. - ::play::Ending::Time { .. } | ::play::Ending::Resigned { .. } => return None, + ::play::Ending::Time { .. } + | ::play::Ending::Resigned { .. } + | ::play::Ending::DrawAgreed => return None, }) } } @@ -143,6 +145,30 @@ impl ResignJudge { .unwrap_or_else(|e| e.into_inner()) .forget(); } + + /// Moves were taken back: the scores of Maia's turns gone are forgotten. + pub fn forget_scores(&self) { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .forget_scores(); + } + + /// A draw may be offered now (not right after a refusal). + pub fn may_offer_draw(&self) -> bool { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .may_offer_draw() + } + + /// The user offers a draw: whether Maia accepts (the shared rule, `play::accepts_draw`). + pub fn offer_draw(&self) -> bool { + self.judge + .lock() + .unwrap_or_else(|e| e.into_inner()) + .offer_draw() + } } /// The weakest and strongest Maia on the phone (the small model's measured range). diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index 2bc0bfa..21c47a4 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -27,6 +27,8 @@ pub enum Ending { Resigned { loser: Color, }, + /// The user offered a draw and Maia accepted. + DrawAgreed, } impl Ending { @@ -43,7 +45,8 @@ impl Ending { Ending::Stalemate | Ending::InsufficientMaterial | Ending::Threefold - | Ending::FiftyMoves => R::Draw, + | Ending::FiftyMoves + | Ending::DrawAgreed => R::Draw, } } @@ -167,6 +170,49 @@ pub fn game_tags( tags } +// ----- a draw offered ------------------------------------------------------------------- + +/// Maia's turns whose scores must agree for a level position to be called settled. +pub const DRAW_STABLE_TURNS: usize = 3; +/// She accepts a draw when she is not better by more than this (centipawns)… +const DRAW_MAX_CP: i32 = 20; +/// …the position settled (her last scores no further apart than this)… +const DRAW_SPREAD_CP: i32 = 30; +/// …or at once when she is worse by this much. +const DRAW_WORSE_CP: i32 = -50; +/// After a refusal, her turns before the next offer counts. +pub const DRAW_AGAIN_AFTER: usize = 2; + +/// Whether Maia accepts a draw, from the scores of her latest turns (oldest first, each +/// for her as the side to move): when clearly worse or mated, at once; when about level +/// (at most +0.2 for her), if the game has kept its character — her last three scores +/// within 0.3 of each other. Never when she mates or is better by more. +pub fn accepts_draw(scores: &[uci::Score]) -> bool { + let Some(&last) = scores.last() else { + return false; + }; + match last { + uci::Score::Mate(n) => return n < 0, + uci::Score::Cp(cp) if cp <= DRAW_WORSE_CP => return true, + uci::Score::Cp(cp) if cp > DRAW_MAX_CP => return false, + uci::Score::Cp(_) => {} + } + if scores.len() < DRAW_STABLE_TURNS { + return false; + } + let recent: Option> = scores[scores.len() - DRAW_STABLE_TURNS..] + .iter() + .map(|s| match s { + uci::Score::Cp(cp) => Some(*cp), + uci::Score::Mate(_) => None, + }) + .collect(); + recent.is_some_and(|v| { + let (lo, hi) = (v.iter().min().unwrap(), v.iter().max().unwrap()); + hi - lo <= DRAW_SPREAD_CP + }) +} + // ----- Maia resigns -------------------------------------------------------------------- /// Nodes the judge searches a position: a tenth of a second or two, enough to see that @@ -194,6 +240,10 @@ pub struct Judge { tx: Sender<(u64, uci::EnginePosition)>, rx: Receiver<(u64, uci::Score)>, generation: u64, + /// The scores of Maia's turns so far (for a draw offered), oldest first. + scores: Vec, + /// A draw refused when this many scores were in. + refused_at: Option, } impl Judge { @@ -272,6 +322,8 @@ impl Judge { tx, rx, generation: 0, + scores: Vec::new(), + refused_at: None, } } @@ -294,8 +346,32 @@ impl Judge { out = Some(s); } } + if let Some(s) = out { + self.scores.push(s); + } out } + + /// Moves were taken back: the scores of positions gone are forgotten. + pub fn forget_scores(&mut self) { + self.scores.clear(); + self.refused_at = None; + } + + /// A draw may be offered (not right after a refusal: two of her turns later). + pub fn may_offer_draw(&self) -> bool { + self.refused_at + .is_none_or(|n| self.scores.len() >= n + DRAW_AGAIN_AFTER) + } + + /// The user offers a draw: whether Maia accepts (by [`accepts_draw`]). + pub fn offer_draw(&mut self) -> bool { + let yes = accepts_draw(&self.scores); + if !yes { + self.refused_at = Some(self.scores.len()); + } + yes + } } #[cfg(test)] @@ -314,6 +390,22 @@ mod tests { assert!(!hopeless(Score::Mate(2))); } + #[test] + fn maia_accepts_a_draw_when_level_and_settled_or_worse() { + use uci::Score::{Cp, Mate}; + // Level and settled: yes; level but just changed: no. + assert!(accepts_draw(&[Cp(10), Cp(-5), Cp(15)])); + assert!(!accepts_draw(&[Cp(-120), Cp(-5), Cp(15)])); + // Too few turns to call it settled. + assert!(!accepts_draw(&[Cp(0), Cp(0)])); + // Better by more than 0.2: no; clearly worse or mated: at once. + assert!(!accepts_draw(&[Cp(25), Cp(25), Cp(25)])); + assert!(accepts_draw(&[Cp(-60)])); + assert!(accepts_draw(&[Mate(-4)])); + assert!(!accepts_draw(&[Mate(3)])); + assert!(!accepts_draw(&[])); + } + #[test] fn games_end_as_the_rules_say() { let line = |moves: &[&str]| { diff --git a/docs/decisions.md b/docs/decisions.md index ff20399..05da302 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -104,6 +104,10 @@ - Логика — в общих крейтах Rust (обе программы на одном коде); в `mobile-api` не копируется код из `apps/desktop`. - По проекту `docs/design/android-play.md` (2026-10-26): «назад» во время партии с Maia откладывает её (карточка «Продолжить» на «Базах»); ходы в чужой партии не сохраняются и не спрашиваются (подсказка «Ваши ходы не сохранены · Вернуть»); ряд «Играть с Maia · Новая партия» вверху «Баз» — как в проекте, не во всю ширину. +## Предложение ничьей (2026-10-26) + +Владелец: человек может предложить ничью движку (компьютер и телефон). Движок соглашается, если ему хуже или он лучше не больше чем на 0,2 и оценка несколько ходов почти не меняется (как у ботов Lichess). Сделано правилом крейта `play` (`accepts_draw`): явно хуже (−0,5 и ниже) или его матуют — сразу; около равенства (≤ +0,2) — если три последних оценки в пределах 0,3; иначе отказ; после отказа снова — через два его хода. Оценивает тот же скрытый Stockfish, что и сдачу; без него кнопка объясняет, что нужен Stockfish. + ## Соперник с характером: Rodent V (2026-10-26) Решение владельца по `docs/research/rodent.md`: