From 9cd28b9039472e9cdb3c4622d8faa470f6169e88 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sun, 25 Oct 2026 04:10:02 +0300 Subject: [PATCH] Play against Maia: dialog, clocks, game screen, result strip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «⚔ Play» (Ctrl+G) opens «Play against the computer»: name and rating (optional), strength 600–2600 (or weaker/as me/stronger), colour, Lichess time controls, custom, no clock. The game screen in play mode: clock cards above and below the notation (read-only), take back, resign (abort before the first moves); no engine, analysis or editing. Maia answers in a background thread with a human-like pause bounded so she never loses on time; stale answers are dropped. Endings: mate, stalemate, no material, threefold, fifty moves, time (draw when the other side cannot mate), resignation; then the result strip (Analyse, Rematch, New game, Save to a database) and an ordinary game with the tags of a played game and [%clk]. Leaving during a game asks (resign and add / resign and leave / keep playing), the clocks wait meanwhile. maia reads the published PyTorch checkpoint directly (zip + a small pickle reader that refuses everything but tensors); maia_download fetches it on request (pinned revision, SHA-256). Dev hooks CP_PLAY, CP_PLAY_AUTO, CP_MAIA. Russian texts; the other languages follow. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 + Cargo.lock | 1 + apps/desktop/Cargo.toml | 1 + apps/desktop/src/app.rs | 122 +++- apps/desktop/src/game_view.rs | 755 ++++++++++++++++++++++- apps/desktop/src/library.rs | 23 +- apps/desktop/src/maia_download.rs | 128 ++++ apps/desktop/src/main.rs | 2 + apps/desktop/src/notation.rs | 5 + apps/desktop/src/play.rs | 962 ++++++++++++++++++++++++++++++ apps/desktop/src/settings.rs | 6 + crates/maia/src/checkpoint.rs | 321 ++++++++++ crates/maia/src/lib.rs | 9 +- crates/maia/src/weights.rs | 81 +-- crates/maia/tests/reference.rs | 2 +- docs/design/play-mode.md | 493 +++++++++++++++ docs/dev/desktop.md | 2 +- scripts/maia-convert.py | 65 -- 18 files changed, 2843 insertions(+), 151 deletions(-) create mode 100644 apps/desktop/src/maia_download.rs create mode 100644 apps/desktop/src/play.rs create mode 100644 crates/maia/src/checkpoint.rs create mode 100644 docs/design/play-mode.md delete mode 100755 scripts/maia-convert.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 19c83a7..8a27f20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Play against the computer (desktop): «⚔ Play» in the library (Ctrl+G) starts a game + against Maia — a neural network (Maia-3, CSSLab, University of Toronto) that plays like + a human of the chosen rating, 600–2600, mistakes included. Your name and rating + (optional; «Weaker · As me · Stronger» choose the strength relative to it), colour, + Lichess time controls (bullet to classical, custom, no clock). During the game: the + board, the notation, both clocks (time runs after each side's first move, increment + after the move, low time in red), take back, resign; no engine or analysis. Maia + thinks like a human — a pause that depends on her clock — and never loses on time. The + game ends by mate, stalemate, no material, threefold repetition, fifty moves, time or + resignation; then it is an ordinary game with the result strip: Analyse, Rematch, New + 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. + ## [1.2.0] — 2026-10-25 - Your own comments in a game (desktop): Enter on a move (or the right-click menu, a diff --git a/Cargo.lock b/Cargo.lock index 4b161ff..91ba6d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -808,6 +808,7 @@ dependencies = [ "getrandom 0.3.4", "image", "log", + "maia", "online-games", "releases", "rfd", diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index c03c4cb..b478727 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -11,6 +11,7 @@ license.workspace = true [dependencies] chess-core.workspace = true +maia.workspace = true game-review.workspace = true chess-import.workspace = true shakmaty.workspace = true diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 314bf1c..38b387a 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -166,6 +166,12 @@ pub fn overlay_open_besides(ctx: &egui::Context, own: &[egui::Id]) -> bool { }) } +/// What starts once the played game is closed. +enum PlayNext { + Rematch(crate::play::Start), + Dialog, +} + #[derive(Clone, Copy, PartialEq)] pub enum CloseIntent { BackToLibrary, @@ -186,6 +192,11 @@ pub struct App { settings_ui: SettingsWindow, toast: Option, own: Own, + /// The play dialog («Play against the computer»). + play_dialog: Option, + /// After the current game is closed: a new game against Maia (a rematch, or the + /// dialog for a new one). + play_next: Option, tx: Sender, rx: Receiver, confirm_close: Option, @@ -240,6 +251,8 @@ struct DebugStartup { /// (own_db.rs) after a short delay; `delete` and `chooser` without a game: the /// record `CP_OPEN` (default 0) of the first database. own: Option, + /// `CP_PLAY`: a game against Maia at start (see `debug_screenshot`). + play: Option, keys: std::collections::VecDeque<(Modifiers, Key)>, next_key: f64, /// `CP_TYPE=`: typed into the field that has the keyboard, 2.5 s after start. @@ -261,6 +274,7 @@ impl DebugStartup { screenshot_requested: false, open_settings: false, own: std::env::var("CP_OWN").ok(), + play: std::env::var("CP_PLAY").ok(), keys: std::env::var("CP_KEYS") .unwrap_or_default() .split_whitespace() @@ -343,6 +357,8 @@ impl App { settings_ui: SettingsWindow::new(), toast: None, own: Own::default(), + play_dialog: None, + play_next: None, tx, rx, confirm_close: None, @@ -432,6 +448,44 @@ impl App { self.debug.open_settings = false; self.settings_ui.open = true; } + // `CP_PLAY=white|black[,5+3|none][,1500]`: a game against Maia starts at once; + // `CP_PLAY=dialog`: the play dialog. + if let Some(spec) = self.debug.play.take() { + if spec == "dialog" { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)); + } else { + let mut parts = spec.split(','); + let user = if parts.next() == Some("black") { + chess_core::shakmaty::Color::Black + } else { + chess_core::shakmaty::Color::White + }; + let clock = match parts.next() { + Some("none") => None, + Some(tc) => tc.split_once('+').and_then(|(m, i)| { + Some(crate::play::TimeControl { + base: m.parse::().ok()? * 60, + increment: i.parse().ok()?, + }) + }), + None => Some(crate::play::TimeControl { + base: 300, + increment: 3, + }), + }; + let strength = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1500); + self.start_play( + ctx, + crate::play::Start { + user, + strength, + user_elo: self.settings.rating, + user_name: self.settings.your_name.clone(), + clock, + }, + ); + } + } if self.debug.own.is_some() && ctx.input(|i| i.time) > 1.5 { let what = self.debug.own.take().unwrap_or_default(); // `CP_PASTE=`: this game is open first (a game from no database). @@ -1230,6 +1284,18 @@ impl App { self.game = Some(GameView::new(g, None, Vec::new())); } + /// A new game against Maia (the weights are there: the dialog saw to it). + fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) { + let Some(weights) = crate::maia_download::installed() else { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)); + return; + }; + self.new_game(); + if let Some(g) = self.game.as_mut() { + g.start_play(start, weights, ctx); + } + } + /// The game's data for editing (F2, the title, the menu). fn edit_game_data(&mut self) { let Some(g) = &self.game else { return }; @@ -1682,9 +1748,11 @@ impl App { } fn request_close(&mut self, ctx: &egui::Context, intent: CloseIntent) { - // A comment being written goes into the game first. + // A comment being written goes into the game first; a game against Maia still + // being played ends (resigned, or dropped before the first moves). if let Some(g) = self.game.as_mut() { g.commit_editor(); + g.resign_if_playing(); } if self.game.as_ref().is_some_and(|g| g.game.is_modified()) { self.confirm_close = Some(intent); @@ -1722,6 +1790,13 @@ impl App { { self.library.reveal(&src.path, src.index); } + match self.play_next.take() { + Some(PlayNext::Rematch(s)) => self.start_play(ctx, s), + Some(PlayNext::Dialog) => { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)) + } + None => {} + } if let Some((path, start, line, flipped)) = self.find_after_close.take() { self.library.show_position(&path, start, line, flipped, ctx); } @@ -1972,6 +2047,7 @@ impl App { Some(2) => { self.confirm_close = None; self.find_after_close = None; + self.play_next = None; // A restart asked for waits for no later quit. self.restart_to = None; } @@ -2003,6 +2079,7 @@ impl eframe::App for App { && let Some(g) = self.game.as_mut() { g.commit_editor(); + g.resign_if_playing(); } // Quitting with a modified game left for another (reference tab): show that one, // so the question "save?" is about the game that has the changes. @@ -2054,6 +2131,9 @@ impl eframe::App for App { self.own.then_close = None; self.new_base_dialog(own_db::AfterCreate::Shelf); } + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) && self.game.is_none() { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)); + } if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() { self.new_game(); } @@ -2134,6 +2214,34 @@ impl eframe::App for App { self.toast(&ctx, msg); } GameAction::Save => self.save_current(&ctx, None), + GameAction::Rematch => { + let next = self + .game + .as_ref() + .and_then(|g| g.play_end.clone()) + .map(|e| { + let mut s = e.start; + s.user = match self.settings.play.color { + crate::play::ColorChoice::Random => { + if crate::play::random_unit() < 0.5 { + chess_core::shakmaty::Color::White + } else { + chess_core::shakmaty::Color::Black + } + } + _ => !s.user, + }; + s + }); + if let Some(s) = next { + self.play_next = Some(PlayNext::Rematch(s)); + self.request_close(&ctx, CloseIntent::BackToLibrary); + } + } + GameAction::PlayAgain => { + self.play_next = Some(PlayNext::Dialog); + self.request_close(&ctx, CloseIntent::BackToLibrary); + } GameAction::AddToDatabase => { if let Some(g) = self.game.as_mut() { g.commit_editor(); @@ -2202,6 +2310,9 @@ impl eframe::App for App { } LibraryAction::OpenPgn(text) => self.open_pgn_text(&ctx, text, true), LibraryAction::NewGame => self.new_game(), + LibraryAction::Play => { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)) + } LibraryAction::NewGameIn(path) => { self.new_game(); if let Some(g) = self.game.as_mut() { @@ -2369,6 +2480,15 @@ impl eframe::App for App { self.confirm_dialog(&ctx); self.own_dialogs(&ctx); + if let Some(d) = self.play_dialog.as_mut() + && let Some(out) = d.show(&ctx, &mut self.settings) + { + self.play_dialog = None; + if let crate::play::DialogOutcome::Play(start) = out { + self.settings_dirty = true; + self.start_play(&ctx, start); + } + } // Ctrl+Z on the library while the deleted game can still come back. if self.game.is_none() && self.own.undo.is_some() diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 9ed08dc..71487c0 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -62,6 +62,15 @@ pub struct GameView { scroll_to_cursor: bool, /// The comment being written (user-comments.md). editor: Option, + /// A game against Maia in progress (play-mode.md). + pub play: Option, + /// The game just played: the result strip. + pub play_end: Option, + /// What the play started with (for the end, a rematch). + play_start: Option, + /// «The game is on» asked (leaving during a game); the clocks wait meanwhile. + /// `true`: back to the previous game, not to the library. + play_leave: Option<(bool, std::time::Instant)>, show_diagnostics: bool, engine_settings_open: bool, review: Review, @@ -92,6 +101,10 @@ pub enum GameAction { CopyText(String, &'static str), /// Ctrl+S: into the game's own database, else "Add to database…". Save, + /// After a game against Maia: the same again with colours swapped. + Rematch, + /// After a game against Maia: the play dialog. + PlayAgain, /// Ctrl+Shift+S: choose the database to add the game to. AddToDatabase, /// F2: players, event, date, result… @@ -138,6 +151,10 @@ impl GameView { preview: None, scroll_to_cursor: true, editor: None, + play: None, + play_end: None, + play_start: None, + play_leave: None, show_diagnostics: false, engine_settings_open: false, review, @@ -241,6 +258,10 @@ impl GameView { /// A move made on the board or picked in the reference tab: goes to it if the /// game has it, else adds it (undoable). fn play_move(&mut self, m: Move, actions: &mut Vec) { + if self.play.is_some() { + self.user_move(m, actions); + return; + } match self.game.add_move(self.cursor, m) { Ok(id) => { self.goto(id); @@ -601,7 +622,8 @@ impl GameView { { self.review.note_live_speed(analysis.nps, e.threads); } - if input_enabled && !self.review.dialog_open { + self.play_tick(ui.ctx(), &mut actions); + if input_enabled && !self.review.dialog_open && self.play_leave.is_none() { self.editor_keys(ui, &mut actions); self.keyboard(ui, &mut actions); } @@ -685,6 +707,10 @@ impl GameView { None => {} } + // Leaving during a game asks first; the question itself. + self.guard_leaving(&mut actions); + self.leave_question(ui.ctx(), &mut actions); + if self.show_diagnostics { let mut open = true; egui::Window::new(tr("PGN compatibility")) @@ -1177,7 +1203,7 @@ impl GameView { } else { None }, - interactive: self.preview.is_none(), + interactive: self.preview.is_none() && self.user_may_move(), show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, @@ -1188,6 +1214,7 @@ impl GameView { } if let Some(drawn) = self.board.take_shape() && self.preview.is_none() + && self.play.is_none() { self.apply_shape(drawn); } @@ -1219,6 +1246,13 @@ impl GameView { hub: &mut crate::translate_ui::Hub, actions: &mut Vec, ) { + if self.play.is_some() { + self.play_side(ui, settings, analysis, reference, hub, actions); + return; + } + if self.play_end.is_some() { + egui::Panel::top("play_result").show(ui, |ui| self.result_strip(ui, actions)); + } egui::Panel::bottom("game_toolbar").show(ui, |ui| self.toolbar(ui, actions)); egui::Panel::top("engine_panel") .show(ui, |ui| self.engine_panel(ui, settings, analysis, actions)); @@ -1313,6 +1347,7 @@ impl GameView { .map(|p| (p.base, p.san.as_slice(), p.shown)), translations: self.translation.shown(), editor: self.editor.as_mut(), + read_only: self.play.is_some(), } .show(ui); if let Some(id) = resp.clicked { @@ -1895,6 +1930,718 @@ impl GameView { } } + // ----- playing against Maia (docs/design/play-mode.md) ----------------------------- + + /// Starts a game against Maia in this (new, empty) game. + pub fn start_play( + &mut self, + start: crate::play::Start, + weights: std::path::PathBuf, + ctx: &egui::Context, + ) { + use crate::play::{Clock, Opponent, Session}; + let maia = format!("Maia {}", start.strength); + let you = if start.user_name.is_empty() { + "?".to_owned() + } else { + start.user_name.clone() + }; + let (white, black) = match start.user { + Color::White => (you, maia), + Color::Black => (maia, you), + }; + let event = match start.clock { + Some(tc) => trf( + "Game vs computer, {speed}", + &[("speed", &tc.speed().name().to_lowercase())], + ), + None => tr("Game vs computer").to_owned(), + }; + let g = &mut self.game; + g.set_tag("Event", &event); + g.set_tag("Site", "ChessPenguin"); + g.set_tag("White", &white); + g.set_tag("Black", &black); + let (we, be) = match start.user { + Color::White => (start.user_elo, Some(start.strength)), + Color::Black => (Some(start.strength), start.user_elo), + }; + if let Some(e) = we { + g.set_tag("WhiteElo", &e.to_string()); + } + if let Some(e) = be { + g.set_tag("BlackElo", &e.to_string()); + } + let (wt, bt) = match start.user { + Color::White => ("human", "program"), + Color::Black => ("program", "human"), + }; + g.set_tag("WhiteType", wt); + g.set_tag("BlackType", bt); + g.set_tag( + "TimeControl", + &start.clock.map_or_else(|| "-".to_owned(), |tc| tc.pgn()), + ); + g.mark_saved(); + self.flipped = start.user == Color::Black; + self.play_end = None; + self.play = Some(Session { + user: start.user, + strength: start.strength, + user_elo: start.user_elo, + clock: start.clock.map(Clock::new), + opponent: Opponent::start(weights, ctx), + warned: false, + resign_asked: false, + }); + self.play_start = Some(start); + self.ask_maia(); + } + + /// The positions of the main line, from the start to its end. + fn mainline_positions(&self) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.game.position(NodeId::ROOT) { + out.push(p.clone()); + } + for id in self.game.mainline() { + if let Some(p) = self.game.position(id) { + out.push(p.clone()); + } + } + out + } + + fn play_end_node(&self) -> NodeId { + self.game.line_end(NodeId::ROOT) + } + + /// The side to move at the end of the main line. + fn play_turn(&self) -> Color { + self.game + .position(self.play_end_node()) + .map_or(Color::White, |p| p.turn()) + } + + /// The user may move: their turn, at the current position, Maia not thinking. + fn user_may_move(&self) -> bool { + match &self.play { + None => true, + Some(s) => { + self.play_leave.is_none() + && self.play_turn() == s.user + && self.cursor == self.play_end_node() + && !s.opponent.thinking + } + } + } + + /// Asks Maia for a move when it is her turn (dev hook `CP_PLAY_AUTO`: for the user + /// too, quickly — a whole game without a mouse). + fn ask_maia(&mut self) { + let turn = self.play_turn(); + let positions = self.mainline_positions(); + let ply = positions.len() - 1; + let only = positions.last().is_some_and(|p| p.legal_moves().len() == 1); + let auto = std::env::var_os("CP_PLAY_AUTO").is_some(); + let Some(s) = self.play.as_mut() else { return }; + if turn == s.user { + if auto { + let elo = s.user_elo.unwrap_or(s.strength); + s.opponent.ask( + positions, + elo, + s.strength, + std::time::Duration::from_millis(30), + ); + } + return; + } + let now = std::time::Instant::now(); + let clock = s + .clock + .as_ref() + .map(|c| (c.left(turn, now), c.control.increment)); + let pause = if auto { + std::time::Duration::from_millis(30) + } else { + crate::play::pause(clock, ply, only) + }; + let oppo = s.user_elo.unwrap_or(s.strength); + s.opponent.ask(positions, s.strength, oppo, pause); + } + + /// A move at the end of the main line by the side to move: the clock, `[%clk]`, the + /// sound, the end of the game, Maia's turn. + fn play_add(&mut self, m: Move, actions: &mut Vec) { + let end = self.play_end_node(); + let mover = self.play_turn(); + let Ok(id) = self.game.add_move(end, m) else { + return; + }; + let now = std::time::Instant::now(); + if let Some(s) = self.play.as_mut() { + s.resign_asked = false; + if let Some(c) = s.clock.as_mut() { + c.moved(mover, now); + let left = c.left(mover, now); + let _ = self + .game + .annotate(id, Vec::new(), vec![crate::play::clk_command(left)]); + } + } + // The moves of a game played are not undone as edits (the take-back is). + self.goto(id); + if let Some(snd) = self.sound_for(id) { + actions.push(GameAction::Sound(snd)); + } + if let Some(e) = crate::play::ending(&self.mainline_positions()) { + self.finish_play(e, actions); + } else { + self.ask_maia(); + } + } + + fn user_move(&mut self, m: Move, actions: &mut Vec) { + if !self.user_may_move() { + // A move in a past position: back to the game. + let end = self.play_end_node(); + self.goto(end); + return; + } + self.play_add(m, actions); + } + + /// The clock and Maia's answers, each frame. + fn play_tick(&mut self, ctx: &egui::Context, actions: &mut Vec) { + if self.play_leave.is_some() { + return; + } + let Some(s) = self.play.as_mut() else { return }; + if let Some(err) = s.opponent.failed() { + actions.push(GameAction::Toast(trf( + "Maia did not start: {e}", + &[("e", &err)], + ))); + self.play = None; + self.game.mark_saved(); + actions.push(GameAction::Back); + return; + } + if let Some(m) = s.opponent.answer() { + self.play_add(m, actions); + } + let now = std::time::Instant::now(); + let end_pos = self.game.position(self.play_end_node()).cloned(); + let Some(s) = self.play.as_mut() else { return }; + if let Some(c) = &s.clock + && let Some(side) = c.running() + { + let left = c.left(side, now); + if left.is_zero() { + // Time is up; a draw when the other side cannot mate (FIDE 6.9). + let draw = end_pos.is_some_and(|p| p.has_insufficient_material(!side)); + self.finish_play(crate::play::Ending::Time { loser: side, draw }, actions); + return; + } + if side == s.user && left <= c.low() { + s.warned = true; + } + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + /// 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) { + let Some(mut s) = self.play.take() else { + return; + }; + s.opponent.forget(); + let now = std::time::Instant::now(); + let left = s.clock.as_mut().map(|c| { + c.stop(now); + (c.left(s.user, now), c.left(!s.user, now)) + }); + self.game.set_result(ending.result()); + self.game.set_tag("Termination", ending.termination()); + let end = self.play_end_node(); + self.goto(end); + if matches!(ending, crate::play::Ending::Checkmate { .. }) { + actions.push(GameAction::Sound(Sound::Checkmate)); + } + if let Some(start) = self.play_start.clone() { + self.play_end = Some(crate::play::End { + ending, + user: s.user, + start, + left, + }); + } + } + + /// Before both sides have moved there is nothing to lose: the game is dropped. + fn play_started(&self) -> bool { + self.game.mainline().len() >= 2 + } + + /// Resigns the game in progress (leaving it, closing the program); before the first + /// moves it is dropped instead. The game stays as played. + pub fn resign_if_playing(&mut self) { + let Some(s) = &self.play else { return }; + if self.play_started() { + let user = s.user; + let mut sink = Vec::new(); + self.finish_play(crate::play::Ending::Resigned { loser: user }, &mut sink); + } else { + self.play = None; + self.game.mark_saved(); + } + } + + /// Takes back the user's last move and Maia's answer to it (no variation is left). + fn take_back(&mut self) { + let Some(s) = self.play.as_mut() else { return }; + s.opponent.forget(); + let user = s.user; + // The last move of the user on the main line. + let line = self.game.mainline(); + let last = line.iter().rev().find(|&&id| { + self.game + .parent(id) + .and_then(|p| self.game.position(p)) + .is_some_and(|p| p.turn() == user) + }); + if let Some(&id) = last + && let Ok(parent) = self.game.delete_variation(id) + { + self.goto(parent); + } + self.ask_maia(); + } + + /// Keys during a game: looking through it, flipping, the take-back; Esc asks. + fn play_keys(&mut self, ui: &Ui, actions: &mut Vec) { + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let mut cmds = Vec::new(); + ui.input_mut(|i| { + if i.consume_shortcut(&ctrl(Key::Z)) { + cmds.push("takeback"); + } + if i.consume_shortcut(&ctrl(Key::W)) { + cmds.push("leave"); + } + if i.modifiers.is_none() { + for (key, cmd) in [ + (Key::ArrowLeft, "back1"), + (Key::ArrowRight, "fwd1"), + (Key::ArrowUp, "end"), + (Key::ArrowDown, "home"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::L, "engine"), + (Key::Escape, "leave"), + ] { + if i.key_pressed(key) { + cmds.push(cmd); + } + } + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { + cmds.push("engine"); + } + }); + for cmd in cmds { + match cmd { + "takeback" => self.take_back(), + "back1" => self.step_back(), + "fwd1" => self.step_forward(actions), + "home" => self.goto(NodeId::ROOT), + "end" => { + let end = self.play_end_node(); + self.goto(end); + } + "flip" => self.flipped = !self.flipped, + "engine" => actions.push(GameAction::Toast( + tr("The engine is off during the game — analyse after it ends").to_owned(), + )), + "leave" => { + if let Some(s) = self.play.as_mut() + && s.resign_asked + { + s.resign_asked = false; + } else { + ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)); + actions.push(GameAction::Back); + } + } + _ => {} + } + } + } + + /// Leaving during a game asks first (play-mode.md §6); before the first moves of + /// both sides the game is just dropped. + fn guard_leaving(&mut self, actions: &mut Vec) { + if self.play.is_none() { + return; + } + let leaving = actions + .iter() + .position(|a| matches!(a, GameAction::Back | GameAction::ReturnToPrevious)); + if let Some(k) = leaving { + let a = actions.remove(k); + if self.play_started() { + let previous = matches!(a, GameAction::ReturnToPrevious); + self.play_leave = Some((previous, std::time::Instant::now())); + } else { + if let Some(s) = self.play.as_mut() { + s.opponent.forget(); + } + self.play = None; + self.game.mark_saved(); + actions.push(a); + } + } + } + + /// «The game is on»: resign and add, resign and leave, keep playing. + fn leave_question(&mut self, ctx: &egui::Context, actions: &mut Vec) { + let Some((previous, since)) = self.play_leave else { + return; + }; + let action = if previous { + GameAction::ReturnToPrevious + } else { + GameAction::Back + }; + let mut choice = None; + egui::Modal::new(egui::Id::new("play_leave")).show(ctx, |ui| { + ui.set_width(460.0); + ui.heading(tr("The game is on")); + ui.label(tr("If you leave, the game ends with your resignation.")); + ui.add_space(8.0); + ui.horizontal_wrapped(|ui| { + if ui.button(tr("Resign and add to a database…")).clicked() { + choice = Some(0); + } + if ui.button(tr("Resign and leave")).clicked() { + choice = Some(1); + } + if crate::widgets::primary(ui, tr("Keep playing")).clicked() { + choice = Some(2); + } + }); + }); + if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + choice = Some(2); + } + let Some(choice) = choice else { return }; + self.play_leave = None; + // The clocks waited while the question was open. + let waited = since.elapsed(); + if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { + c.pause(waited); + } + match choice { + 0 => { + self.resign_if_playing(); + actions.push(GameAction::Save); + } + 1 => { + self.resign_if_playing(); + actions.push(action); + } + _ => {} + } + } + + /// The side panel during a game: the opponent's clock, the notation, the user's + /// clock, the game's buttons. + fn play_side( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + analysis: &mut Analysis, + reference: &mut crate::reference::Reference, + hub: &mut crate::translate_ui::Hub, + actions: &mut Vec, + ) { + let _ = (settings, analysis, reference, hub); + let Some(s) = &self.play else { return }; + let user = s.user; + // The side whose pieces are at the top of the board is at the top. + let top = if self.flipped { + Color::White + } else { + Color::Black + }; + egui::Panel::bottom("play_toolbar").show(ui, |ui| self.play_toolbar(ui, actions)); + egui::Panel::bottom("play_card_bottom") + .show_separator_line(false) + .show(ui, |ui| self.clock_card(ui, !top, user)); + egui::Panel::top("play_card_top") + .show_separator_line(false) + .show(ui, |ui| self.clock_card(ui, top, user)); + egui::CentralPanel::default().show(ui, |ui| { + egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + let resp = Notation { + game: &self.game, + cursor: self.cursor, + scroll_to_cursor: self.scroll_to_cursor, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + } + .show(ui); + if let Some(id) = resp.clicked { + self.goto(id); + } + self.scroll_to_cursor = false; + }); + if self.cursor != self.play_end_node() + && ui + .link( + RichText::new(tr("Viewing an earlier position · back to the game — End")) + .weak(), + ) + .clicked() + { + let end = self.play_end_node(); + self.goto(end); + } + }); + } + + /// A player's card: name, rating, the clock and what is going on. + fn clock_card(&self, ui: &mut Ui, side: Color, user: Color) { + let Some(s) = &self.play else { return }; + let now = 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)); + let low = s + .clock + .as_ref() + .zip(left) + .is_some_and(|(c, l)| c.running() == Some(side) && l <= c.low()); + let sel = ui.visuals().selection; + let mut frame = egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )); + if active { + frame = frame.fill(sel.bg_fill.gamma_multiply(0.35)); + } + if low { + frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color)); + } + ui.add_space(4.0); + frame.show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.vertical(|ui| { + let king = if side == Color::White { "♔" } else { "♚" }; + let name = if side == user { + match s.user_elo { + Some(r) => format!("{king} {} · {r}", tr("You")), + None => format!("{king} {}", tr("You")), + } + } else { + format!("{king} Maia {}", s.strength) + }; + ui.label(RichText::new(name).size(15.0)); + let state = if side != user && s.opponent.thinking { + tr("thinking…") + } else if side == user && active { + tr("your move") + } else if side != user { + tr("waiting") + } else { + "" + }; + ui.label(RichText::new(state).weak().size(13.0)); + }); + if let Some(left) = left { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut t = RichText::new(crate::play::clock_text(left)) + .monospace() + .size(28.0); + if low { + t = t.color(ui.visuals().error_fg_color); + } else if active { + t = t.strong(); + } else { + t = t.weak(); + } + ui.label(t); + }); + } + }); + }); + ui.add_space(4.0); + } + + /// ⏮ ◀ ▶ ⏭ · 🔃 · ↶ Take back · 🏳 Resign (✕ Abort before the first moves). + fn play_toolbar(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + let big = |s: &str| RichText::new(s).size(18.0); + if ui.button(big("⏮")).clicked() { + self.goto(NodeId::ROOT); + } + if ui.button(big("◀")).clicked() { + self.step_back(); + } + if ui.button(big("▶")).clicked() { + self.step_forward(actions); + } + if ui.button(big("⏭")).clicked() { + let end = self.play_end_node(); + self.goto(end); + } + ui.separator(); + if ui + .button(big("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + ui.separator(); + let user = self.play.as_ref().map_or(Color::White, |s| s.user); + let user_moved = self.game.mainline().iter().any(|&id| { + self.game + .parent(id) + .and_then(|p| self.game.position(p)) + .is_some_and(|p| p.turn() == user) + }); + if ui + .add_enabled(user_moved, egui::Button::new(tr("↶ Take back"))) + .on_hover_text(tr("Take back a move (Ctrl+Z)")) + .clicked() + { + self.take_back(); + } + if !self.play_started() { + if ui + .button(tr("× Abort")) + .on_hover_text(tr("Leave without a result: no moves made yet")) + .clicked() + { + actions.push(GameAction::Back); + } + } else if self.play.as_ref().is_some_and(|s| s.resign_asked) { + ui.label(tr("Resign?")); + if ui + .add( + egui::Button::new(RichText::new(tr("Yes")).color(Color32::WHITE)) + .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.button(tr("No")).clicked() + && let Some(s) = self.play.as_mut() + { + s.resign_asked = false; + } + } else if ui.button(tr("⚑ Resign")).clicked() + && let Some(s) = self.play.as_mut() + { + s.resign_asked = true; + } + }); + ui.add_space(4.0); + } + + /// The strip above the notation after a game: the result and what to do next. + fn result_strip(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(end) = self.play_end.clone() else { + return; + }; + let mut close = false; + ui.add_space(4.0); + 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().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!(" {} ", end.ending.result().as_str())) + .strong() + .size(15.0) + .background_color(ui.visuals().widgets.inactive.weak_bg_fill), + ); + ui.label(RichText::new(end.heading()).strong().size(17.0)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Close")) + .clicked() + { + close = true; + } + }); + }); + if !end.detail().is_empty() { + ui.label(end.detail()); + } + if let Some((you, maia)) = end.left { + ui.label( + RichText::new(trf( + "Left: you {you} · Maia {maia}", + &[ + ("you", &crate::play::clock_text(you)), + ("maia", &crate::play::clock_text(maia)), + ], + )) + .weak(), + ); + } + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + if crate::widgets::primary(ui, tr("📈 Analyse")).clicked() { + self.review.dialog_open = true; + } + if ui + .button(tr("↻ Rematch")) + .on_hover_text(tr("Same settings, colours swapped")) + .clicked() + { + actions.push(GameAction::Rematch); + } + if ui.button(tr("⚔ New game")).clicked() { + actions.push(GameAction::PlayAgain); + } + if ui + .button(tr("💾 Save to a database…")) + .on_hover_text("Ctrl+S") + .clicked() + { + actions.push(GameAction::Save); + } + }); + }); + if close { + self.play_end = None; + } + } + /// Dev hook (`CP_SHAPE=Ge2e4,Rd5`): shapes drawn on the board at the current move. pub fn debug_shapes(&mut self, spec: &str) { for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) { @@ -1983,6 +2730,10 @@ impl GameView { if ui.ctx().egui_wants_keyboard_input() { return; } + if self.play.is_some() { + self.play_keys(ui, actions); + return; + } let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); let ctrl_shift = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k); let overlay = crate::app::overlay_open(ui.ctx()); diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 9baafe8..b132c7b 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -38,6 +38,8 @@ pub enum LibraryAction { /// Open PGN text as a new game. OpenPgn(String), NewGame, + /// A game against Maia: the play dialog. + Play, /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. NewGameIn(PathBuf), PastePgn, @@ -116,10 +118,15 @@ fn legacy_pgn(path: &Path) -> bool { /// `Library::app_buttons`), with the gap that sets the game ones apart from the /// database actions. fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { - let texts: [&str; 3] = if icons { - ["⚙", "📋", "♟"] + let texts: [&str; 4] = if icons { + ["⚙", "📋", "♟", "⚔"] } else { - [tr("⚙ Settings"), tr("📋 Paste PGN"), tr("♟ New game")] + [ + tr("⚙ Settings"), + tr("📋 Paste PGN"), + tr("♟ New game"), + tr("⚔ Play"), + ] }; texts.iter().map(|t| button_w(ui, t)).sum::() + update.map_or(0.0, |v| button_w(ui, v)) @@ -705,6 +712,16 @@ impl Library { { actions.push(LibraryAction::NewGame); } + if ui + .button(label(tr("⚔ Play"), "⚔")) + .on_hover_text(hint( + tr("⚔ Play"), + tr("A game against Maia, which plays like a human of the chosen rating (Ctrl+G)"), + )) + .clicked() + { + actions.push(LibraryAction::Play); + } if ui .button(label(tr("📋 Paste PGN"), "📋")) .on_hover_text(hint( diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs new file mode 100644 index 0000000..7bbf15e --- /dev/null +++ b/apps/desktop/src/maia_download.rs @@ -0,0 +1,128 @@ +//! Downloading the Maia-3 weights on request: the published checkpoint `maia3-5m.pt` +//! of a pinned revision from huggingface.co/UofTCSSLab/Maia3-5M, checked against its +//! SHA-256 and loaded once before use. Nothing is downloaded without the user asking; +//! the file is the authors' own, not redistributed by us. + +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use sha2::{Digest, Sha256}; + +const REVISION: &str = "b6559de2398d7140b985f28fd2c19fb5e47ddabe"; +const FILE: &str = "maia3-5m.pt"; +const SHA256: &str = "ba14208b2992d85502f5fb501934abf6aaaeb355e9f3fdf90e326911f562524f"; +pub const SIZE: u64 = 20_968_049; + +/// `/maia/maia3-5m.pt`. +fn dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("maia")) +} + +/// The weights, when they are there (`CP_MAIA` points elsewhere: development). +pub fn installed() -> Option { + if let Some(p) = std::env::var_os("CP_MAIA") { + return Some(PathBuf::from(p)); + } + let p = dir()?.join(FILE); + p.is_file().then_some(p) +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Stage { + Downloading { done: u64 }, + Checking, + Done(PathBuf), + Failed(String), +} + +/// A download in a background thread. +pub struct Download { + stage: Arc>, + cancel: Arc, +} + +impl Download { + pub fn start(ctx: &egui::Context) -> Download { + let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0 })); + let cancel = Arc::new(AtomicBool::new(false)); + let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone()); + let _ = std::thread::Builder::new() + .name("maia-download".into()) + .spawn(move || { + let report = |st: Stage| { + if let Ok(mut g) = s.lock() { + *g = st; + } + ctx.request_repaint(); + }; + let end = match run(&report, &c) { + Ok(p) => Stage::Done(p), + Err(e) => Stage::Failed(e), + }; + report(end); + }); + Download { stage, cancel } + } + + pub fn stage(&self) -> Stage { + self.stage + .lock() + .map(|g| g.clone()) + .unwrap_or(Stage::Failed(String::new())) + } +} + +impl Drop for Download { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { + let dir = dir().ok_or("no data directory")?; + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let part = dir.join(format!("{FILE}.part")); + let url = format!("https://huggingface.co/UofTCSSLab/Maia3-5M/resolve/{REVISION}/{FILE}"); + let result = (|| { + let mut response = ureq::get(&url).call().map_err(|e| e.to_string())?; + let mut body = response.body_mut().with_config().limit(SIZE + 1).reader(); + let mut file = std::fs::File::create(&part).map_err(|e| e.to_string())?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + let mut done = 0u64; + loop { + if cancel.load(Ordering::Relaxed) { + return Err("cancelled".to_owned()); + } + let n = body.read(&mut buf).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]).map_err(|e| e.to_string())?; + done += n as u64; + report(Stage::Downloading { done }); + } + file.sync_all().map_err(|e| e.to_string())?; + let digest: String = hasher + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + if done != SIZE || digest != SHA256 { + return Err(crate::i18n::tr("The file is not the published one").to_owned()); + } + report(Stage::Checking); + maia::Maia::load(&part).map_err(|e| e.to_string())?; + let dest = dir.join(FILE); + std::fs::rename(&part, &dest).map_err(|e| e.to_string())?; + Ok(dest) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&part); + } + result +} diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 1fd6972..67411e8 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -16,10 +16,12 @@ mod graphics; mod i18n; mod large_db; mod library; +mod maia_download; mod notation; mod online; mod online_ui; mod own_db; +mod play; mod reference; mod review; mod san; diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 3807715..51b538f 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -22,6 +22,8 @@ pub struct Notation<'a> { pub translations: Option<&'a HashMap>, /// The comment being written, drawn where the comment stands (user-comments.md §3). pub editor: Option<&'a mut CommentEditor>, + /// A game being played: moves only show their position (no menus, no editing). + pub read_only: bool, } /// Result of a frame of the notation panel. @@ -328,6 +330,9 @@ fn handle_move_response( resp.scroll_to_me(Some(egui::Align::Center)); } let is_variation = n.game.child_index(id).is_some_and(|i| i > 0) || !n.game.is_mainline(id); + if n.read_only { + return; + } // The menu is about the move it opens on: the move becomes the current one. if resp.secondary_clicked() && id != n.cursor { out.clicked = Some(id); diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs new file mode 100644 index 0000000..cf4c119 --- /dev/null +++ b/apps/desktop/src/play.rs @@ -0,0 +1,962 @@ +//! Playing against Maia (docs/research/play-mode.md, docs/design/play-mode.md): time +//! controls as on Lichess, the clock, the end of a game, and Maia's moves computed in a +//! background thread with a human-like pause. + +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use chess_core::shakmaty::zobrist::Zobrist64; +use chess_core::shakmaty::{Chess, Color, EnPassantMode, Move, Position}; +use serde::{Deserialize, Serialize}; + +use crate::i18n::tr; + +// ----- time controls -------------------------------------------------------------------- + +/// A clock: base seconds and increment seconds; `None` in the settings is "no clock". +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TimeControl { + pub base: u32, + pub increment: u32, +} + +/// The pools of Lichess (lila `PoolList.scala`). +pub const PRESETS: [TimeControl; 11] = [ + TimeControl { + base: 60, + increment: 0, + }, + TimeControl { + base: 120, + increment: 1, + }, + TimeControl { + base: 180, + increment: 0, + }, + TimeControl { + base: 180, + increment: 2, + }, + TimeControl { + base: 300, + increment: 0, + }, + TimeControl { + base: 300, + increment: 3, + }, + TimeControl { + base: 600, + increment: 0, + }, + TimeControl { + base: 600, + increment: 5, + }, + TimeControl { + base: 900, + increment: 10, + }, + TimeControl { + base: 1800, + increment: 0, + }, + TimeControl { + base: 1800, + increment: 20, + }, +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Speed { + UltraBullet, + Bullet, + Blitz, + Rapid, + Classical, +} + +impl Speed { + pub fn name(self) -> &'static str { + match self { + Speed::UltraBullet => tr("UltraBullet"), + Speed::Bullet => tr("Bullet"), + Speed::Blitz => tr("Blitz"), + Speed::Rapid => tr("Rapid"), + Speed::Classical => tr("Classical"), + } + } +} + +impl TimeControl { + /// The category by the estimated length, base + 40 × increment (scalachess + /// `Speed.scala`). + pub fn speed(self) -> Speed { + match self.base + 40 * self.increment { + 0..30 => Speed::UltraBullet, + 30..180 => Speed::Bullet, + 180..480 => Speed::Blitz, + 480..1500 => Speed::Rapid, + _ => Speed::Classical, + } + } + + /// «5+3», «½+0» as Lichess writes it (minutes + seconds). + pub fn label(self) -> String { + let min = match self.base { + 15 => "¼".to_owned(), + 30 => "½".to_owned(), + 45 => "¾".to_owned(), + 90 => "1½".to_owned(), + b => (b / 60).to_string(), + }; + format!("{min}+{}", self.increment) + } + + /// The PGN tag `TimeControl`: seconds + increment. + pub fn pgn(self) -> String { + format!("{}+{}", self.base, self.increment) + } +} + +/// The minutes the custom control offers (Lichess `timeControl.ts`), in seconds. +pub const CUSTOM_BASES: &[u32] = &[ + 0, 15, 30, 45, 60, 90, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900, + 960, 1020, 1080, 1140, 1200, 1500, 1800, 2100, 2400, 2700, 3600, 4500, 5400, 6300, 7200, 8100, + 9000, 9900, 10800, +]; +pub const CUSTOM_INCREMENTS: &[u32] = &[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 35, 40, 45, + 60, 90, 120, 150, 180, +]; + +/// The colour the user asks for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ColorChoice { + White, + #[default] + Random, + Black, +} + +/// The last choices of the play dialog (settings). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PlayPrefs { + pub color: ColorChoice, + /// `None`: no clock. + pub clock: Option, + /// Maia's rating, 600–2600. + pub strength: u32, +} + +impl Default for PlayPrefs { + fn default() -> Self { + PlayPrefs { + color: ColorChoice::Random, + clock: Some(TimeControl { + base: 300, + increment: 3, + }), + strength: 1500, + } + } +} + +pub const STRENGTH_MIN: u32 = 600; +pub const STRENGTH_MAX: u32 = 2600; + +/// «As me»: the user's rating rounded to 100, within Maia's range. +pub fn strength_like(rating: u32) -> u32 { + (((rating + 50) / 100) * 100).clamp(STRENGTH_MIN, STRENGTH_MAX) +} + +// ----- the clock ----------------------------------------------------------------------- + +/// Both clocks. Time runs for the side to move from the moment its opponent moved; a +/// side's first move takes no time (Lichess); the increment comes after the move. +#[derive(Clone, Debug)] +pub struct Clock { + pub control: TimeControl, + left: [Duration; 2], + moved: [bool; 2], + running: Option<(Color, Instant)>, +} + +fn idx(c: Color) -> usize { + match c { + Color::White => 0, + Color::Black => 1, + } +} + +impl Clock { + pub fn new(control: TimeControl) -> Clock { + // A base of 0 starts from the increment, at least 3 s (scalachess). + let start = if control.base == 0 { + Duration::from_secs(u64::from(control.increment.max(3))) + } else { + Duration::from_secs(u64::from(control.base)) + }; + Clock { + control, + left: [start; 2], + moved: [false; 2], + running: None, + } + } + + /// The time left of `c` at `now`. + pub fn left(&self, c: Color, now: Instant) -> Duration { + let base = self.left[idx(c)]; + match self.running { + Some((r, since)) if r == c && self.moved[idx(c)] => base.saturating_sub(now - since), + _ => base, + } + } + + /// `c` has moved: its time is taken (not on its first move), the increment added, + /// the other side's clock starts. + pub fn moved(&mut self, c: Color, now: Instant) { + let i = idx(c); + if self.moved[i] { + self.left[i] = self.left(c, now); + } + self.moved[i] = true; + self.left[i] += Duration::from_secs(u64::from(self.control.increment)); + self.running = Some((!c, now)); + } + + /// The side to move, its clock running (after its first move). + pub fn running(&self) -> Option { + self.running.map(|(c, _)| c).filter(|c| self.moved[idx(*c)]) + } + + /// The clocks waited (a question about leaving was open): the running one is moved + /// on by `d`, as if no time passed. + pub fn pause(&mut self, d: Duration) { + if let Some((_, since)) = self.running.as_mut() { + *since += d; + } + } + + pub fn stop(&mut self, now: Instant) { + if let Some((c, _)) = self.running { + self.left[idx(c)] = self.left(c, now); + } + self.running = None; + } + + /// The low-time threshold: min(60, max(10, base / 8)) seconds (scalachess). + pub fn low(&self) -> Duration { + Duration::from_secs(u64::from((self.control.base / 8).clamp(10, 60))) + } +} + +/// «4:58», «1:02:03», «0:09.4» (tenths under 10 s). +pub fn clock_text(d: Duration) -> String { + let ms = d.as_millis(); + let s = ms / 1000; + if s >= 3600 { + format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60) + } else if ms < 10_000 { + format!("0:{:02}.{}", s, ms / 100 % 10) + } else { + format!("{}:{:02}", s / 60, s % 60) + } +} + +/// `[%clk 0:04:58]` for the PGN. +pub fn clk_command(d: Duration) -> String { + let s = d.as_secs(); + format!("[%clk {}:{:02}:{:02}]", s / 3600, s / 60 % 60, s % 60) +} + +// ----- the end of a game --------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ending { + Checkmate { + winner: Color, + }, + Stalemate, + InsufficientMaterial, + Threefold, + FiftyMoves, + /// `loser` ran out of time; a draw when the other side cannot mate. + Time { + loser: Color, + draw: bool, + }, + Resigned { + loser: Color, + }, +} + +impl Ending { + pub fn result(self) -> chess_core::GameResult { + use chess_core::GameResult as R; + let win = |c: Color| match c { + Color::White => R::WhiteWins, + Color::Black => R::BlackWins, + }; + match self { + Ending::Checkmate { winner } => win(winner), + Ending::Time { draw: true, .. } => R::Draw, + Ending::Time { loser, .. } | Ending::Resigned { loser } => win(!loser), + Ending::Stalemate + | Ending::InsufficientMaterial + | Ending::Threefold + | Ending::FiftyMoves => R::Draw, + } + } + + /// The tag `Termination` (as Lichess writes it). + pub fn termination(self) -> &'static str { + match self { + Ending::Time { .. } => "Time forfeit", + _ => "Normal", + } + } +} + +/// How the game stands after the last of `positions` (the positions of the main line +/// from the start): mate, stalemate, no material, threefold repetition, fifty moves. +pub fn ending(positions: &[Chess]) -> Option { + let pos = positions.last()?; + if pos.is_checkmate() { + return Some(Ending::Checkmate { + winner: !pos.turn(), + }); + } + if pos.is_stalemate() { + return Some(Ending::Stalemate); + } + if pos.is_insufficient_material() { + return Some(Ending::InsufficientMaterial); + } + let key = |p: &Chess| p.zobrist_hash::(EnPassantMode::Legal); + let now = key(pos); + // Only positions since the last capture or pawn move can repeat. + let span = (pos.halfmoves() as usize + 1).min(positions.len()); + let repeats = positions[positions.len() - span..] + .iter() + .filter(|p| key(p) == now) + .count(); + if repeats >= 3 { + return Some(Ending::Threefold); + } + if pos.halfmoves() >= 100 { + return Some(Ending::FiftyMoves); + } + None +} + +// ----- Maia's moves ------------------------------------------------------------------- + +/// A request for a move: the positions up to now, the ratings, the pause. +struct Request { + generation: u64, + positions: Vec, + self_elo: u32, + oppo_elo: u32, + pause: Duration, +} + +/// The engine in a thread of its own: loads Maia once, answers requests after a pause. +/// An answer for an older generation (after a take-back, a resignation) is dropped. +pub struct Opponent { + tx: Sender, + rx: Receiver<(u64, Option)>, + generation: u64, + /// Loading failed: why (shown to the user). + pub error: Arc>>, + pub thinking: bool, +} + +impl Opponent { + pub fn start(weights: std::path::PathBuf, ctx: &egui::Context) -> Opponent { + let (tx, req_rx) = channel::(); + let (ans_tx, rx) = channel(); + let error = Arc::new(Mutex::new(None)); + let err = error.clone(); + let ctx = ctx.clone(); + let _ = std::thread::Builder::new() + .name("maia".into()) + .spawn(move || { + let maia = match maia::Maia::load(&weights) { + Ok(m) => m, + Err(e) => { + if let Ok(mut g) = err.lock() { + *g = Some(e.to_string()); + } + ctx.request_repaint(); + return; + } + }; + while let Ok(mut r) = req_rx.recv() { + // Only the newest request counts. + while let Ok(newer) = req_rx.try_recv() { + r = newer; + } + let started = Instant::now(); + let p = maia.predict(&r.positions, r.self_elo, r.oppo_elo); + let m = maia::pick(&p, 1.0, random_unit()); + let rest = r.pause.saturating_sub(started.elapsed()); + std::thread::sleep(rest); + if ans_tx.send((r.generation, m)).is_err() { + return; + } + ctx.request_repaint(); + } + }); + Opponent { + tx, + rx, + generation: 0, + error, + thinking: false, + } + } + + /// Asks for a move in the last of `positions`. + pub fn ask(&mut self, positions: Vec, self_elo: u32, oppo_elo: u32, pause: Duration) { + self.generation += 1; + self.thinking = true; + let _ = self.tx.send(Request { + generation: self.generation, + positions, + self_elo, + oppo_elo, + pause, + }); + } + + /// Forgets what was asked (its answer will be dropped). + pub fn forget(&mut self) { + self.generation += 1; + self.thinking = false; + } + + /// The move asked for last, when it has come. + pub fn answer(&mut self) -> Option { + let mut out = None; + while let Ok((g, m)) = self.rx.try_recv() { + if g == self.generation { + self.thinking = false; + out = m; + } + } + out + } + + pub fn failed(&self) -> Option { + self.error.lock().ok().and_then(|g| g.clone()) + } +} + +/// A number in [0, 1). +pub fn random_unit() -> f32 { + let mut b = [0u8; 4]; + let _ = getrandom::fill(&mut b); + (u32::from_le_bytes(b) >> 8) as f32 / (1u32 << 24) as f32 +} + +/// How long Maia "thinks" (it computes in a tenth of a second): about 1/30 of its time +/// plus most of the increment, varied at random; fast in the opening and with one +/// legal move; never so long that it could lose on time (docs/research/play-mode.md R15). +pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Duration { + let r = random_unit(); + // A log-normal-ish factor between 0.4 and 2.5. + let factor = (0.4f32 * (2.5f32 / 0.4).powf(r)).clamp(0.4, 2.5); + let secs = match clock { + None => 0.5 + 1.5 * r, + Some((left, inc)) => { + let left = left.as_secs_f32(); + if left < 10.0 { + 0.2 + 0.8 * r + } else { + let mut t = (left / 30.0 + 0.75 * inc as f32) * factor; + if ply < 10 { + t *= 0.3; + } + t.clamp(0.4, (left / 8.0).min(60.0)) + } + } + }; + let secs = if only_move { + secs.min(0.3 + 0.5 * r) + } else { + secs + }; + Duration::from_secs_f32(secs) +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::shakmaty::uci::UciMove; + + #[test] + fn speeds_as_lichess() { + let s = |base, increment| TimeControl { base, increment }.speed(); + assert_eq!(s(60, 0), Speed::Bullet); + assert_eq!(s(120, 1), Speed::Bullet); + assert_eq!(s(180, 0), Speed::Blitz); + assert_eq!(s(300, 3), Speed::Blitz); + assert_eq!(s(420, 0), Speed::Blitz); + assert_eq!(s(480, 0), Speed::Rapid); + assert_eq!(s(900, 10), Speed::Rapid); + assert_eq!(s(1500, 0), Speed::Classical); + assert_eq!(s(15, 0), Speed::UltraBullet); + assert_eq!( + TimeControl { + base: 300, + increment: 3 + } + .label(), + "5+3" + ); + assert_eq!( + TimeControl { + base: 30, + increment: 0 + } + .label(), + "½+0" + ); + assert_eq!( + TimeControl { + base: 300, + increment: 3 + } + .pgn(), + "300+3" + ); + } + + #[test] + fn clock_runs_after_first_moves() { + let mut c = Clock::new(TimeControl { + base: 60, + increment: 2, + }); + let t0 = Instant::now(); + c.moved(Color::White, t0); // the first move takes nothing + assert_eq!(c.left(Color::White, t0), Duration::from_secs(62)); + // Black's first move: no time taken either. + c.moved(Color::Black, t0 + Duration::from_secs(5)); + assert_eq!( + c.left(Color::Black, t0 + Duration::from_secs(5)), + Duration::from_secs(62) + ); + // White thinks 10 s. + let t1 = t0 + Duration::from_secs(15); + assert_eq!(c.left(Color::White, t1), Duration::from_secs(52)); + c.moved(Color::White, t1); + assert_eq!(c.left(Color::White, t1), Duration::from_secs(54)); + assert_eq!(c.running(), Some(Color::Black)); + assert_eq!(clock_text(Duration::from_millis(9_450)), "0:09.4"); + assert_eq!(clock_text(Duration::from_secs(298)), "4:58"); + assert_eq!(clock_text(Duration::from_secs(3723)), "1:02:03"); + assert_eq!(clk_command(Duration::from_secs(298)), "[%clk 0:04:58]"); + assert_eq!( + Clock::new(TimeControl { + base: 180, + increment: 0 + }) + .low(), + Duration::from_secs(22) + ); + } + + fn play(moves: &[&str]) -> Vec { + let mut pos = Chess::default(); + let mut out = vec![pos.clone()]; + for m in moves { + let m = m.parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(m); + out.push(pos.clone()); + } + out + } + + #[test] + fn endings() { + let mate = play(&["f2f3", "e7e5", "g2g4", "d8h4"]); + assert_eq!( + ending(&mate), + Some(Ending::Checkmate { + winner: Color::Black + }) + ); + let rep = play(&[ + "g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8", + ]); + assert_eq!(ending(&rep), Some(Ending::Threefold)); + assert_eq!(ending(&rep[..rep.len() - 1]), None); + assert_eq!(ending(&play(&["e2e4"])), None); + assert_eq!( + Ending::Time { + loser: Color::White, + draw: false + } + .result(), + chess_core::GameResult::BlackWins + ); + } + + #[test] + fn pauses_never_lose_on_time() { + for _ in 0..200 { + let p = pause(Some((Duration::from_secs(20), 0)), 30, false); + assert!(p <= Duration::from_millis(2500), "{p:?}"); + let p = pause(Some((Duration::from_secs(5), 0)), 30, false); + assert!(p <= Duration::from_millis(1000)); + } + assert_eq!(strength_like(1350), 1400); + assert_eq!(strength_like(300), 600); + } +} + +// ----- a game being played ------------------------------------------------------------ + +/// A game against Maia in progress (lives in the game screen while it is played). +pub struct Session { + pub user: Color, + pub strength: u32, + pub user_elo: Option, + pub clock: Option, + pub opponent: Opponent, + /// The low-time warning was given (once). + pub warned: bool, + /// «Resign?» waits for the second click. + pub resign_asked: bool, +} + +/// What the play dialog starts. +#[derive(Clone, Debug)] +pub struct Start { + pub user: Color, + pub strength: u32, + pub user_elo: Option, + pub user_name: String, + pub clock: Option, +} + +// ----- the dialog --------------------------------------------------------------------- + +/// «Play against the computer»: name and rating, colour, time, strength. +pub struct Dialog { + name: String, + rating: String, + prefs: PlayPrefs, + custom: bool, + download: Option, + focus: bool, +} + +pub enum DialogOutcome { + Play(Start), + Cancel, +} + +impl Dialog { + pub fn new(settings: &crate::settings::Settings) -> Dialog { + let prefs = settings.play.clone(); + let custom = prefs.clock.is_some_and(|c| !PRESETS.contains(&c)); + Dialog { + name: settings.your_name.clone(), + rating: settings.rating.map(|r| r.to_string()).unwrap_or_default(), + prefs, + custom, + download: None, + focus: true, + } + } + + fn rating(&self) -> Option { + self.rating + .trim() + .parse::() + .ok() + .filter(|r| (100..=3500).contains(r)) + } + + /// Draws the dialog; on «Play» the choices are written into `settings`. + pub fn show( + &mut self, + ctx: &egui::Context, + settings: &mut crate::settings::Settings, + ) -> Option { + use egui::RichText; + let mut out = None; + let installed = crate::maia_download::installed(); + egui::Modal::new(egui::Id::new("play_dialog")).show(ctx, |ui| { + ui.set_width(460.0); + ui.heading(tr("Play against the computer")); + ui.label( + RichText::new(tr( + "Maia plays like a human of the chosen rating: it makes the moves people of that level make, mistakes included.", + )) + .weak(), + ); + ui.add_space(10.0); + + // You. + ui.label(RichText::new(tr("You")).strong()); + ui.horizontal(|ui| { + ui.label(tr("Name:")); + let r = ui.add(egui::TextEdit::singleline(&mut self.name).desired_width(200.0)); + if std::mem::take(&mut self.focus) && self.name.is_empty() { + r.request_focus(); + } + ui.label(tr("Rating:")); + let r = ui.add( + egui::TextEdit::singleline(&mut self.rating) + .desired_width(60.0) + .hint_text("1500"), + ); + if r.changed() { + self.rating.retain(|c| c.is_ascii_digit()); + self.rating.truncate(4); + } + }); + ui.label( + RichText::new(tr("Not required; the opponent's strength is chosen relative to it.")) + .weak() + .size(11.5), + ); + ui.add_space(10.0); + + // Colour. + ui.label(RichText::new(tr("Your colour")).strong()); + ui.horizontal(|ui| { + for (c, label) in [ + (ColorChoice::White, tr("♔ White")), + (ColorChoice::Random, tr("Random")), + (ColorChoice::Black, tr("♚ Black")), + ] { + ui.selectable_value(&mut self.prefs.color, c, label); + } + }); + ui.add_space(10.0); + + // Time. + ui.label(RichText::new(tr("Time")).strong()); + egui::Grid::new("play_presets") + .spacing(egui::vec2(6.0, 6.0)) + .show(ui, |ui| { + for (k, tc) in PRESETS.iter().enumerate() { + let on = !self.custom && self.prefs.clock == Some(*tc); + let text = format!("{}\n{}", tc.label(), tc.speed().name()); + if ui + .add_sized([96.0, 40.0], egui::Button::selectable(on, text)) + .clicked() + { + self.prefs.clock = Some(*tc); + self.custom = false; + } + if k % 4 == 3 { + ui.end_row(); + } + } + if ui + .add_sized([96.0, 40.0], egui::Button::selectable(self.custom, tr("Custom"))) + .clicked() + { + self.custom = true; + if self.prefs.clock.is_none() { + self.prefs.clock = Some(TimeControl { base: 600, increment: 0 }); + } + } + ui.end_row(); + }); + ui.horizontal(|ui| { + let none = self.prefs.clock.is_none(); + if ui.selectable_label(none, tr("No clock")).clicked() { + self.prefs.clock = None; + self.custom = false; + } + }); + if self.custom + && let Some(tc) = self.prefs.clock.as_mut() + { + let mut b = CUSTOM_BASES.iter().position(|&x| x >= tc.base).unwrap_or(14); + let mut i = CUSTOM_INCREMENTS + .iter() + .position(|&x| x >= tc.increment) + .unwrap_or(0); + ui.horizontal(|ui| { + ui.label(tr("Minutes:")); + ui.add(egui::Slider::new(&mut b, 0..=CUSTOM_BASES.len() - 1).show_value(false)); + ui.label(TimeControl { base: CUSTOM_BASES[b], increment: 0 }.label().trim_end_matches("+0")); + }); + ui.horizontal(|ui| { + ui.label(tr("Increment, s:")); + ui.add( + egui::Slider::new(&mut i, 0..=CUSTOM_INCREMENTS.len() - 1).show_value(false), + ); + ui.label(CUSTOM_INCREMENTS[i].to_string()); + }); + tc.base = CUSTOM_BASES[b]; + tc.increment = CUSTOM_INCREMENTS[i]; + if tc.base == 0 && tc.increment == 0 { + tc.increment = 1; + } + ui.label( + RichText::new(format!("{} · {}", tc.label(), tc.speed().name())).weak(), + ); + } + ui.add_space(10.0); + + // Strength. + ui.label(RichText::new(tr("Opponent")).strong()); + ui.horizontal(|ui| { + ui.add( + egui::Slider::new(&mut self.prefs.strength, STRENGTH_MIN..=STRENGTH_MAX) + .step_by(100.0) + .show_value(false), + ); + ui.label(RichText::new(format!("Maia {}", self.prefs.strength)).strong()); + }); + let rating = self.rating(); + ui.add_enabled_ui(rating.is_some(), |ui| { + ui.horizontal(|ui| { + for (label, delta) in [(tr("Weaker"), -200), (tr("As me"), 0), (tr("Stronger"), 200)] { + if ui.button(label).clicked() + && let Some(r) = rating + { + self.prefs.strength = + strength_like((r as i32 + delta).max(0) as u32); + } + } + }); + }) + .response + .on_disabled_hover_text(tr("Enter your rating to choose relative to it")); + ui.label( + RichText::new(tr("Maia's ratings are Lichess ratings: club and federation ratings are usually lower.")) + .weak() + .size(11.5), + ); + ui.add_space(10.0); + + // Maia itself: downloaded once. + let mut ready = installed.is_some(); + if !ready { + match self.download.as_ref().map(|d| d.stage()) { + None => { + ui.label(trf_size()); + if ui.button(tr("Download Maia")).clicked() { + self.download = Some(crate::maia_download::Download::start(ctx)); + } + } + Some(crate::maia_download::Stage::Downloading { done }) => { + ui.add( + egui::ProgressBar::new(done as f32 / crate::maia_download::SIZE as f32) + .show_percentage(), + ); + } + Some(crate::maia_download::Stage::Checking) => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Checking…")); + }); + } + Some(crate::maia_download::Stage::Done(_)) => ready = true, + Some(crate::maia_download::Stage::Failed(e)) => { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + if ui.button(tr("Try again")).clicked() { + self.download = Some(crate::maia_download::Download::start(ctx)); + } + } + } + } + + ui.add_space(6.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let play = ui + .add_enabled_ui(ready, |ui| crate::widgets::primary(ui, tr("Play"))) + .inner; + let enter = ready && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if play.clicked() || enter { + let user = match self.prefs.color { + ColorChoice::White => Color::White, + ColorChoice::Black => Color::Black, + ColorChoice::Random => { + if random_unit() < 0.5 { + Color::White + } else { + Color::Black + } + } + }; + settings.your_name = self.name.trim().to_owned(); + settings.rating = rating; + settings.play = self.prefs.clone(); + out = Some(DialogOutcome::Play(Start { + user, + strength: self.prefs.strength, + user_elo: rating, + user_name: self.name.trim().to_owned(), + clock: self.prefs.clock, + })); + } + if ui.button(tr("Cancel")).clicked() { + out = Some(DialogOutcome::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + out = Some(DialogOutcome::Cancel); + } + out + } +} + +fn trf_size() -> String { + crate::i18n::trf( + "Maia is downloaded once ({mb} MB, from huggingface.co, the authors' own file).", + &[("mb", &crate::maia_download::SIZE.div_ceil(1_000_000))], + ) +} + +/// A game just played: what the result strip says. +#[derive(Clone, Debug)] +pub struct End { + pub ending: Ending, + pub user: Color, + pub start: Start, + /// The clocks at the end (user, Maia). + pub left: Option<(Duration, Duration)>, +} + +impl End { + /// «You won» / «You lost» / «Draw» / «You resigned». + pub fn heading(&self) -> &'static str { + match self.ending { + Ending::Resigned { .. } => tr("You resigned"), + e => match e.result() { + chess_core::GameResult::Draw => tr("Draw"), + r if r == Ending::Checkmate { winner: self.user }.result() => tr("You won"), + _ => tr("You lost"), + }, + } + } + + pub fn detail(&self) -> &'static str { + match self.ending { + Ending::Checkmate { .. } => tr("checkmate"), + Ending::Stalemate => tr("stalemate"), + Ending::InsufficientMaterial => tr("neither side can checkmate"), + Ending::Threefold => tr("the position occurred three times"), + Ending::FiftyMoves => tr("50 moves without a capture or a pawn move"), + Ending::Time { draw: true, .. } => tr("time is up, but Maia cannot checkmate"), + Ending::Time { .. } => tr("time is up"), + Ending::Resigned { .. } => "", + } + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index 9b6c2fd..988fb1f 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -139,6 +139,10 @@ pub struct Settings { pub new_database_dir: Option, /// The database a game was last added to (preselected in the chooser). pub last_target: Option, + /// The user's rating (optional): the strength of Maia is chosen relative to it. + pub rating: Option, + /// The last choices of the play dialog. + pub play: crate::play::PlayPrefs, } /// Options of the whole-game analysis (the engine is the active one). @@ -203,6 +207,8 @@ impl Default for Settings { your_name: String::new(), new_database_dir: None, last_target: None, + rating: None, + play: Default::default(), } } } diff --git a/crates/maia/src/checkpoint.rs b/crates/maia/src/checkpoint.rs new file mode 100644 index 0000000..0a3fe27 --- /dev/null +++ b/crates/maia/src/checkpoint.rs @@ -0,0 +1,321 @@ +//! Reads the published PyTorch checkpoint (`maia3-5m.pt`) directly: a zip archive with +//! stored (uncompressed) members — a pickle describing the tensors (`data.pkl`) and +//! their raw little-endian f32 storages (`data/`). Only what such a checkpoint +//! uses is understood; anything else is refused, nothing is executed. + +use std::collections::HashMap; + +use crate::weights::{Tensor, WeightsError}; + +/// The members of a zip archive stored without compression: name → bytes. +fn zip_members(b: &[u8]) -> Result, WeightsError> { + let u16_at = |i: usize| -> Result { + Ok(u16::from_le_bytes( + b.get(i..i + 2) + .ok_or(WeightsError::Format)? + .try_into() + .unwrap(), + ) as usize) + }; + let u32_at = |i: usize| -> Result { + Ok(u32::from_le_bytes( + b.get(i..i + 4) + .ok_or(WeightsError::Format)? + .try_into() + .unwrap(), + ) as usize) + }; + // The end of central directory record, searched from the end (a comment may follow). + let eocd = (0..b.len().saturating_sub(21)) + .rev() + .take(65_557) + .find(|&i| b[i..].starts_with(b"PK\x05\x06")) + .ok_or(WeightsError::Format)?; + let count = u16_at(eocd + 10)?; + let mut at = u32_at(eocd + 16)?; + let mut out = HashMap::new(); + for _ in 0..count { + if !b.get(at..).is_some_and(|r| r.starts_with(b"PK\x01\x02")) { + return Err(WeightsError::Format); + } + let method = u16_at(at + 10)?; + let size = u32_at(at + 20)?; + let (name_len, extra_len, comment_len) = + (u16_at(at + 28)?, u16_at(at + 30)?, u16_at(at + 32)?); + let local = u32_at(at + 42)?; + let name = std::str::from_utf8( + b.get(at + 46..at + 46 + name_len) + .ok_or(WeightsError::Format)?, + ) + .map_err(|_| WeightsError::Format)? + .to_owned(); + at += 46 + name_len + extra_len + comment_len; + if method != 0 { + return Err(WeightsError::Format); + } + let data = local + 30 + u16_at(local + 26)? + u16_at(local + 28)?; + out.insert(name, b.get(data..data + size).ok_or(WeightsError::Format)?); + } + Ok(out) +} + +/// A value of the pickle machine (only what a checkpoint holds). +#[derive(Clone, Debug)] +enum Value { + Int(i64), + Str(String), + Bool, + Tuple(Vec), + Global(String), + /// A storage: its key in `data/`. + Storage(String), + /// A tensor: storage key, offset, shape, strides. + Tensor(String, usize, Vec, Vec), + Dict(Vec<(Value, Value)>), + Mark, + None, +} + +fn as_usizes(v: &Value) -> Result, WeightsError> { + match v { + Value::Tuple(items) => items + .iter() + .map(|i| match i { + Value::Int(n) if *n >= 0 => Ok(*n as usize), + _ => Err(WeightsError::Format), + }) + .collect(), + _ => Err(WeightsError::Format), + } +} + +/// Runs the pickle `p` (protocol 2, the opcodes `torch.save` writes for a state dict). +fn unpickle(p: &[u8]) -> Result { + let bad = || WeightsError::Format; + let mut stack: Vec = Vec::new(); + let mut memo: HashMap = HashMap::new(); + let mut i = 0; + let byte = |i: usize| p.get(i).copied().ok_or(WeightsError::Format); + let le = |i: usize, n: usize| -> Result { + let s = p.get(i..i + n).ok_or(WeightsError::Format)?; + Ok(s.iter() + .rev() + .fold(0usize, |a, b| (a << 8) | usize::from(*b))) + }; + let pop_mark = |stack: &mut Vec| -> Result, WeightsError> { + let at = stack + .iter() + .rposition(|v| matches!(v, Value::Mark)) + .ok_or(WeightsError::Format)?; + let items = stack.split_off(at + 1); + stack.pop(); + Ok(items) + }; + loop { + let op = byte(i)?; + i += 1; + match op { + 0x80 => i += 1, // PROTO + b'}' => stack.push(Value::Dict(vec![])), // EMPTY_DICT + b')' => stack.push(Value::Tuple(vec![])), // EMPTY_TUPLE + b'(' => stack.push(Value::Mark), // MARK + b'q' => { + // BINPUT + memo.insert(usize::from(byte(i)?), stack.last().ok_or_else(bad)?.clone()); + i += 1; + } + b'r' => { + // LONG_BINPUT + memo.insert(le(i, 4)?, stack.last().ok_or_else(bad)?.clone()); + i += 4; + } + b'h' => { + // BINGET + stack.push(memo.get(&usize::from(byte(i)?)).ok_or_else(bad)?.clone()); + i += 1; + } + b'j' => { + // LONG_BINGET + stack.push(memo.get(&le(i, 4)?).ok_or_else(bad)?.clone()); + i += 4; + } + b'K' => { + stack.push(Value::Int(i64::from(byte(i)?))); + i += 1; + } + b'M' => { + stack.push(Value::Int(le(i, 2)? as i64)); + i += 2; + } + b'J' => { + stack.push(Value::Int(i64::from(le(i, 4)? as u32 as i32))); + i += 4; + } + b'X' => { + // BINUNICODE + let n = le(i, 4)?; + let s = std::str::from_utf8(p.get(i + 4..i + 4 + n).ok_or_else(bad)?) + .map_err(|_| bad())?; + stack.push(Value::Str(s.to_owned())); + i += 4 + n; + } + b'c' => { + // GLOBAL "module\nname\n" + let end1 = p[i..].iter().position(|&c| c == b'\n').ok_or_else(bad)? + i; + let end2 = p[end1 + 1..] + .iter() + .position(|&c| c == b'\n') + .ok_or_else(bad)? + + end1 + + 1; + let module = std::str::from_utf8(&p[i..end1]).map_err(|_| bad())?; + let name = std::str::from_utf8(&p[end1 + 1..end2]).map_err(|_| bad())?; + stack.push(Value::Global(format!("{module}.{name}"))); + i = end2 + 1; + } + 0x88 => stack.push(Value::Bool), // NEWTRUE + 0x89 => stack.push(Value::Bool), // NEWFALSE + b'N' => stack.push(Value::None), + b't' => { + let items = pop_mark(&mut stack)?; + stack.push(Value::Tuple(items)); + } + 0x85..=0x87 => { + // TUPLE1/2/3 + let n = usize::from(op - 0x84); + if stack.len() < n { + return Err(bad()); + } + let items = stack.split_off(stack.len() - n); + stack.push(Value::Tuple(items)); + } + b'Q' => { + // BINPERSID: ('storage', FloatStorage, key, location, numel) + let Value::Tuple(pid) = stack.pop().ok_or_else(bad)? else { + return Err(bad()); + }; + match pid.as_slice() { + [Value::Str(kind), Value::Global(t), Value::Str(key), ..] + if kind == "storage" && t == "torch.FloatStorage" => + { + stack.push(Value::Storage(key.clone())); + } + _ => return Err(bad()), + } + } + b'R' => { + // REDUCE: only the constructors of a state dict. + let Value::Tuple(args) = stack.pop().ok_or_else(bad)? else { + return Err(bad()); + }; + let Value::Global(f) = stack.pop().ok_or_else(bad)? else { + return Err(bad()); + }; + match f.as_str() { + "torch._utils._rebuild_tensor_v2" => match args.as_slice() { + [Value::Storage(key), Value::Int(offset), shape, stride, ..] => { + stack.push(Value::Tensor( + key.clone(), + *offset as usize, + as_usizes(shape)?, + as_usizes(stride)?, + )); + } + _ => return Err(bad()), + }, + "torch._utils._rebuild_parameter" => { + stack.push(args.into_iter().next().ok_or_else(bad)?); + } + "collections.OrderedDict" => stack.push(Value::Dict(vec![])), + _ => return Err(bad()), + } + } + b'u' => { + // SETITEMS + let items = pop_mark(&mut stack)?; + let Some(Value::Dict(d)) = stack.last_mut() else { + return Err(bad()); + }; + for kv in items.chunks(2) { + if let [k, v] = kv { + d.push((k.clone(), v.clone())); + } + } + } + b's' => { + // SETITEM + let v = stack.pop().ok_or_else(bad)?; + let k = stack.pop().ok_or_else(bad)?; + let Some(Value::Dict(d)) = stack.last_mut() else { + return Err(bad()); + }; + d.push((k, v)); + } + b'.' => return stack.pop().ok_or_else(bad), + _ => return Err(bad()), + } + } +} + +/// The tensors of a checkpoint: name → shape and f32 data. +pub fn read(bytes: &[u8]) -> Result, WeightsError> { + let members = zip_members(bytes)?; + let (pkl_name, pkl) = members + .iter() + .find(|(n, _)| n.ends_with("/data.pkl")) + .ok_or(WeightsError::Format)?; + let root = pkl_name.trim_end_matches("data.pkl"); + let Value::Dict(mut items) = unpickle(pkl)? else { + return Err(WeightsError::Format); + }; + // A checkpoint may wrap the state dict: {"model_state_dict": {...}, ...}. + if let Some((_, Value::Dict(inner))) = items + .iter() + .find(|(k, _)| matches!(k, Value::Str(s) if s == "model_state_dict")) + { + items = inner.clone(); + } + let mut out = HashMap::new(); + for (k, v) in items { + let (Value::Str(name), Value::Tensor(key, offset, shape, stride)) = (k, v) else { + continue; + }; + let n: usize = shape.iter().product(); + // Contiguous, row-major: what a saved state dict holds. + let mut want = vec![1usize; shape.len()]; + for d in (0..shape.len().saturating_sub(1)).rev() { + want[d] = want[d + 1] * shape[d + 1]; + } + if n > 1 && stride != want { + return Err(WeightsError::Format); + } + let raw = members + .get(&format!("{root}data/{key}")) + .ok_or(WeightsError::Format)? + .get(offset * 4..(offset + n) * 4) + .ok_or(WeightsError::Format)?; + let data = raw + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes(*c)) + .collect(); + out.insert(name.replace("smolgen", "gab"), Tensor { shape, data }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refuses_what_is_not_a_checkpoint() { + assert!(read(b"").is_err()); + assert!(read(b"PK\x05\x06garbage").is_err()); + assert!(read(&[0u8; 100]).is_err()); + // A pickle that calls anything but the state-dict constructors is refused. + assert!(unpickle(b"\x80\x02cos\nsystem\nq\x00X\x02\x00\x00\x00lsq\x01\x85q\x02R.").is_err()); + assert!(unpickle(b"\x80\x02}q\x00.").is_ok()); + } +} diff --git a/crates/maia/src/lib.rs b/crates/maia/src/lib.rs index 78e5e5c..36ee1cd 100644 --- a/crates/maia/src/lib.rs +++ b/crates/maia/src/lib.rs @@ -5,10 +5,11 @@ //! move and the ratings of both players, and gives the probability of each legal move //! as a player of that rating would play it, plus the chances of win, draw and loss. //! -//! The weights come from a file in our own simple format (`MAIA3W02`, written by -//! `scripts/maia-convert.py` from the published PyTorch checkpoint): halves (f16), -//! read once into f32. +//! The weights are the published checkpoint itself (`maia3-5m.pt`, PyTorch's zip of a +//! pickle and raw f32 storages), read without PyTorch: the network shares one bias +//! tensor between its blocks. +mod checkpoint; mod net; mod weights; @@ -23,7 +24,7 @@ pub struct Maia { } impl Maia { - /// Reads the weights file. + /// Reads the checkpoint (`maia3-5m.pt`). pub fn load(path: &std::path::Path) -> Result { let bytes = std::fs::read(path).map_err(WeightsError::Io)?; Maia::from_bytes(&bytes) diff --git a/crates/maia/src/weights.rs b/crates/maia/src/weights.rs index 54caadd..eed0c83 100644 --- a/crates/maia/src/weights.rs +++ b/crates/maia/src/weights.rs @@ -1,5 +1,4 @@ -//! The weights file: `MAIA3W02`, a u32 count, then per tensor a u16 name length, the -//! name, a u8 rank, u32 dims and a u64 offset; the data are f16 little-endian. +//! The network's tensors by name, read from the published checkpoint. use std::collections::HashMap; @@ -7,7 +6,7 @@ use std::collections::HashMap; pub enum WeightsError { #[error("cannot read the weights: {0}")] Io(std::io::Error), - #[error("not a Maia weights file")] + #[error("not a Maia checkpoint")] Format, #[error("the weights lack {0}")] Missing(String), @@ -24,64 +23,12 @@ pub struct Weights { tensors: HashMap, } -fn f16_to_f32(h: u16) -> f32 { - let sign = u32::from(h >> 15) << 31; - let exp = u32::from((h >> 10) & 0x1f); - let frac = u32::from(h & 0x3ff); - let bits = match (exp, frac) { - (0, 0) => sign, - (0, f) => { - // Subnormal: normalise. - let mut e = 127 - 15 + 1; - let mut f = f; - while f & 0x400 == 0 { - f <<= 1; - e -= 1; - } - sign | (e << 23) | ((f & 0x3ff) << 13) - } - (0x1f, f) => sign | 0x7f80_0000 | (f << 13), - (e, f) => sign | ((e + 127 - 15) << 23) | (f << 13), - }; - f32::from_bits(bits) -} - impl Weights { - pub fn parse(b: &[u8]) -> Result { - let take = |at: usize, n: usize| b.get(at..at + n).ok_or(WeightsError::Format); - if take(0, 8)? != b"MAIA3W02" { - return Err(WeightsError::Format); - } - let count = u32::from_le_bytes(take(8, 4)?.try_into().unwrap()) as usize; - let mut at = 12; - let mut tensors = HashMap::new(); - for _ in 0..count { - let len = u16::from_le_bytes(take(at, 2)?.try_into().unwrap()) as usize; - at += 2; - let name = std::str::from_utf8(take(at, len)?) - .map_err(|_| WeightsError::Format)? - .to_owned(); - at += len; - let rank = take(at, 1)?[0] as usize; - at += 1; - let mut shape = Vec::with_capacity(rank); - for _ in 0..rank { - shape.push(u32::from_le_bytes(take(at, 4)?.try_into().unwrap()) as usize); - at += 4; - } - let offset = u64::from_le_bytes(take(at, 8)?.try_into().unwrap()) as usize; - at += 8; - let n: usize = shape.iter().product(); - let raw = take(offset, 2 * n)?; - let data = raw - .as_chunks::<2>() - .0 - .iter() - .map(|c| f16_to_f32(u16::from_le_bytes(*c))) - .collect(); - tensors.insert(name, Tensor { shape, data }); - } - Ok(Weights { tensors }) + /// The tensors of a PyTorch checkpoint (`maia3-5m.pt`). + pub fn parse(bytes: &[u8]) -> Result { + Ok(Weights { + tensors: crate::checkpoint::read(bytes)?, + }) } /// The tensor `name` of this shape. @@ -100,17 +47,3 @@ impl Weights { Ok(t.data.clone()) } } - -#[cfg(test)] -mod tests { - use super::f16_to_f32; - - #[test] - fn halves() { - assert_eq!(f16_to_f32(0x3c00), 1.0); - assert_eq!(f16_to_f32(0xc000), -2.0); - assert_eq!(f16_to_f32(0x0000), 0.0); - assert!((f16_to_f32(0x3555) - 0.33325).abs() < 1e-4); - assert!((f16_to_f32(0x0001) - 5.96e-8).abs() < 1e-9); - } -} diff --git a/crates/maia/tests/reference.rs b/crates/maia/tests/reference.rs index 02e0532..1d5318b 100644 --- a/crates/maia/tests/reference.rs +++ b/crates/maia/tests/reference.rs @@ -1,6 +1,6 @@ //! Agreement with the original PyTorch model (tests/reference.json, written by //! scripts/maia-reference.py): the same top moves with close probabilities. Needs the -//! weights: `MAIA_WEIGHTS=/path/maia3-5m.bin cargo test -p maia -- --ignored`. +//! weights: `MAIA_WEIGHTS=/path/maia3-5m.pt cargo test -p maia -- --ignored`. use maia::Maia; use shakmaty::fen::Fen; diff --git a/docs/design/play-mode.md b/docs/design/play-mode.md new file mode 100644 index 0000000..47d58c6 --- /dev/null +++ b/docs/design/play-mode.md @@ -0,0 +1,493 @@ +# Игра с компьютером (Maia): кнопка, диалог, экран игры, конец партии + +Статус: проект дизайнера, 2026-10-25, **не утверждён**. Основа — запрос владельца («Играть»: имя и рейтинг по желанию, сила Maia 600–2600 или от своего рейтинга, цвет, контроль времени как на Lichess, во время игры — только доска и нотация, после — обычная партия) и исследование аналитика `docs/research/play-mode.md` (требования R1–R21, пресеты Lichess, теги PGN, объём v1). Где проект расходится с исследованием, это сказано явно (§10). + +Опирается на код и документы: `apps/desktop/src/library.rs` (`shelf`, `compact_shelf`, `game_buttons`, `shelf_buttons_w`), `game_view.rs` (`show` — решение «рядом/стопка», `header`, `side_panel`, `engine_panel`, `toolbar`, `keyboard`, `game_over`), `library-layout.md` §1.4 (строка заголовка и её сужение), `own-databases.md` §3.2–3.5 (Ctrl+S, «Добавить в базу», вопрос «Партия изменена», «Данные партии»), `narrow-windows.md` (обязательные правила узких окон), `user-comments.md` (стрелки и комментарии), `engine-download.md` (получение движка по запросу). Снимки 0.17-dev: `ef_main.png`, `ef_640.png` (экран партии 1400 и 640), `x_1400.png`, `x_640.png` (библиотека) в scratchpad разработчика `dev2/`. + +Размеры — логические точки egui. Тексты — по-русски, в скобках английский ключ `tr(...)`; существующие помечены «(есть)». Макеты: 1400 — 14 точек на знак (100 знаков), 640 — 10 точек на знак (64 знака), диалог — 10 точек на знак. Значки, которые ломают выравнивание ASCII, названы в тексте. + +## 0. Главное + +1. **Вход** — «⚔ Играть» в строке заголовка библиотеки, между «♟ Новая партия» и «📋 Вставить PGN», клавиша **Ctrl+G** (предложение аналитика; свободна). +2. **Один диалог** «Игра с компьютером»: Вы (имя, рейтинг) → Соперник (Maia 600–2600 и «Слабее · Как я · Сильнее») → Цвет → Время (плитки по категориям, «Свой», «Без часов») → «Играть». Всё запоминается; повторная игра — Ctrl+G, Enter. +3. **Экран игры** — тот же экран партии в режиме игры. Вместо строки движка и вкладок — две карточки часов: соперник вверху, вы внизу, нотация между ними (как на Lichess). Полоса оценки — пустое место (чтобы доска не прыгнула после игры). Панель инструментов: листание, переворот, «↶ Ход назад», «🏳 Сдаться». Всё остальное скрыто, а не серое. +4. **Конец** — экран сразу становится обычной партией (движок, справочник, комментарии, Ctrl+S), а сверху боковой панели — полоса результата: «Вы выиграли · мат» и кнопки «📈 Анализировать», «↻ Реванш», «⚔ Новая игра», «💾 Сохранить в базу…». +5. **Уход во время игры** — один вопрос «Партия идёт» с тремя ответами: «Сдаться и добавить в базу…», «Сдаться и выйти», «Продолжить игру». Пока вопрос открыт, часы стоят. До первых ходов обеих сторон — уход без вопроса. + +## 1. Кнопка «Играть» в библиотеке + +### 1.1. Место + +Группа партий — «что положить на экран»: новая пустая доска, игра, партия из буфера. «Играть» встаёт **второй**: рядом с «Новой партией» (владелец так и описал), но перед «Вставить PGN», которым пользуются реже. + +``` +1400, все подписаны (шаг 1 library-layout.md §1.4) +Базы ♟ Новая партия ⚔ Играть 📋 Вставить PGN + Добавить базу ✚ Новая база 🌐 Онлайн-партии ⚙ Настройки +┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ +│Mine │ │Alekhin │ │Anand 01-14│ │Дворецкий │ +└───────────┘ └───────────┘ └───────────┘ └───────────┘ +``` + +``` +640 (шаг 2: действия баз свёрнуты) +Базы ♟ Новая партия ⚔ Играть 📋 Вставить PGN + ▾ 🌐 ⚙ Настр. +``` + +| Элемент | Подпись | Подсказка | Клавиша | Действие | +|---|---|---|---|---| +| кнопка | «⚔ Играть» (`⚔ Play`) | «Партия с компьютером Maia: он играет как человек выбранного рейтинга (Ctrl+G)» (`A game against Maia, a computer that plays like a human of the chosen rating (Ctrl+G)`) | Ctrl+G (только в библиотеке, как Ctrl+N) | `LibraryAction::Play` → диалог §2 | + +- Вид — обычный `ui.button`, как соседи; не главная кнопка (акцентной заливки в строке нет ни у кого). +- Значок `⚔` (U+2694) — проверить, что он есть в шрифтах программы; если нет — `▶` (U+25B6). Подпись не меняется. + +### 1.2. Сужение + +Порядок шагов `library-layout.md` §1.4 не меняется, «Играть» входит в группу партий: + +1. всё подписано; +2. действия баз → «+ ▾ 🌐»; +3. группа партий и «Настройки» → значки «♟ ⚔ 📋 · ⚙»; подсказка значка начинается с названия («Играть\nПартия с компьютером Maia… (Ctrl+G)», правило `shelf_hint`); +4. скрывается заголовок «Базы». + +- Ширину добавить в `shelf_buttons_w`: тексты `[⚙ Settings, 📋 Paste PGN, ⚔ Play, ♟ New game]` / значки `["⚙", "📋", "⚔", "♟"]`. +- Проверка по `x_640.png`: на шаге 2 справа от «🌐» до «Настройки» свободно ≈ 188 точек, «⚔ Играть» ≈ 75 — при 640 строка остаётся на шаге 2, подписи видны. Измерить на снимке. +- **Компактная полка** — то же: «♟ ⚔ 📋» в той же группе, порядок тот же. +- **Пустая полка** (`library-layout.md` §1.5): строка под карточками — «или ♟ Новая партия — без базы · ⚔ Играть с компьютером» (`or ♟ New game — without a database · ⚔ Play the computer`), две кнопки-ссылки. +- На экране партии кнопки нет: начать игру из открытой партии — через библиотеку или кнопками полосы результата (§5). «Играть отсюда» (с позиции) — не v1. + +## 2. Диалог «Игра с компьютером» + +### 2.1. Вид + +`egui::Modal`, ширина **520** (в узком окне — `min(520, W − 32)`), заголовок «Игра с компьютером» (`Play the computer`). Блоки сверху вниз — в порядке, в котором один влияет на другой: рейтинг задаёт силу соперника. + +``` +┌─ Игра с компьютером ─────────────────────────────────┐ +│ Вы │ +│ Имя [Иванов Сергей ] Рейтинг [1350] │ +│ Не обязательно. По рейтингу подбирается соперник. │ ← слабым +│ │ +│ Соперник — Maia 1400 · как вы │ +│ 600 ━━━━━━━━━━━━━━━━●━━━━━━━━━━━━━━━━━━━━━━━━━ 2600 │ +│ [ Слабее ] [▌Как я▐] [ Сильнее ] │ +│ Maia — нейросеть: ходит как человек этого рейтинга │ ← слабым +│ на Lichess и ошибается так же. │ +│ │ +│ Цвет │ +│ [ ♔ Белые ] [▌◐ Случайно▐] [ ♚ Чёрные ] │ +│ │ +│ Время │ +│ Пуля [ 1+0 ] [ 2+1 ] │ +│ Блиц [ 3+0 ] [ 3+2 ] [ 5+0 ] [▌5+3▐] │ +│ Рапид [10+0 ] [10+5 ] [15+10] │ +│ Классика [30+0 ] [30+20] │ +│ [ Свой… ] [ Без часов ] │ +│ │ +│ [▌Играть▐] [Отмена] │ +└──────────────────────────────────────────────────────┘ +``` + +**Вы** (`You`, заголовок блока — как группы в панели фильтров). +- «Имя» (`Name`) — поле, общее с «Ваше имя» в настройках (`Settings.your_name`, `own-databases.md` §7): одно имя для комментатора и для игры. Подсказка в пустом поле — «как записать в партию» (`as written in the game`). +- «Рейтинг» (`Rating`) — поле 64, только цифры, до 4 знаков; пусто — рейтинга нет. Допустимо 100–3000; вне — красная рамка, подсказка «Рейтинг от 100 до 3000» (`A rating from 100 to 3000`), «Играть» неактивна. Подсказка поля: «Примерно как на Lichess: Maia считает в его рейтингах» (`Roughly your Lichess rating: Maia counts in those`) — до ответа владельца на вопрос аналитика № 1. +- Слабая строка: «Не обязательно. По рейтингу подбирается соперник.» (`Optional. The opponent is matched to your rating.`). +- Хранение: имя и рейтинг пишутся в настройки **при нажатии «Играть»** (не на каждую букву; «Отмена» ничего не меняет). Новое поле `Settings.your_rating: Option`; в «Настройки → Интерфейс → Свои базы» рядом с «Ваше имя» — поле «Ваш рейтинг» (`Your rating`), та же проверка. + +**Соперник** (`Opponent`). +- Заголовок с текущей силой: «Соперник — Maia 1400» (`Opponent — Maia {elo}`); при выбранной относительной силе — «· как вы» / «· на 200 слабее» / «· на 200 сильнее» (`· like you`, `· 200 weaker`, `· 200 stronger`). +- Ползунок 600–2600, шаг 100, подписи концов слабым. Клавиатура: ←/→ — ±100, Home/End — концы. +- Три переключателя «Слабее» (`Weaker`), «Как я» (`Like me`), «Сильнее» (`Stronger`): сила = рейтинг −200 / ±0 / +200, округление до 100, обрезка в 600–2600. **Это режим, а не разовая кнопка:** выбранный переключатель запоминается (`Strength::Relative(−200 | 0 | +200)`), и при изменении рейтинга — сейчас или в следующий раз — сила пересчитывается; ползунок ходит сам. Сдвиг ползунка рукой снимает выбор (`Strength::Fixed(elo)`). +- Без рейтинга переключатели неактивны, подсказка «Укажите свой рейтинг выше» (`Enter your rating above`); сила — по ползунку (впервые 1500). Если рейтинг стёрт при выбранном «Как я» — остаётся последнее значение как фиксированное. +- Слабая строка про Maia — одна на весь диалог; она объясняет, почему «1400» — это «человек», а не уровень 1–8. + +**Цвет** (`Colour`): три переключателя «Белые» (`White`), «Случайно» (`Random`), «Чёрные» (`Black`), 140 × 40. Значок — король из **текущего набора фигур** 20 точек (белый, чёрный, для «Случайно» — разрезанный по диагонали), а не символ шрифта: совпадает с доской и не зависит от глифов. Впервые — «Случайно» (как Lichess). + +**Время** (`Time`): +- Строки по категориям Lichess, подпись категории слева (колонка = ширина самой длинной подписи текущего языка): «Пуля» (`Bullet`) 1+0, 2+1 · «Блиц» (`Blitz`) 3+0, 3+2, 5+0, 5+3 · «Рапид» (`Rapid`) 10+0, 10+5, 15+10 · «Классика» (`Classical`) 30+0, 30+20. Пресеты и категории — исследование §2.1 (`PoolList.scala`, формула `база + 40 × прибавка`). +- Плитка 64 × 36, текст «5+3» 16 точек; выбранная — заливка выделения и жирный (как переключатели «Результат» в фильтрах). Подсказка плитки — «5 минут + 3 секунды за ход» (`5 minutes + 3 seconds a move`). +- Последняя строка: «Свой…» (`Custom…`) и «Без часов» (`No clock`) — шире, по тексту. +- **«Свой»** раскрывает под сеткой два ползунка со шагами Lichess (исследование §2.1) и строку-итог; при выборе другой плитки они исчезают (диалог меняет высоту — допустимо, это ответ на щелчок): + +``` +│ [▌Свой▐] [ Без часов ] │ +│ Минуты ━━━━━━━●━━━━━━━━━━━━━━━━━━━━━━━━━ 7 │ +│ Прибавка ━━●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2 с │ +│ 7+2 · около 8 мин у каждого · рапид │ ← слабым +``` + + - Подписи: «Минуты» (`Minutes`), «Прибавка» (`Increment`), значение справа: «¼», «½», «1½», «7»; «2 с» (`2 s`). Итог: «{tc} · около {n} мин у каждого · {категория}» (`{tc} · about {n} min each · {category}`). + - Значения — последние свои; впервые 7+2. **0+0 нельзя** (как у Lichess): итог «Нужны минуты или прибавка» (`Set minutes or an increment`) красным, «Играть» неактивна. База 0 с прибавкой — можно (начальное время = прибавка, не меньше 3 с, R5). +- **«Без часов»** — часов нет ни у кого; категории в шапке нет. +- Впервые выбрано **10+0**: обычный рапид, спокойный для ученика и не «вечный». Владелец может предпочесть «Без часов» (как у компьютера Lichess) — вопрос §11. +- Пули (1+0, 2+1) в v1 остаются, хотя предварительных ходов нет: в подсказке плиток пули — «Без предварительных ходов это очень быстро» (`Without premoves this is very fast`). Решение владельца — вопрос аналитика № 4. + +**Кнопки**: «Играть» (`Play`) — главная, «Отмена» (`Cancel`, есть); порядок как в `own-databases.md` (главная левее, прижаты вправо). + +### 2.2. Клавиатура и фокус + +- Фокус при открытии — **на «Играть»**: прошлые настройки уже стоят, Enter сразу начинает (сценарий С2). Tab — по блокам сверху вниз; внутри групп переключателей ←/→ меняют выбор. +- Enter в любом месте, включая поля имени и рейтинга, — «Играть» (как «Готово» в «Данных партии»). Esc — «Отмена». +- Щелчок вне окна диалог не закрывает (там поля ввода). + +### 2.3. Запоминание + +`Settings.play` (новое): `strength: Fixed(u16) | Relative(i16)`, `colour: White | Random | Black`, `time: Preset(index) | Custom { minutes_step, increment_step } | NoClock`, `custom` (последние значения ползунков, даже когда выбран пресет). Пишется при «Играть». Первое открытие: 1500, «Случайно», 10+0. + +### 2.4. Состояния + +- **Maia не установлена.** Блоки диалога те же; над кнопками — строка «Для игры нужна Maia (≈ 21 МБ). Скачать один раз.» (`Maia is needed to play (≈ 21 MB). Downloaded once.`), главная кнопка — «Скачать и играть» (`Download and play`). Дальше — состояния окна из `engine-download.md` §2.5–2.8 **в этом же диалоге** (полоса «8 из 21 МБ · 38 %», проверка, ошибки с «Повторить»); после установки партия начинается сама — «запрошенное действие». Без интернета — ошибка §2.8 там же. Как поставляется Maia и в каком виде (вопрос аналитика № 8) — до этого решения макет состояния условный. +- **Maia загружается** (первый запуск в сеансе может занять секунды): диалог закрывается сразу, экран игры открыт, в карточке соперника — «загружается…» (§3.3). Часы ещё не идут (они пойдут после первых ходов), поэтому ожидание ничего не стоит. +- **Не удалось запустить Maia** — экран игры не открывается: диалог остаётся, над кнопками красным «Maia не запустилась: {причина}» (`Maia did not start: {reason}`) и «Подробнее» (сворачиваемый текст ошибки). + +### 2.5. Узкое окно + +- Ширина `min(520, W − 32)`: при 640 — 520, помещается. Сетка времени: колонка подписей ≈ 72 + 4 × (64 + 6) = 352, имя + рейтинг — поле имени гибкое (не уже 160). +- Высота: содержимое ≈ 560 (≈ 620 с раскрытым «Свой»). Если `H − 32` меньше — блоки в `ScrollArea`, **строка кнопок вне прокрутки**, всегда видна. При 640 × 480 прокручивается; при 640 × 900 — нет. + +## 3. Экран игры + +### 3.1. Принцип + +Это **тот же `GameView`** с признаком игры (R6, `play: Option`). Решение «рядом / стопка» — та же функция ширины и высоты окна (`narrow-windows.md` §3.1), **с теми же допущениями** (полоса оценки зарезервирована). Поэтому после конца партии экран не перестраивается: исчезают часы и появляются строка движка и вкладки, доска остаётся на месте (единственное исключение — стопка, §7.2). + +Доска повёрнута стороной пользователя вниз. Место полосы оценки слева от доски — **пустое** (полосы нет, место держится). + +### 3.2. 1400 × 900, рядом + +``` +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ ⬅ Библиотека │ Вы — Maia 1500 [5+3] ⚙ Настройки │ +│ │ Партия с компьютером · блиц │ +├──────────────────────────────────────────────────────────────────┬───────────────────────────────┤ +│ ┌───────────────────────────────────────────────────────────┐ │┌─────────────────────────────┐│ +│ │8 │ ││ ♚ Maia 1500 4:52 ││ ← не её ход: приглушено +│ │ │ ││ ждёт ││ +│ │ │ │└─────────────────────────────┘│ +│ │ │ │ 1 e4 e5 │ +│ │ │ │ 2 Nf3 Nc6 │ +│ │ доска ≈ 832, белые снизу │ │ 3 Bb5 a6 │ +│ │ │ │ 4 Ba4 ▌Nf6▐ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │┌─────────────────────────────┐│ +│ │ │ ││▌♔ Вы · 1350 3:07 ▐││ ← ваш ход: заливка +│ │1 a h │ ││▌ ваш ход ▐││ +│ └───────────────────────────────────────────────────────────┘ │└─────────────────────────────┘│ +│ ↑ место полосы оценки (пусто) │ ⏮ ◀ ▶ ⏭ │ 🔃 │ ↶ Ход назад │ 🏳 Сдаться +└──────────────────────────────────────────────────────────────────┴───────────────────────────────┘ +``` + +Боковая панель (та же `Panel::right("game_side")`, та же ширина, что у обычной партии) сверху вниз: + +1. карточка соперника; +2. нотация (вся оставшаяся высота); +3. строка просмотра (только когда листают назад, §3.6); +4. карточка пользователя; +5. панель инструментов §3.5. + +Карточки у верхнего и нижнего края панели, т. е. примерно на уровне верхнего и нижнего края доски — «соперник напротив, вы у себя», как на Lichess. При перевороте доски (F) карточки меняются местами: сверху всегда тот, чьи фигуры сверху (R9). + +### 3.3. Карточка часов + +Высота 56, на всю ширину панели, скругление и фон как у блока комментария (`ef_main.png`), отступы 8. + +``` +┌─────────────────────────────┐ +│ ♔ Вы · 1350 3:07 │ ← король 18 (набор фигур), имя 15, рейтинг слабым; время моно 30 +│ ваш ход │ ← состояние, 13, слабым +└─────────────────────────────┘ +``` + +- **Имя:** «Вы» (`You`) — в игре это понятнее, чем своё имя; рейтинг слабым после «·», если задан. Соперник — «Maia 1500». +- **Время:** моноширинный шрифт 30 (цифры не прыгают), прижато вправо. Формат `м:сс`; от часа — `ч:мм:сс`; меньше 10 с — десятые: `0:08.4`. Считается по монотонным часам (R10). +- **Состояния** (строка под именем и вид карточки): + +| Состояние | Строка | Вид | +|---|---|---| +| не его ход | «ждёт» (`waiting`) у Maia; у пользователя — пусто | фон панели, время обычным цветом | +| ход пользователя, часы идут | «ваш ход» (`your move`) | заливка выделения (`selection.bg_fill` слабо), время ярким | +| ход Maia | «думает…» (`thinking…`), три точки анимированы | то же выделение | +| до первых ходов | у того, кто ходит: «ваш ход · часы пойдут после первого хода каждой стороны» (`your move · the clocks start after each side's first move`), сокращается с «…»; у Maia — «думает…» | выделение, время полное, не убывает | +| мало времени (`≤ emergSeconds`: 1+0 → 10 с, 3+0 → 22 с, 5+0 → 37 с, ≥ 10+0 → 60 с) | без изменений | время **красным** (`error_fg_color`), рамка карточки красная 1,5 | +| время вышло | «время вышло» (`time is up`) | `0:00` красным; через кадр — конец партии §5 | +| Maia загружается | «загружается…» (`loading…`) | выделение, часы не идут | +| без часов | как выше, но без времени | время не рисуется, имя на всю ширину | + +- Звук при входе в «мало времени»: в наборах звуков программы его нет (`assets/sounds/*`: Move, Capture, Check, Checkmate). В v1 — только вид; звук — когда будет проверенный источник с лицензией (`AGENTS.md`). Звуки ходов, взятий, шаха — как в обычной партии; конец партии — `Checkmate`, если он есть в наборе. +- Maia **не проигрывает по времени** (R15), поэтому красной её карточка практически не бывает; правило одно для обеих. + +### 3.4. Шапка + +``` +⬅ Библиотека │ Вы — Maia 1500 [5+3] ⚙ Настройки + │ Партия с компьютером · блиц +``` + +- Название — белые — чёрные, как всегда, но пользователь назван «Вы»: «Вы — Maia 1500» белыми, «Maia 1500 — Вы» чёрными (`You`). Не кликается (нет «Данных партии» в игре). +- **Чип контроля** «5+3» — на месте чипа результата, тем же видом; «Без часов» — чип «∞» с подсказкой «Без часов» (`No clock`). После конца на этом месте — результат «1-0»: чип не прыгает. +- Подзаголовок: «Партия с компьютером · {категория}» (`Game vs computer · {category}`), без часов — «Партия с компьютером». +- Слева — «⬅ Библиотека» (ведёт к вопросу §6). Справа — только «⚙ Настройки» (вид доски и звук можно менять, часы при этом идут). **Скрыты:** «🔍 Найти в базе», «⏷», «⚠/ℹ заметки», «•» несохранённой партии, «⬅ К партии …». + +### 3.5. Панель инструментов + +``` +⏮ ◀ ▶ ⏭ │ 🔃 │ ↶ Ход назад │ 🏳 Сдаться +``` + +| Кнопка | Подпись / подсказка | Клавиша | Когда активна | +|---|---|---|---| +| ⏮ ◀ ▶ ⏭ | как сейчас (есть) | Home ← → End, ↓ ↑ | всегда; только просмотр (§3.6) | +| 🔃 | «Перевернуть доску (F)» (есть) | F | всегда | +| ↶ Ход назад | «Взять ход назад (Ctrl+Z)» (`Take back a move (Ctrl+Z)`) | Ctrl+Z | после первого хода пользователя | +| 🏳 Сдаться | «Сдаться» (`Resign`) | нет (чтобы не сдаться случайно) | после первых ходов обеих сторон; до них на этом месте «✕ Прервать» (`✕ Abort`, подсказка «Выйти без результата: ходы ещё не сделаны» — `Leave without a result: no moves made yet`) | + +- **Ход назад** (R21, предложение аналитика принято для v1 — всегда разрешён): если ход пользователя — снимаются ответ Maia и предыдущий ход пользователя; если Maia думает — снимается ход пользователя, её расчёт отбрасывается (R14). Часы не возвращаются. Ходы удаляются, а не становятся вариантом. Если пользователь чёрными и есть только первый ход Maia — неактивна. +- **Сдаться** — подтверждение на месте, без окна (часы идут, модальное окно здесь лишнее): кнопка превращается в «Сдаться? [Да] [Нет]» (`Resign? [Yes] [No]`), «Да» — красной заливкой. Отмена — «Нет», Esc, ход любой стороны или 4 с без действия. «Да» → конец §5. +- **Прервать** — без подтверждения (терять нечего): экран закрывается, возврат в библиотеку, партия не сохраняется (R20). +- Скрыты (не серые): ↩ ↪, ☰, 💾, 📋, 📈. Группы переносятся по `narrow-windows.md` §4a; группа «↶ Ход назад · 🏳 Сдаться» — одна, при ширине панели меньше её подписанной ширины кнопки становятся значками «↶ 🏳» с подписями в подсказках. + +### 3.6. Нотация и просмотр + +- Нотация — та же таблица «№ · белые · чёрные», только главная линия, **только чтение**: щелчок по ходу показывает позицию; правый щелчок по ходу меню не открывает; Enter, 1–6, двойной щелчок ничего не делают. Последний ход выделен, нотация прокручена к нему. +- **Листание назад** не мешает игре: часы идут. Под нотацией появляется строка «Просмотр: 12…Nf6 · к игре — End» (`Viewing 12…Nf6 · back to the game — End`), слабым, вся строка — ссылка. Попытка хода в прошлой позиции не делает хода: доска возвращается к текущей позиции (фигура на место). Ход Maia возвращает к текущей позиции сам — его нужно увидеть. +- Во время хода Maia фигуры пользователя не перетаскиваются (предварительных ходов в v1 нет); курсор обычный. +- **Стрелки и выделения правой кнопкой** работают, но **в партию не пишутся**: они временные и стираются следующим ходом (как на Lichess). Иначе каждая стрелка становилась бы комментарием `[%cal]` в сыгранной партии. + +### 3.7. Что скрыто и что делают клавиши + +| Во время игры нет | Клавиша | Что при нажатии | +|---|---|---| +| строка движка, линии, стрелки движка, полоса оценки | L | тост «Во время партии движок выключен — анализ после конца» (`The engine is off during the game — analyse after it ends`) | +| «Анализ партии», график, вкладка «Отчёт» | Shift+A | тот же тост | +| вкладка «Справочник» (вкладок нет вовсе) | — | — | +| «Найти в базе» | Ctrl+Shift+F | ничего | +| редактор комментариев и значков, варианты | Enter, 1–6, Shift+↑/↓ | ничего | +| «Данные партии», сохранение, копирование | F2, Ctrl+S, Ctrl+Shift+S, Ctrl+Shift+C | ничего | +| отмена правок | Ctrl+Z / Ctrl+Y | Ctrl+Z = «Ход назад»; Ctrl+Y — ничего | +| перевод комментариев | Ctrl+Shift+T | ничего | +| — | Esc, Ctrl+W | вопрос «Партия идёт» (§6); если открыт «Сдаться? Да/Нет» — Esc сначала закрывает его | + +Тост только для L и Shift+A: эти клавиши жмут по привычке и должны получить ответ; остальные просто молчат. + +### 3.8. Сбой Maia + +Если процесс Maia завершился или не ответил за таймаут: часы обеих сторон **останавливаются** (вина программы, не игрока), над карточкой соперника — блок: + +``` +┌─────────────────────────────┐ +│ Maia перестала отвечать. │ +│ [Перезапустить] [Прервать] │ +└─────────────────────────────┘ +``` + +`Maia stopped responding.` · `Restart` (новый процесс, позиция передаётся всей историей ходов, R12; часы продолжают с того же места) · `Abort` (партия заканчивается без результата `*`, экран становится обычной партией; её можно сохранить, `Termination "Unterminated"`). + +## 4. Окно и система во время игры + +- Свёрнутое окно, другое окно в фокусе — часы идут (как на Lichess); Maia ходит, звук хода есть. +- Сон компьютера — по исследованию, критерий 9: фактическое поведение зафиксировать при проверке. +- Окно «Настройки» поверх игры — часы идут. + +## 5. Конец партии + +### 5.1. Что происходит + +В один кадр: +1. результат пишется в документ и теги (исследование §5: `Result`, `Termination`, `TimeControl`, `WhiteElo/BlackElo`, `WhiteType/BlackType`, `[%clk]`), признак игры снимается; +2. экран становится **обычной новой партией**: в боковой панели — строка «Анализ: выкл», вкладки «Нотация · Справочник · Отчёт», полная панель инструментов; шапка — настоящие имена «Иванов Сергей — Maia 1500», чип результата «0-1», «•» несохранённой партии, название снова открывает «Данные партии»; подзаголовок — «Партия с компьютером, блиц · 2026.10.25» (из тегов `Event`, `Date`); +3. сверху боковой панели — **полоса результата**; +4. звук конца (если есть в наборе); курсор — на последнем ходе. + +Движок сам не включается (L, как всегда). Место полосы оценки уже было, доска не двигается. + +### 5.2. Полоса результата + +``` +1400 × 900, после конца +├──────────────────────────────────────────────────────────────────┬───────────────────────────────┤ +│ ┌───────────────────────────────────────────────────────────┐ │┌─────────────────────────────┐│ +│ │ │ ││ [0-1] Вы проиграли ││ ← 17, жирным +│ │ │ ││ время вышло ││ +│ │ │ ││ Осталось: вы 0:00 · Maia 2:41│ ← слабым +│ │ │ ││ [▌📈 Анализировать▐] [↻ Реванш]│ +│ │ доска (не сдвинулась) │ ││ [⚔ Новая игра] [💾 Сохранить в базу…] ×│ +│ │ │ │└─────────────────────────────┘│ +│ │ │ │ Анализ: выкл · Stockfish 19 ⚙│ +│ │ │ │ [Нотация] Справочник Отчёт │ +│ │ │ │ 1 e4 e5 │ +│ │ │ │ … │ +│ └───────────────────────────────────────────────────────────┘ │ ⏮ ◀ ▶ ⏭ │ 🔃 ↩ ↪ │ ☰ 💾 📋 │ 📈 │ +└──────────────────────────────────────────────────────────────────┴───────────────────────────────┘ +``` + +Тексты: чип результата + заголовок + причина. Заголовок — с точки зрения пользователя: + +| Исход | Чип | Заголовок | Причина | +|---|---|---|---| +| мат Maia | 1-0 / 0-1 | «Вы выиграли» (`You won`) | «мат» (`checkmate`) | +| мат пользователю | | «Вы проиграли» (`You lost`) | «мат» | +| время пользователя вышло | | «Вы проиграли» | «время вышло» (`time is up`) | +| время вышло, у Maia нечем матовать | ½-½ | «Ничья» (`Draw`) | «время вышло, но у Maia нечем поставить мат» (`time is up, but Maia cannot checkmate`) | +| сдача | | «Вы сдались» (`You resigned`) | — | +| пат | ½-½ | «Ничья» | «пат» (`stalemate`) | +| повторение | ½-½ | «Ничья» | «позиция повторилась трижды» (`the position occurred three times`) | +| 50 ходов | ½-½ | «Ничья» | «50 ходов без взятий и ходов пешек» (`50 moves without a capture or a pawn move`) | +| мало материала | ½-½ | «Ничья» | «ни у кого нет материала для мата» (`neither side can checkmate`) | +| прервано из-за сбоя (§3.8) | * | «Партия прервана» (`Game aborted`) | — | + +- «Осталось: вы {t} · Maia {t}» (`Left: you {t} · Maia {t}`) — итог часов; без часов строки нет. +- Кнопки (переносятся по ширине, главная — первая): + - **«📈 Анализировать»** (`📈 Analyse`) — главная. То же, что 📈 / Shift+A: окно «Анализ партии» с прошлыми настройками, Enter запускает; без Stockfish — предложение скачать (`engine-download.md` §1.2). Отдельного пути анализа нет. + - **«↻ Реванш»** (`↻ Rematch`), подсказка «Те же настройки, цвета меняются» (`Same settings, colours swapped`). При «Случайно» — снова случайно. + - **«⚔ Новая игра»** (`⚔ New game`) — диалог §2 с прошлыми настройками. Название отличается от «Новой партии» (пустая доска), значок тот же, что у «Играть». + - **«💾 Сохранить в базу…»** (`💾 Save to a database…`), подсказка «Ctrl+S». Поток `own-databases.md` §3.3: список баз → «Данные партии» в режиме добавления, предзаполнены (имена, Эло, дата, результат, турнир «Партия с компьютером, блиц») → дубль → запись. После записи кнопка становится текстом «✓ В «Мои партии», № 13» (`✓ In “{name}”, No. {n}`). + - **×** — убрать полосу. +- Полоса держится, пока её не закрыли, пока пользователь не начал править партию (ход, комментарий, данные) или не ушёл. Анализ полосу не убирает. +- **Реванш и Новая игра заменяют несохранённую партию**, поэтому перед заменой — обычный вопрос `own-databases.md` §3.4 «Партия изменена · Добавить партию в свою базу?» («Добавить в базу…» / «Не сохранять» / «Отмена»). Для «Новой игры» вопрос задаётся **при нажатии «Играть»** в диалоге (отмена диалога ничего не теряет); «Отмена» в вопросе возвращает к диалогу. +- Автосохранения нет: как у «Новой партии», запись — явное действие (исследование, вопрос № 9). + +## 6. Уход во время игры + +Поводы: «⬅ Библиотека», Esc, Ctrl+W, закрытие окна программы. + +- **До первых ходов обеих сторон** — ухода не спрашиваем: партия прерывается без результата и не сохраняется (R20). +- **Иначе** — вопрос; пока он открыт, **часы обеих сторон стоят и Maia не ходит** (ответ, пришедший за это время, держится до закрытия вопроса и применяется только при «Продолжить игру»): + +``` +┌─ Партия идёт ──────────────────────────────────────────────┐ +│ Вы — Maia 1500 · 5+3 · 24-й ход │ ← слабым +│ Если выйти, партия закончится вашей сдачей. │ +│ │ +│ [Сдаться и добавить в базу…] [Сдаться и выйти] [Продолжить игру] │ +└────────────────────────────────────────────────────────────┘ +``` + +- Заголовок «Партия идёт» (`The game is on`); текст «Если выйти, партия закончится вашей сдачей.» (`If you leave, the game ends with your resignation.`). Modal 460, `confirm_dialog` по образцу §3.4. +- «Сдаться и добавить в базу…» (`Resign and add to a database…`) — результат «сдача», затем поток «Добавить в базу» (§5.2); после записи уход продолжается (`close_after_save`); «Отмена» в нём — партия уже закончена, экран остаётся на сыгранной партии с полосой результата (уход не продолжается, ничего не потеряно). +- «Сдаться и выйти» (`Resign and leave`) — результат пишется, партия не сохраняется, уход (или закрытие программы). +- «Продолжить игру» (`Keep playing`) — Esc; часы продолжают. +- Enter **ничего не нажимает** (вопрос появляется от Esc — как в `own-databases.md` §3.4). +- При закрытии программы — тот же вопрос; второй вопрос «Партия изменена» не задаётся: этот уже спросил про базу. + +## 7. Узкие окна + +Обязательные правила `narrow-windows.md` действуют без исключений; ниже — только то, что добавляет игра. + +### 7.1. Рядом (640 × 480, 800 × 1000, 960 × 1050) + +- Боковая панель не уже `SIDE_MIN` = 240: карточка (имя сокращается с «…», время 30 моно не сокращается) + нотация + карточка + панель инструментов в две строки по группам: «⏮ ◀ ▶ ⏭ │ 🔃» / «↶ Ход назад │ 🏳 Сдаться» (при нехватке — «↶ 🏳»). +- 640 × 480: высота под шапкой ≈ 430 → карточки 2 × 56, панель 2 × 44, нотации ≈ 220 (7 строк). Состояние «до первых ходов» сокращается с «…», полное — в подсказке. +- Шапка: правило `narrow-windows.md` §3.4 — «⬅» и «⚙» значками, название «Вы — Maia 1500» сокращается, чип «5+3» виден всегда. +- Полоса результата в панели 240: «📈 Анализировать» — отдельная строка, затем «↻ Реванш · ⚔ Новая игра», затем «💾 Сохранить в базу…»; × — в строке заголовка полосы. + +### 7.2. Стопка (640 × 900, 640 × 1000, 720 × 1000) + +При 640 × 900 решение §3.1: `board_side` = 350, `board_stack` = 584 ≥ 1,25 × 350 → стопка. Карточки здесь — **полосы над и под доской** (в центральной панели, ширина доски с местом полосы оценки), а не в нижней панели: «соперник напротив» должен быть у доски. + +``` +640 × 900, игра +┌──────────────────────────────────────────────────────────────┐ +│ ⬅ │ Вы — Maia 1500 [5+3] ⚙ │ +│ │ Партия с компьютером · блиц │ +├──────────────────────────────────────────────────────────────┤ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ ♚ Maia 1500 · думает… 4:52 │ │ ← полоса 36, выделение (её ход) +│ └──────────────────────────────────────────────────────┘ │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ доска ≈ 504 │ │ +│ │ │ │ +│ └──────────────────────────────────────────────────────┘ │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ ♔ Вы · 1350 3:07 │ │ ← полоса 36 +│ └──────────────────────────────────────────────────────┘ │ +├═════════════════════ разделитель (тянуть) ═══════════════════┤ +│ 1 │ e4 e5 │ +│ 2 │ Nf3 Nc6 │ +│ 3 │ Bb5 ▌a6▐ │ +│ … │ +│ ⏮ ◀ ▶ ⏭ │ 🔃 │ ↶ Ход назад │ 🏳 Сдаться │ +└──────────────────────────────────────────────────────────────┘ +``` + +- Полоса-карточка — одна строка 36: король, имя, «· состояние» слабым, время моно 24 справа. Состояния и цвета — как §3.3. +- Нижняя панель — нотация + панель инструментов; высота по умолчанию — как у обычной стопки (`STACK_BOTTOM_MIN` и далее по §3.3 `narrow-windows.md`), т. е. нотации достаётся больше строк, чем в обычной партии (нет строки движка и вкладок). +- Доска = `min(W − 16 − EVAL_BAR, высота центральной части − 2 × 40)`, не меньше `BOARD_MIN`. +- **После конца** полосы часов исчезают, доска вырастает на ≈ 80 — один раз, по событию «партия окончена», а не от размера окна; это допустимо (правило «без мигания» касается изменения размеров окна). Полоса результата — первой строкой нижней панели, кнопки в одну-две строки. + +``` +640 × 900, после конца +├──────────────────────────────────────────────────────────────┤ +│ ▌┌────────────────────────────────────────────────────┐ │ +│ ▌│ доска ≈ 584 │ │ +│ ▌└────────────────────────────────────────────────────┘ │ +├═════════════════════════════════════════════════════════════─┤ +│ [0-1] Вы проиграли · время вышло · вы 0:00 · Maia 2:41 × │ +│ [▌📈 Анализировать▐] [↻ Реванш] [⚔ Новая игра] [💾 Сохранить…]│ +│ Анализ: выкл · Stockfish 19 ⚙ │ +│ [Нотация] Справочник Отчёт │ +│ 1 │ e4 e5 │ +└──────────────────────────────────────────────────────────────┘ +``` + +### 7.3. Диалоги + +- «Игра с компьютером» — §2.5. +- «Партия идёт» — ширина `min(460, W − 32)`; три кнопки при нехватке переносятся (каждая на свою строку, по ширине окна, главная сверху). + +## 8. Клавиатура — сводка + +| Клавиша | Где | Действие | Сегодня | +|---|---|---|---| +| Ctrl+G | библиотека | диалог «Игра с компьютером» | свободна | +| Enter / Esc | диалог | «Играть» / «Отмена» | — | +| ← → Home End ↑ ↓ | игра | просмотр ходов | как в партии | +| F | игра | перевернуть доску (карточки меняются местами) | как в партии | +| Ctrl+Z | игра | взять ход назад | в партии — отмена правки | +| Esc, Ctrl+W | игра | закрыть «Сдаться? Да/Нет», иначе вопрос «Партия идёт» | в партии — в библиотеку | +| L, Shift+A | игра | тост «Во время партии движок выключен…» | движок / анализ | +| Ctrl+S | после конца | «Добавить в базу…» | как в партии | + +## 9. Что строит разработчик (компоненты) + +1. `library.rs`: кнопка в `game_buttons`, ширина в `shelf_buttons_w`, `LibraryAction::Play`, Ctrl+G; строка пустой полки. +2. Новый модуль диалога (`play_dialog.rs`): §2, `Settings.play`, `Settings.your_rating`, поле «Ваш рейтинг» в настройках; состояние «Maia не установлена» — переиспользовать окно загрузки `engine-download.md`. +3. `GameView`: `play: Option` (настройки, часы, состояние Maia, подтверждение сдачи); в `show()` — та же функция «рядом/стопка»; `side_panel` в игре — карточки + нотация только для чтения + строка просмотра; в стопке — полосы в `board_area`; `header`, `toolbar`, `keyboard` — ветки игры по таблицам §3.4–3.7; полоса оценки — место без полосы. +4. Часы и Maia — по исследованию (R10, R12–R16); ответ на устаревшую позицию отбрасывается. +5. Конец: определение повторения и 50 ходов (сейчас `game_over` их нет), теги и `[%clk]`, полоса результата §5.2, переход в обычный режим. +6. Вопрос §6 в `app.rs` рядом с `confirm_dialog`, пауза часов на время вопроса. + +## 10. Расхождения с исследованием + +- Порядок блоков диалога: аналитик — Вы, Цвет, Время, Соперник; здесь — Вы, **Соперник**, Цвет, Время: сила зависит от рейтинга и должна быть рядом с ним; самый большой блок (время) — последним, у кнопки. +- Сетка пресетов — **строками по категориям** (запрос владельца «по группам»), а не 4 × 3 с подписью под плиткой. +- «Слабее · Как я · Сильнее» — запоминаемый режим, а не разовые кнопки (смысл «относительно моего рейтинга»). +- Часы — в боковой панели у краёв (рядом) и полосами у доски (стопка), а не только «у доски». +- Уход: одна форма с «Сдаться и добавить в базу…» вместо цепочки «Сдаться и выйти» → «Партия изменена»; «Прервать» — кнопкой на панели до первых ходов, а не в вопросе (до первых ходов вопроса нет). +- Пока открыт вопрос ухода — часы стоят (в исследовании не оговорено). +- Стрелки в игре временные, в партию не пишутся (R7 этого не уточнял). +- «Без часов» вместо «Без времени» (слово владельца). + +## 11. Вопросы владельцу + +1. Контроль по умолчанию при первом открытии: **10+0** (предлагаю) или «Без часов», как у компьютера Lichess? +2. Названия «Ещё раз» (аналитик) или «Реванш» (предлагаю, слово владельца и Lichess)? +3. Ctrl+G для «Играть» — подходит? +4. Остальные вопросы — исследование §8 (шкала рейтинга, пули без premove, язык `Event`, поставка и лицензия Maia); от них зависят подписи поля «Рейтинг», подсказка пуль и состояние «Maia не установлена». + +## 12. Проверки для тестировщика (план, не выполнено) + +1. Библиотека 1400 / 960 / 640: «⚔ Играть» на своём месте, подписана; при сужении — значок с подсказкой; Ctrl+G открывает диалог. +2. Диалог: Enter сразу играет с прошлыми настройками; рейтинг 99/3001 — красная рамка и «Играть» неактивна; «Как я» при 1350 → 1400, после смены рейтинга на 1720 при следующем открытии — 1700; сдвиг ползунка снимает «Как я»; «Свой» 0+0 — нельзя; 7+2 → «рапид»; при 640 × 480 строка кнопок видна, содержимое прокручивается. +3. Отмена диалога не меняет имя и рейтинг в настройках. +4. Экран игры: нет строки движка, вкладок, полосы оценки (но место есть), «Найти в базе», ☰, 💾; L и Shift+A — тост; F2, Ctrl+S, Enter, 1–6 — ничего; Ctrl+Z — ход назад. +5. Чёрными: доска чёрными снизу, Maia ходит первой, карточка Maia сверху; F — карточки меняются местами. +6. Листание назад во время своего хода: часы идут, строка «Просмотр…», попытка хода возвращает к текущей позиции без хода; ход Maia возвращает к текущей позиции. +7. 3+0: при 0:22 часы краснеют; < 10 с — десятые; 0:00 — конец «Вы проиграли · время вышло». +8. «Сдаться» → «Сдаться? Да/Нет»; Esc/4 с/ход отменяют; «Да» — конец. +9. Конец: в тот же кадр — обычная партия, доска (рядом) не сдвинулась; полоса результата; Ctrl+S → «Добавить в базу», данные предзаполнены; «Реванш» с несохранённой партией спрашивает. +10. Esc во время игры: вопрос, часы стоят, Maia не ходит; «Продолжить» — всё продолжается с того же времени; закрытие окна — тот же вопрос, без второго. +11. Esc до первых ходов — выход без вопроса; «✕ Прервать» до первых ходов. +12. Стопка 640 × 900: полосы часов над и под доской; после конца полосы уходят, доска растёт один раз; при медленном изменении размера окна во время игры компоновка переключается там же, где у обычной партии. +13. Сбой Maia (убить процесс): часы стоят, блок «Maia перестала отвечать», «Перезапустить» продолжает партию. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 912c15d..7669d46 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -51,7 +51,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_COMMENT_EDIT=1` — открыть редактор комментария на текущем ходе, `CP_SHAPE=Ge2e4,Rd5` — нарисовать стрелки/круги на доске у текущего хода (как правой кнопкой), `CP_TYPE=текст` — напечатать текст в поле с фокусом через 2,5 с (после `CP_KEYS`, которые начинаются со 2-й секунды, если их мало), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_COMMENT_EDIT=1` — открыть редактор комментария на текущем ходе, `CP_SHAPE=Ge2e4,Rd5` — нарисовать стрелки/круги на доске у текущего хода (как правой кнопкой), `CP_TYPE=текст` — напечатать текст в поле с фокусом через 2,5 с (после `CP_KEYS`, которые начинаются со 2-й секунды, если их мало), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_PLAY=white|black[,5+3|none][,1500]` — сразу начать партию с Maia (`CP_PLAY=dialog` — открыть диалог «Игра с компьютером»), `CP_MAIA=путь/maia3-5m.pt` — веса Maia из этого файла вместо скачанных, `CP_PLAY_AUTO=1` — за пользователя тоже ходит Maia, быстро (партия до конца без мыши), `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки diff --git a/scripts/maia-convert.py b/scripts/maia-convert.py deleted file mode 100755 index 0fb6ea4..0000000 --- a/scripts/maia-convert.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 -"""Reads a PyTorch .pt (zip + pickle) without torch and writes our weights file: -magic b'MAIA3W02', u32 count, then per tensor: u16 name len, name, u8 ndim, u32 dims..., u64 offset; -then aligned f16 little-endian data. Usage: convert.py in.pt out.bin""" -import pickle, struct, sys, zipfile, collections - -src, dst = sys.argv[1], sys.argv[2] -z = zipfile.ZipFile(src) -root = z.namelist()[0].split('/')[0] -pkl = z.read(f'{root}/data.pkl') - -class Storage: - def __init__(self, key, dtype): self.key, self.dtype = key, dtype - -def rebuild(storage, offset, size, stride, *rest): - return ('T', storage, offset, tuple(size), tuple(stride)) - -class U(pickle.Unpickler): - def find_class(self, mod, name): - if mod == 'torch._utils' and name == '_rebuild_tensor_v2': return rebuild - if mod == 'torch' and name.endswith('Storage'): return name - if mod == 'collections' and name == 'OrderedDict': return collections.OrderedDict - if mod == 'torch._utils' and name == '_rebuild_parameter': - return lambda t, *a: t - raise pickle.UnpicklingError(f'refused {mod}.{name}') - def persistent_load(self, pid): - _, dtype, key, loc, numel = pid - return Storage(key, dtype) - -obj = U(__import__('io').BytesIO(pkl)).load() -sd = obj['model_state_dict'] if isinstance(obj, dict) and 'model_state_dict' in obj else obj -out = [] -for name, t in sd.items(): - if not (isinstance(t, tuple) and t and t[0] == 'T'): continue - _, st, off, size, stride = t - assert st.dtype == 'FloatStorage', (name, st.dtype) - raw = z.read(f'{root}/data/{st.key}') - n = 1 - for d in size: n *= d - # contiguous check - exp = []; acc = 1 - for d in reversed(size): exp.append(acc); acc *= d - assert tuple(reversed(exp)) == stride or n <= 1, (name, size, stride) - data = raw[off*4:(off+n)*4] - vals = struct.unpack(f'<{n}f', data) - data = struct.pack(f'<{n}e', *vals) - name = name.replace('smolgen', 'gab') - # The attention-bias weight is one tensor shared by all the layers: kept once. - if '.self_attn.gab_weight' in name: continue - out.append((name, size, data)) -with open(dst, 'wb') as f: - f.write(b'MAIA3W02'); f.write(struct.pack('