diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e0169c..b92fb82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https game, Save to a database (tags: players, ratings, TimeControl, Termination, [%clk]). Maia is computed in plain Rust, about 0.1 s a move on one core; its weights (21 MB, the authors' own file from huggingface.co) are downloaded once on request. +- Premoves against Maia, as on Lichess: while she thinks, set your next move; it is + played at once after hers when legal. +- Maia resigns: when her position is lost by twelve pawns or more for two of her turns + (judged by Stockfish, unseen), she offers to resign — accept the win, or play to the + end. +- Settings › Board: «Always promote to a queen» (off: the piece is chosen). ## [1.2.0] — 2026-10-25 diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 5f8f237..faa4073 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -1290,9 +1290,18 @@ impl App { self.play_dialog = Some(crate::play::Dialog::new(&self.settings)); return; }; + // The engine judging Maia's resignation: ChessPenguin's Stockfish (its node count + // and the twelve pawns are Stockfish's measures), else the active engine when its + // file is there; none — she plays every game to its end. + let judge = crate::engines::own_stockfish().or_else(|| { + self.settings + .active_engine() + .and_then(|e| e.executable()) + .filter(|p| p.is_file()) + }); self.new_game(); if let Some(g) = self.game.as_mut() { - g.start_play(start, weights, ctx); + g.start_play(start, weights, judge, ctx); } } diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 7ab0bb6..b98a58e 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -1960,6 +1960,7 @@ impl GameView { &mut self, start: crate::play::Start, weights: std::path::PathBuf, + judge: Option, ctx: &egui::Context, ) { use crate::play::{Clock, Opponent, Session}; @@ -2021,6 +2022,10 @@ impl GameView { clock: start.clock.map(Clock::new), opponent: Opponent::start(weights, ctx), resign_asked: false, + judge: judge.map(|p| crate::play::Judge::start(p, ctx)), + hopeless: 0, + resign_offer: None, + play_on: false, }); self.play_start = Some(start); self.ask_maia(); @@ -2051,6 +2056,76 @@ impl GameView { .map_or(Color::White, |p| p.turn()) } + /// Closes Maia's offer to resign: the clocks waited while it was open. + fn close_resign_offer(&mut self) { + let Some(s) = self.play.as_mut() else { return }; + if let Some(since) = s.resign_offer.take() + && let Some(c) = s.clock.as_mut() + { + c.pause(since.elapsed()); + } + } + + /// Maia offers to resign: accept the win, or play to the end (no more offers). + fn resign_offer(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(s) = &self.play else { return }; + let user = s.user; + ui.add_space(4.0); + let mut choice = None; + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 8)) + .corner_radius(4) + .fill(ui.visuals().extreme_bg_color) + .stroke(egui::Stroke::new(1.0, ui.visuals().selection.bg_fill)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(tr("Maia resigns")).strong().size(16.0)); + ui.label( + RichText::new(tr( + "Her position is lost. Accept the win, or play to the end?", + )) + .weak(), + ); + ui.add_space(4.0); + // One under the other, as wide as the card: they fit a narrow panel. + let w = ui.available_width(); + if ui + .add_sized( + [w, 30.0], + egui::Button::new(RichText::new(tr("Accept the win")).strong().size(14.0)) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + { + choice = Some(true); + } + if ui + .add_sized( + [w, 30.0], + egui::Button::new(RichText::new(tr("Play to the end")).size(14.0)), + ) + .on_hover_text(tr("Maia plays on and will not offer again in this game")) + .clicked() + { + choice = Some(false); + } + }); + match choice { + Some(true) => { + self.close_resign_offer(); + self.finish_play(crate::play::Ending::Resigned { loser: !user }, actions); + } + Some(false) => { + self.close_resign_offer(); + if let Some(s) = self.play.as_mut() { + s.play_on = true; + } + self.ask_maia(); + } + None => {} + } + } + /// The side that may set a premove now: the user, while Maia is to move, at the /// current position of the game. fn premove_side(&self) -> Option { @@ -2079,6 +2154,11 @@ impl GameView { /// too, quickly — a whole game without a mouse). fn ask_maia(&mut self) { let turn = self.play_turn(); + let end = self.play_end_node(); + let engine_pos = self.game.engine_history(end).map(|h| match h.start_fen { + None => uci::EnginePosition::startpos(h.moves), + Some(fen) => uci::EnginePosition::fen(fen, h.moves), + }); let positions = self.mainline_positions(); let ply = positions.len() - 1; let only = positions.last().is_some_and(|p| p.legal_moves().len() == 1); @@ -2101,13 +2181,20 @@ impl GameView { .clock .as_ref() .map(|c| (c.left(turn, now), c.control.increment)); + // (Self-play: Maia slower than the user, so that the judge is heard.) let pause = if auto { - std::time::Duration::from_millis(30) + std::time::Duration::from_millis(300) } else { crate::play::pause(clock, ply, only) }; let oppo = s.user_elo.unwrap_or(s.strength); s.opponent.ask(positions, s.strength, oppo, pause); + // Is her position lost? (Unless the user wants to play to the end.) + if !s.play_on + && let (Some(j), Some(ep)) = (s.judge.as_mut(), engine_pos) + { + j.ask(ep); + } } /// A move at the end of the main line by the side to move: the clock, `[%clk]`, the @@ -2134,6 +2221,13 @@ impl GameView { .annotate(id, Vec::new(), vec![crate::play::clk_command(left)]); } } + // Her move made, a verdict still on its way is about a position gone. + if let Some(s) = self.play.as_mut() + && mover != s.user + && let Some(j) = s.judge.as_mut() + { + j.forget(); + } // Maia's move: what the user holds in hand stays there (Lichess); any other // move goes to its position as usual. let user = self.play.as_ref().map(|s| s.user); @@ -2173,7 +2267,33 @@ impl GameView { if self.play_leave.is_some() { return; } + let maia_to_move = self + .play + .as_ref() + .is_some_and(|s| self.play_turn() != s.user); let Some(s) = self.play.as_mut() else { return }; + if s.resign_offer.is_some() { + return; + } + // The judge's verdict on the position Maia is to move in: lost for two of her + // turns in a row, she offers to resign instead of moving (the clocks wait). + if let Some(score) = s.judge.as_mut().and_then(|j| j.answer()) { + s.hopeless = if crate::play::hopeless(score) { + s.hopeless + 1 + } else { + 0 + }; + if maia_to_move + && !s.play_on + && s.hopeless >= crate::play::HOPELESS_TURNS + && s.opponent.thinking + { + s.opponent.forget(); + s.resign_offer = Some(std::time::Instant::now()); + self.scroll_to_cursor = true; + return; + } + } if let Some(err) = s.opponent.failed() { crate::maia_download::forget_broken(); actions.push(GameAction::Toast(trf( @@ -2218,6 +2338,7 @@ impl GameView { /// The game is over: the result, the tags, the strip; the screen becomes an ordinary /// new game. fn finish_play(&mut self, ending: crate::play::Ending, actions: &mut Vec) { + self.close_resign_offer(); let Some(mut s) = self.play.take() else { return; }; @@ -2268,7 +2389,12 @@ impl GameView { /// Takes back the user's last move and Maia's answer to it (no variation is left). fn take_back(&mut self) { self.board.clear_premove(); + self.close_resign_offer(); let Some(s) = self.play.as_mut() else { return }; + s.hopeless = 0; + if let Some(j) = s.judge.as_mut() { + j.forget(); + } s.opponent.forget(); let user = s.user; // The last move of the user on the main line. @@ -2429,8 +2555,13 @@ impl GameView { let Some(choice) = choice else { return }; self.play_leave = None; // The clocks waited while the question was open. + // (Over Maia's offer to resign the clocks wait since the offer: its closing + // gives that time back, all of it.) let waited = since.elapsed(); - if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { + if let Some(s) = self.play.as_mut() + && s.resign_offer.is_none() + && let Some(c) = s.clock.as_mut() + { c.pause(waited); } match choice { @@ -2476,6 +2607,11 @@ impl GameView { egui::Panel::top("play_card_top") .show_separator_line(false) .show(ui, |ui| self.clock_card(ui, top, user)); + if self.play.as_ref().is_some_and(|s| s.resign_offer.is_some()) { + egui::Panel::bottom("play_resign_offer") + .show_separator_line(false) + .show(ui, |ui| self.resign_offer(ui, actions)); + } if self.cursor != self.play_end_node() { egui::Panel::bottom("play_viewing") .show_separator_line(false) @@ -2523,7 +2659,11 @@ impl GameView { // While «The game is on» is open, the clocks stand at the moment it opened. let now = self .play_leave - .map_or_else(std::time::Instant::now, |(_, since)| since); + .map(|(_, since)| since) + .into_iter() + .chain(s.resign_offer) + .min() + .unwrap_or_else(std::time::Instant::now); let turn = self.play_turn(); let active = turn == side; let left = s.clock.as_ref().map(|c| c.left(side, now)); @@ -2561,7 +2701,9 @@ impl GameView { format!("{king} Maia {}", s.strength) }; ui.label(RichText::new(name).size(15.0)); - let state = if side != user && s.opponent.thinking { + let state = if side != user && s.resign_offer.is_some() { + tr("resigns") + } else if side != user && s.opponent.thinking { tr("thinking…") } else if side == user && active { tr("your move") @@ -2646,19 +2788,20 @@ impl GameView { } } else if self.play.as_ref().is_some_and(|s| s.resign_asked) { ui.label(RichText::new(tr("Resign?")).size(14.0)); + // «Yes» and «No» of one size, side by side. if ui - .add( + .add_sized( + [56.0, 28.0], egui::Button::new( RichText::new(tr("Yes")).size(14.0).color(Color32::WHITE), ) - .fill(ui.visuals().error_fg_color) - .min_size(vec2(0.0, 28.0)), + .fill(ui.visuals().error_fg_color), ) .clicked() { let user = self.play.as_ref().map_or(Color::White, |s| s.user); self.finish_play(crate::play::Ending::Resigned { loser: user }, actions); - } else if ui.add(word(tr("No"))).clicked() + } else if ui.add_sized([56.0, 28.0], word(tr("No"))).clicked() && let Some(s) = self.play.as_mut() { s.resign_asked = false; diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 691abfb..54b96b2 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -10924,6 +10924,83 @@ const ROWS: &[[&str; 9]] = &[ "Reytingingizni kiriting: Kuchsizroq · Men kabi · Kuchliroq siz uchun tanlaydi", "Рейтингіңізді енгізіңіз: Әлсіздеу · Мендей · Күштірек өзі таңдайды", ], + [ + "Maia resigned", + "Maia сдалась", + "Maia a abandonné", + "Maia hat aufgegeben", + "Maia se rindió", + "Maia ha abbandonato", + "Maia desistiu", + "Maia taslim bo‘ldi", + "Maia берілді", + ], + [ + "Maia resigns", + "Maia сдаётся", + "Maia abandonne", + "Maia gibt auf", + "Maia se rinde", + "Maia abbandona", + "Maia desiste", + "Maia taslim bo‘lmoqda", + "Maia беріледі", + ], + [ + "Her position is lost. Accept the win, or play to the end?", + "Её позиция проиграна. Принять победу или играть до конца?", + "Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ?", + "Ihre Stellung ist verloren. Den Sieg annehmen oder zu Ende spielen?", + "Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final?", + "La sua posizione è persa. Accettare la vittoria o giocare fino alla fine?", + "A posição dela está perdida. Aceitar a vitória ou jogar até o fim?", + "Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi?", + "Оның позициясы ұтылған. Жеңісті қабылдайсыз ба, әлде соңына дейін ойнайсыз ба?", + ], + [ + "Accept the win", + "Принять победу", + "Accepter la victoire", + "Sieg annehmen", + "Aceptar la victoria", + "Accetta la vittoria", + "Aceitar a vitória", + "G‘alabani qabul qilish", + "Жеңісті қабылдау", + ], + [ + "Play to the end", + "Играть до конца", + "Jouer jusqu’au bout", + "Zu Ende spielen", + "Jugar hasta el final", + "Gioca fino alla fine", + "Jogar até o fim", + "Oxirigacha o‘ynash", + "Соңына дейін ойнау", + ], + [ + "Maia plays on and will not offer again in this game", + "Maia продолжит и в этой партии больше не предложит", + "Maia continue et ne le proposera plus dans cette partie", + "Maia spielt weiter und bietet es in dieser Partie nicht mehr an", + "Maia sigue jugando y no volverá a ofrecerlo en esta partida", + "Maia continua e non lo proporrà più in questa partita", + "Maia continua e não oferecerá de novo nesta partida", + "Maia davom etadi va bu o‘yinda boshqa taklif qilmaydi", + "Maia жалғастырады және бұл партияда енді ұсынбайды", + ], + [ + "resigns", + "сдаётся", + "abandonne", + "gibt auf", + "se rinde", + "abbandona", + "desiste", + "taslim bo‘lmoqda", + "беріледі", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index df6cf0e..1841f53 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -502,6 +502,18 @@ pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Dur #[cfg(test)] mod tests { + #[test] + fn maia_resigns_only_when_hopeless() { + use uci::Score; + assert!(hopeless(Score::Cp(-1200))); + assert!(hopeless(Score::Cp(-3000))); + assert!(!hopeless(Score::Cp(-1199))); + assert!(!hopeless(Score::Cp(900))); + // Mated by force: hopeless; mating: not. + assert!(hopeless(Score::Mate(-3))); + assert!(!hopeless(Score::Mate(2))); + } + use super::*; use chess_core::shakmaty::uci::UciMove; @@ -652,6 +664,14 @@ pub struct Session { pub opponent: Opponent, /// «Resign?» waits for the second click. pub resign_asked: bool, + /// The engine judging the game for Maia's resignation (none without an engine). + pub judge: Option, + /// Maia's turns in a row with her position hopeless. + pub hopeless: u32, + /// Maia offers to resign: since when the offer is open (the clocks wait). + pub resign_offer: Option, + /// «Play to the end»: no more offers in this game. + pub play_on: bool, } /// What the play dialog starts. @@ -664,6 +684,129 @@ pub struct Start { pub clock: Option, } +// ----- Maia resigns -------------------------------------------------------------------- + +/// Nodes the judge searches a position: a tenth of a second or two, enough to see that +/// a position is lost by twelve pawns. +const JUDGE_NODES: u64 = 150_000; + +/// Maia resigns when her position is worse than this (centipawns) or she is mated… +const HOPELESS_CP: i32 = -1200; +/// …on this many of her turns in a row (one tactic in passing is not a lost game). +pub const HOPELESS_TURNS: u32 = 2; + +/// A position lost for the side to move: twelve pawns down, or mated by force. +pub fn hopeless(score: uci::Score) -> bool { + match score { + uci::Score::Cp(cp) => cp <= HOPELESS_CP, + uci::Score::Mate(n) => n < 0, + } +} + +/// The engine (Stockfish, unseen by the user) judging the positions where Maia is to +/// move, in its own thread for the whole game: the newest request is searched, older +/// ones are dropped; an engine that does not start or dies leaves the game without +/// resignations. +pub struct Judge { + tx: Sender<(u64, uci::EnginePosition)>, + rx: Receiver<(u64, uci::Score)>, + generation: u64, +} + +impl Judge { + pub fn start(path: std::path::PathBuf, ctx: &egui::Context) -> Judge { + let (tx, req_rx) = channel::<(u64, uci::EnginePosition)>(); + let (ans_tx, rx) = channel(); + let ctx = ctx.clone(); + let _ = std::thread::Builder::new() + .name("maia-judge".into()) + .spawn(move || { + let Ok(engine) = + uci::Engine::spawn_with(uci::EngineConfig::new(&path), Box::new(|| {})) + else { + return; + }; + let _ = engine.set_threads(1); + let _ = engine.set_hash_mb(16); + let _ = engine.set_multipv(1); + let _ = engine.new_game(); + while let Ok(mut req) = req_rx.recv() { + while let Ok(newer) = req_rx.try_recv() { + req = newer; + } + let (generation, pos) = req; + let id = uci::SearchId(generation); + if engine + .search(pos, id, uci::SearchLimits::Nodes(JUDGE_NODES)) + .is_err() + { + break; + } + let started = Instant::now(); + let mut stopping = false; + let mut last = None; + loop { + if !stopping && started.elapsed() > Duration::from_secs(10) { + let _ = engine.stop(); + stopping = true; + } + match engine.recv_timeout(Duration::from_millis(100)) { + Some(uci::EngineEvent::Info { search_id, info }) if search_id == id => { + if let Some(s) = info.score + && (s.bound == uci::ScoreBound::Exact || last.is_none()) + { + last = Some(s.score); + } + } + Some(uci::EngineEvent::BestMove { search_id, .. }) + if search_id == id => + { + if let Some(score) = last { + if ans_tx.send((generation, score)).is_err() { + engine.quit(); + return; + } + ctx.request_repaint(); + } + break; + } + Some(uci::EngineEvent::Terminated(_)) => return, + _ => {} + } + } + } + engine.quit(); + }); + Judge { + tx, + rx, + generation: 0, + } + } + + /// Judges `pos` (Maia to move); the answer to an older request is dropped. + pub fn ask(&mut self, pos: uci::EnginePosition) { + self.generation += 1; + let _ = self.tx.send((self.generation, pos)); + } + + /// Drops the request in flight: its answer would be about a position gone. + pub fn forget(&mut self) { + self.generation += 1; + } + + /// The score of the position asked last, for the side to move, once it has come. + pub fn answer(&mut self) -> Option { + let mut out = None; + while let Ok((g, s)) = self.rx.try_recv() { + if g == self.generation { + out = Some(s); + } + } + out + } +} + // ----- the dialog --------------------------------------------------------------------- /// «Play against the computer»: name and rating, colour, time, strength. @@ -899,12 +1042,23 @@ impl Dialog { .num_columns(3) .spacing(egui::vec2(10.0, GAP)) .show(ui, |ui| { - ui.spacing_mut().slider_width = W - 120.0 - 28.0 - 20.0; - ui.add_sized([120.0, 18.0], egui::Label::new(tr("Minutes:"))); + ui.spacing_mut().slider_width = W - 90.0 - 28.0 - 20.0; + // Both labels flush left in one column. + let label = |ui: &mut egui::Ui, text: &str| { + ui.allocate_ui_with_layout( + egui::vec2(90.0, 18.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.set_min_width(90.0); + ui.label(text); + }, + ); + }; + label(ui, tr("Minutes:")); ui.add(egui::Slider::new(&mut b, 0..=CUSTOM_BASES.len() - 1).show_value(false)); ui.add_sized([28.0, 18.0], egui::Label::new(RichText::new((CUSTOM_BASES[b] / 60).to_string()).strong())); ui.end_row(); - ui.label(tr("Increment, s:")); + label(ui, tr("Increment, s:")); ui.add(egui::Slider::new(&mut i, 0..=CUSTOM_INCREMENTS.len() - 1).show_value(false)); ui.add_sized([28.0, 18.0], egui::Label::new(RichText::new(CUSTOM_INCREMENTS[i].to_string()).strong())); ui.end_row(); @@ -1017,7 +1171,8 @@ impl End { /// «You won» / «You lost» / «Draw» / «You resigned». pub fn heading(&self) -> &'static str { match self.ending { - Ending::Resigned { .. } => tr("You resigned"), + Ending::Resigned { loser } if loser == self.user => tr("You resigned"), + Ending::Resigned { .. } => tr("You won"), e => match e.result() { chess_core::GameResult::Draw => tr("Draw"), r if r == Ending::Checkmate { winner: self.user }.result() => tr("You won"), @@ -1038,7 +1193,8 @@ impl End { } Ending::Time { draw: true, .. } => tr("Maia's time is up, but you cannot checkmate"), Ending::Time { .. } => tr("time is up"), - Ending::Resigned { .. } => "", + Ending::Resigned { loser } if loser == self.user => "", + Ending::Resigned { .. } => tr("Maia resigned"), } } }