From 73593ddfc52290804fa1592e5746b27d871117d7 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 26 Oct 2026 03:02:55 +0300 Subject: [PATCH] Play: Rodent V as an opponent (desktop): downloaded on request, strength and style MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dialog (docs/design/rodent-opponent.md): «Maia · Rodent V» tiles, one strength slider for both (Maia's zone marked; past it Rodent is chosen at once), Rodent's style (Balanced, Attacking, Chaotic, Restricting, Classical, Tal, Tal (network)) always in its place, greyed for Maia. Rodent V 1.2 (the authors' release, pinned SHA-256) is downloaded and unpacked with its personalities, nets and books; it plays through UCI at UCI_Elo from the measured table (provisional until the measurement ends), with its book, after Maia's human pause. Its own texts where Russian makes Maia «she» and Rodent «he». The download helper is shared with Stockfish's. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 6 +- apps/desktop/src/engine_download.rs | 26 +- apps/desktop/src/game_view.rs | 148 ++++-- apps/desktop/src/i18n.rs | 542 ++++++++++++++++++++++ apps/desktop/src/main.rs | 1 + apps/desktop/src/play.rs | 669 +++++++++++++++++++++++++--- apps/desktop/src/rodent_download.rs | 189 ++++++++ crates/mobile-api/src/play.rs | 16 +- crates/play/src/lib.rs | 10 +- docs/design/rodent-opponent.md | 170 +++++++ 10 files changed, 1660 insertions(+), 117 deletions(-) create mode 100644 apps/desktop/src/rodent_download.rs create mode 100644 docs/design/rodent-opponent.md diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 1a47ae8..3e67bfc 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -484,6 +484,8 @@ impl App { crate::play::Start { user, strength, + rival: crate::play::debug_rival().0, + style: crate::play::debug_rival().1, user_elo: self.settings.rating, user_name: self.settings.your_name.clone(), clock, @@ -597,6 +599,8 @@ impl App { match user { Some(user) => { self.debug.play_from = Some(crate::play::Start { + rival: crate::play::debug_rival().0, + style: crate::play::debug_rival().1, user, strength, user_elo: self.settings.rating, @@ -1404,7 +1408,7 @@ impl App { /// A new game against Maia. Her model missing (a rematch, a game from a position): /// the dialog with the same choices, to download it. fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) { - let Ok(maia) = crate::play::model_for(start.strength) else { + let Some(maia) = crate::play::engine_for(&start) else { self.play_dialog = Some(crate::play::Dialog::for_start(&self.settings, &start)); return; }; diff --git a/apps/desktop/src/engine_download.rs b/apps/desktop/src/engine_download.rs index 30347b2..e2defde 100644 --- a/apps/desktop/src/engine_download.rs +++ b/apps/desktop/src/engine_download.rs @@ -14,12 +14,12 @@ use sha2::{Digest, Sha256}; const TAG: &str = "sf_19"; /// An archive of the release for this platform. -struct Asset { - file: &'static str, - sha256: &'static str, +pub struct Asset { + pub file: &'static str, + pub sha256: &'static str, /// Bytes, for the size shown before the download. - size: u64, - zip: bool, + pub size: u64, + pub zip: bool, } fn asset() -> Option { @@ -147,6 +147,16 @@ pub struct Download { impl Download { pub fn start(ctx: &egui::Context) -> Download { let total = asset().map_or(0, |a| a.size); + Download::spawn(ctx, total, run) + } + + /// Runs `job` (a download and what follows it) in a thread of its own; `total`: the + /// bytes expected, shown until the server says. + pub fn spawn( + ctx: &egui::Context, + total: u64, + job: fn(&dyn Fn(Stage), &AtomicBool) -> Result, + ) -> Download { let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0, total })); let cancel = Arc::new(AtomicBool::new(false)); let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone()); @@ -159,7 +169,7 @@ impl Download { } ctx.request_repaint(); }; - let end = match run(&report, &c) { + let end = match job(&report, &c) { Ok(path) => Stage::Done(path), Err(_) if c.load(Ordering::Relaxed) => Stage::Cancelled, Err(f) => Stage::Failed(f), @@ -220,7 +230,7 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result } /// Downloads `url` into `to`, checking the size and the SHA-256 on the way. -fn fetch( +pub fn fetch( url: &str, to: &Path, asset: &Asset, @@ -350,7 +360,7 @@ fn check_runs(exe: &Path) -> Result<(), Failure> { } } -fn disk(e: std::io::Error) -> Failure { +pub fn disk(e: std::io::Error) -> Failure { Failure::Disk(e.to_string()) } diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 8477bdd..57c5b04 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -2098,7 +2098,7 @@ impl GameView { pub fn start_play( &mut self, start: crate::play::Start, - (model, weights): (crate::maia_download::Model, std::path::PathBuf), + (engine, file): (crate::play::Engine, std::path::PathBuf), judge: Option, ctx: &egui::Context, ) { @@ -2122,6 +2122,7 @@ impl GameView { start.user, &start.user_name, start.user_elo, + &start.rival_name(), start.strength, &start.clock.map_or_else(|| "-".to_owned(), |tc| tc.pgn()), ) { @@ -2133,21 +2134,44 @@ impl GameView { Some(from) => { let floor = g.line_end(NodeId::ROOT); let elo = start.strength.to_string(); - let note = match (&from.game, &from.after) { - (Some(game), Some(m)) => trf( - "Continued from {game}, after {move}. From here on, a game against Maia {elo}.", - &[("game", game), ("move", m), ("elo", &elo)], - ), - (None, Some(m)) => trf( - "Continued after {move}. From here on, a game against Maia {elo}.", - &[("move", m), ("elo", &elo)], - ), - (Some(game), None) => trf( - "Continued from {game}. From here on, a game against Maia {elo}.", - &[("game", game), ("elo", &elo)], - ), - (None, None) => { - trf("From here on, a game against Maia {elo}.", &[("elo", &elo)]) + // Rodent's notes name him whole («Rodent V 2400 (Tal)»). + let rodent = start.rival == crate::play::Rival::Rodent; + let name = start.rival_name(); + let note = if rodent { + match (&from.game, &from.after) { + (Some(game), Some(m)) => trf( + "Continued from {game}, after {move}. From here on, a game against {name}.", + &[("game", game), ("move", m), ("name", &name)], + ), + (None, Some(m)) => trf( + "Continued after {move}. From here on, a game against {name}.", + &[("move", m), ("name", &name)], + ), + (Some(game), None) => trf( + "Continued from {game}. From here on, a game against {name}.", + &[("game", game), ("name", &name)], + ), + (None, None) => { + trf("From here on, a game against {name}.", &[("name", &name)]) + } + } + } else { + match (&from.game, &from.after) { + (Some(game), Some(m)) => trf( + "Continued from {game}, after {move}. From here on, a game against Maia {elo}.", + &[("game", game), ("move", m), ("elo", &elo)], + ), + (None, Some(m)) => trf( + "Continued after {move}. From here on, a game against Maia {elo}.", + &[("move", m), ("elo", &elo)], + ), + (Some(game), None) => trf( + "Continued from {game}. From here on, a game against Maia {elo}.", + &[("game", game), ("elo", &elo)], + ), + (None, None) => { + trf("From here on, a game against Maia {elo}.", &[("elo", &elo)]) + } } }; let (nags, mut comments) = g @@ -2170,10 +2194,19 @@ impl GameView { self.play = Some(Session { user: start.user, strength: start.strength, - model, + engine, + style: start.style.clone(), user_elo: start.user_elo, clock: start.clock.map(Clock::new), - opponent: Opponent::start(weights, ctx), + opponent: match engine { + crate::play::Engine::Maia(_) => Opponent::start(file, ctx), + crate::play::Engine::Rodent => Opponent::start_rodent( + file, + start.style.clone(), + crate::play::rodent_elo(start.strength), + ctx, + ), + }, resign_asked: false, judge: judge.map(|p| { let ctx = ctx.clone(); @@ -2240,10 +2273,20 @@ impl GameView { .stroke(egui::Stroke::new(1.0, ui.visuals().selection.bg_fill)) .show(ui, |ui| { ui.set_width(ui.available_width()); - ui.label(RichText::new(tr("Maia resigns")).strong().size(16.0)); + let rival = self + .play + .as_ref() + .map_or(crate::play::Rival::Maia, |s| s.rival()); ui.label( - RichText::new(tr( + RichText::new(crate::play::said(rival, "Maia resigns", "Rodent V resigns")) + .strong() + .size(16.0), + ); + ui.label( + RichText::new(crate::play::said( + rival, "Her position is lost. Accept the win, or play to the end?", + "Its position is lost. Accept the win, or play to the end?", )) .weak(), ); @@ -2265,7 +2308,11 @@ impl GameView { [w, 30.0], egui::Button::new(RichText::new(tr("Play to the end")).size(14.0)), ) - .on_hover_text(tr("Maia plays on and will not offer again in this game")) + .on_hover_text(crate::play::said( + rival, + "Maia plays on and will not offer again in this game", + "Rodent V plays on and will not offer again in this game", + )) .clicked() { choice = Some(false); @@ -2330,10 +2377,8 @@ impl GameView { let elo = s.user_elo.unwrap_or(s.strength); s.opponent.ask( positions, - ( - crate::play::rating_input(s.model, elo), - crate::play::temperature(s.model, elo), - ), + engine_pos.clone(), + s.engine.input(elo), s.strength, std::time::Duration::from_millis(30), ); @@ -2353,11 +2398,9 @@ impl GameView { }; // Her rating input is what makes her play at her strength; the user's is as is. let oppo = s.user_elo.unwrap_or(s.strength); - let own = ( - crate::play::rating_input(s.model, s.strength), - crate::play::temperature(s.model, s.strength), - ); - s.opponent.ask(positions, own, oppo, pause); + let own = s.engine.input(s.strength); + s.opponent + .ask(positions, engine_pos.clone(), own, oppo, pause); // Is her position lost? (Unless the user wants to play to the end.) if !s.play_on && let (Some(j), Some(ep)) = (s.judge.as_mut(), engine_pos) @@ -2465,11 +2508,18 @@ impl GameView { } } if let Some(err) = s.opponent.failed() { - crate::maia_download::forget_broken(s.model); - actions.push(GameAction::Toast(trf( - "Maia did not start: {e}", - &[("e", &err)], - ))); + // A file that does not start is removed: the dialog offers it again. + let text = match s.engine { + crate::play::Engine::Maia(m) => { + crate::maia_download::forget_broken(m); + "Maia did not start: {e}" + } + crate::play::Engine::Rodent => { + let _ = crate::rodent_download::remove(); + "Rodent V did not start: {e}" + } + }; + actions.push(GameAction::Toast(trf(text, &[("e", &err)]))); self.play = None; self.game.mark_saved(); actions.push(GameAction::Back); @@ -2998,7 +3048,7 @@ impl GameView { None => format!("{king} {}", tr("You")), } } else { - format!("{king} Maia {}", s.strength) + format!("{king} {}", s.rival_label()) }; ui.label(RichText::new(name).size(15.0)); let state = if side != user && s.resign_offer.is_some() { @@ -3110,13 +3160,25 @@ impl GameView { // judge, no answer: the button says why). if self.play_started() { let judge = self.play.as_ref().and_then(|s| s.judge.as_ref()); + let rival = self + .play + .as_ref() + .map_or(crate::play::Rival::Maia, |s| s.rival()); let may = judge.is_some_and(|j| j.may_offer_draw()); + let said = |m, r| crate::play::said(rival, m, r); let hint = match judge { - None => { - tr("Maia answers a draw offer with Stockfish's help: none is installed") - } - Some(_) if !may => tr("Maia declined; offer again after two of her moves"), - Some(_) => tr("Maia accepts when her position is no better and has settled"), + None => said( + "Maia answers a draw offer with Stockfish's help: none is installed", + "Rodent V answers a draw offer with Stockfish's help: none is installed", + ), + Some(_) if !may => said( + "Maia declined; offer again after two of her moves", + "Rodent V declined; offer again after two of its moves", + ), + Some(_) => said( + "Maia accepts when her position is no better and has settled", + "Rodent V accepts when its position is no better and has settled", + ), }; if ui .add_enabled(may, word(tr("½ Offer a draw"))) @@ -3132,7 +3194,9 @@ impl GameView { if yes { self.finish_play(crate::play::Ending::DrawAgreed, actions); } else { - actions.push(GameAction::Toast(tr("Maia declines the draw").into())); + actions.push(GameAction::Toast( + said("Maia declines the draw", "Rodent V declines the draw").into(), + )); } } } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 0084d7c..9e6afcd 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -10957,6 +10957,548 @@ const ROWS: &[[&str; 9]] = &[ "Maia durangdan bosh tortadi", "Maia тең ойыннан бас тартады", ], + [ + "Opponent — Rodent V {elo}", + "Соперник — Rodent V {elo}", + "Adversaire — Rodent V {elo}", + "Gegner — Rodent V {elo}", + "Rival — Rodent V {elo}", + "Avversario — Rodent V {elo}", + "Adversário — Rodent V {elo}", + "Raqib — Rodent V {elo}", + "Қарсылас — Rodent V {elo}", + ], + [ + "not yet for macOS", + "пока нет для macOS", + "pas encore pour macOS", + "noch nicht für macOS", + "aún no para macOS", + "non ancora per macOS", + "ainda não para macOS", + "macOS uchun hali yo‘q", + "macOS үшін әзірге жоқ", + ], + [ + "not yet for this system", + "пока нет для этой системы", + "pas encore pour ce système", + "noch nicht für dieses System", + "aún no para este sistema", + "non ancora per questo sistema", + "ainda não para este sistema", + "bu tizim uchun hali yo‘q", + "бұл жүйе үшін әзірге жоқ", + ], + [ + "The authors of Rodent V have no build for this system yet. When there is one, it will be here.", + "У авторов Rodent V ещё нет сборки для этой системы. Когда появится, он будет здесь.", + "Les auteurs de Rodent V n’ont pas encore de version pour ce système. Dès qu’il y en aura une, elle sera ici.", + "Die Autoren von Rodent V haben noch keine Version für dieses System. Sobald es eine gibt, ist sie hier.", + "Los autores de Rodent V aún no tienen versión para este sistema. Cuando la haya, estará aquí.", + "Gli autori di Rodent V non hanno ancora una versione per questo sistema. Quando ci sarà, sarà qui.", + "Os autores do Rodent V ainda não têm versão para este sistema. Quando houver, estará aqui.", + "Rodent V mualliflarida bu tizim uchun hali yig‘ma yo‘q. Paydo bo‘lsa, shu yerda bo‘ladi.", + "Rodent V авторларында бұл жүйеге әзірге нұсқа жоқ. Шыққанда осында болады.", + ], + [ + "Maia plays up to {elo}: the strength is lowered to {elo}.", + "Maia играет до {elo} — сила снижена до {elo}.", + "Maia joue jusqu’à {elo} : la force est ramenée à {elo}.", + "Maia spielt bis {elo}: die Stärke ist auf {elo} gesenkt.", + "Maia juega hasta {elo}: la fuerza baja a {elo}.", + "Maia gioca fino a {elo}: la forza è ridotta a {elo}.", + "A Maia joga até {elo}: a força foi reduzida para {elo}.", + "Maia {elo} gacha o‘ynaydi: kuch {elo} ga tushirildi.", + "Maia {elo} дейін ойнайды: күш {elo} дейін төмендетілді.", + ], + [ + "Rodent V plays from {elo}: the strength is raised to {elo}.", + "Rodent V играет от {elo} — сила поднята до {elo}.", + "Rodent V joue à partir de {elo} : la force est portée à {elo}.", + "Rodent V spielt ab {elo}: die Stärke ist auf {elo} erhöht.", + "Rodent V juega desde {elo}: la fuerza sube a {elo}.", + "Rodent V gioca da {elo}: la forza è alzata a {elo}.", + "O Rodent V joga a partir de {elo}: a força foi elevada para {elo}.", + "Rodent V {elo} dan o‘ynaydi: kuch {elo} ga ko‘tarildi.", + "Rodent V {elo} бастап ойнайды: күш {elo} дейін көтерілді.", + ], + [ + "Stronger than {elo} plays Rodent V: Maia does not play that strong.", + "Сильнее {elo} играет Rodent V: Maia так сильно не играет.", + "Au-delà de {elo}, c’est Rodent V : Maia ne joue pas aussi fort.", + "Stärker als {elo} spielt Rodent V: so stark spielt Maia nicht.", + "Por encima de {elo} juega Rodent V: Maia no juega tan fuerte.", + "Oltre {elo} gioca Rodent V: Maia non gioca così forte.", + "Acima de {elo} joga o Rodent V: a Maia não joga tão forte.", + "{elo} dan kuchliroq Rodent V o‘ynaydi: Maia bunchalik kuchli o‘ynamaydi.", + "{elo}-ден күштірек Rodent V ойнайды: Maia мұндай күшті ойнамайды.", + ], + [ + "Weaker than {elo} plays Maia.", + "Слабее {elo} играет Maia.", + "En dessous de {elo}, c’est Maia.", + "Schwächer als {elo} spielt Maia.", + "Por debajo de {elo} juega Maia.", + "Sotto {elo} gioca Maia.", + "Abaixo de {elo} joga a Maia.", + "{elo} dan kuchsizroq Maia o‘ynaydi.", + "{elo}-ден әлсіздеу Maia ойнайды.", + ], + [ + "Maia can play here too: choose her if you want human mistakes.", + "Здесь может играть и Maia — выберите её, если хотите человечных ошибок.", + "Maia peut aussi jouer ici : choisissez-la pour des erreurs humaines.", + "Hier kann auch Maia spielen: wählen Sie sie für menschliche Fehler.", + "Aquí también puede jugar Maia: elígela si quieres errores humanos.", + "Qui può giocare anche Maia: sceglila per errori umani.", + "Aqui também pode jogar a Maia: escolha-a para erros humanos.", + "Bu yerda Maia ham o‘ynay oladi: insoniy xatolar istasangiz, uni tanlang.", + "Мұнда Maia да ойнай алады: адами қателер керек болса, оны таңдаңыз.", + ], + [ + "Measured strength, on the Lichess blitz scale.", + "Измеренная сила, по шкале блица Lichess.", + "Force mesurée, sur l’échelle du blitz Lichess.", + "Gemessene Spielstärke, auf der Lichess-Blitz-Skala.", + "Fuerza medida, en la escala de blitz de Lichess.", + "Forza misurata, sulla scala del blitz di Lichess.", + "Força medida, na escala de blitz do Lichess.", + "O‘lchangan kuch, Lichess blits shkalasi bo‘yicha.", + "Өлшенген күш, Lichess блиц шкаласы бойынша.", + ], + [ + "Her measured strength, on the Lichess blitz scale. Stronger than {elo}: Rodent V.", + "Её измеренная сила, по шкале блица Lichess. Сильнее {elo} — Rodent V.", + "Sa force mesurée, sur l’échelle du blitz Lichess. Au-delà de {elo} : Rodent V.", + "Ihre gemessene Stärke, Lichess-Blitz-Skala. Stärker als {elo}: Rodent V.", + "Su fuerza medida, escala de blitz de Lichess. Por encima de {elo}: Rodent V.", + "La sua forza misurata, scala blitz di Lichess. Oltre {elo}: Rodent V.", + "A força medida dela, escala de blitz do Lichess. Acima de {elo}: Rodent V.", + "Uning o‘lchangan kuchi, Lichess blits shkalasi. {elo} dan yuqori — Rodent V.", + "Оның өлшенген күші, Lichess блиц шкаласы. {elo}-ден жоғары — Rodent V.", + ], + [ + "Like a human", + "Как человек", + "Comme un humain", + "Wie ein Mensch", + "Como una persona", + "Come un umano", + "Como um humano", + "Odamdek", + "Адам сияқты", + ], + [ + "Style", + "Стиль", + "Style", + "Stil", + "Estilo", + "Stile", + "Estilo", + "Uslub", + "Стиль", + ], + [ + "As a player", + "Как игрок", + "Comme un joueur", + "Wie ein Spieler", + "Como un jugador", + "Come un giocatore", + "Como um jogador", + "O‘yinchidek", + "Ойыншы сияқты", + ], + [ + "The style is chosen for Rodent V", + "Стиль выбирается у Rodent V", + "Le style se choisit pour Rodent V", + "Der Stil wird für Rodent V gewählt", + "El estilo se elige para Rodent V", + "Lo stile si sceglie per Rodent V", + "O estilo é escolhido para o Rodent V", + "Uslub Rodent V uchun tanlanadi", + "Стиль Rodent V үшін таңдалады", + ], + [ + "Maia does not pick a style: she plays like people of her rating.", + "Maia не выбирает стиль: она играет, как люди её рейтинга.", + "Maia ne choisit pas de style : elle joue comme les gens de son niveau.", + "Maia wählt keinen Stil: Sie spielt wie Menschen ihrer Wertung.", + "Maia no elige estilo: juega como la gente de su nivel.", + "Maia non sceglie uno stile: gioca come le persone del suo livello.", + "A Maia não escolhe estilo: joga como as pessoas do nível dela.", + "Maia uslub tanlamaydi: u o‘z reytingidagi odamlardek o‘ynaydi.", + "Maia стиль таңдамайды: ол өз рейтингіндегі адамдар сияқты ойнайды.", + ], + [ + "Balanced", + "Сбалансированный", + "Équilibré", + "Ausgewogen", + "Equilibrado", + "Equilibrato", + "Equilibrado", + "Muvozanatli", + "Теңгерімді", + ], + [ + "Attacking", + "Атакующий", + "Offensif", + "Angriffslustig", + "Atacante", + "Offensivo", + "Atacante", + "Hujumkor", + "Шабуылшыл", + ], + [ + "Chaotic", + "Хаотичный", + "Chaotique", + "Chaotisch", + "Caótico", + "Caotico", + "Caótico", + "Tartibsiz", + "Ретсіз", + ], + [ + "Restricting", + "Сковывающий", + "Étouffant", + "Einengend", + "Restrictivo", + "Soffocante", + "Restritivo", + "Siqib qo‘yuvchi", + "Қысып тастайтын", + ], + [ + "Tal", "Таль", "Tal", "Tal", "Tal", "Tal", "Tal", "Tal", "Таль", + ], + [ + "Tal (network)", + "Таль (сеть)", + "Tal (réseau)", + "Tal (Netz)", + "Tal (red)", + "Tal (rete)", + "Tal (rede)", + "Tal (tarmoq)", + "Таль (желі)", + ], + [ + "Even, all-round play with no bias.", + "Ровная универсальная игра, без перекосов.", + "Jeu régulier et polyvalent, sans parti pris.", + "Gleichmäßiges, vielseitiges Spiel ohne Vorlieben.", + "Juego regular y versátil, sin sesgos.", + "Gioco regolare e completo, senza sbilanciamenti.", + "Jogo regular e versátil, sem desvios.", + "Bir tekis, har tomonlama o‘yin, og‘ishsiz.", + "Біркелкі, жан-жақты ойын, бұрмаланусыз.", + ], + [ + "Active pieces and attack, sound pawn structure.", + "Активные фигуры и атака, крепкая пешечная структура.", + "Pièces actives et attaque, structure de pions saine.", + "Aktive Figuren und Angriff, gesunde Bauernstruktur.", + "Piezas activas y ataque, estructura de peones sólida.", + "Pezzi attivi e attacco, struttura pedonale sana.", + "Peças ativas e ataque, estrutura de peões sólida.", + "Faol donalar va hujum, mustahkam piyoda tuzilmasi.", + "Белсенді фигуралар мен шабуыл, мықты пешка құрылымы.", + ], + [ + "Aggressive, tricky openings, careless with pawns.", + "Агрессия и хитрые дебюты, пешки не бережёт.", + "Agressif, ouvertures pièges, peu soucieux des pions.", + "Aggressiv, trickreiche Eröffnungen, sorglos mit Bauern.", + "Agresivo, aperturas tramposas, descuidado con los peones.", + "Aggressivo, aperture insidiose, poco attento ai pedoni.", + "Agressivo, aberturas traiçoeiras, descuidado com os peões.", + "Tajovuzkor, ayyorona debyutlar, piyodalarni ayamaydi.", + "Агрессивті, айлалы дебюттер, пешкаларды аямайды.", + ], + [ + "Closed positions, cramping the opponent, old openings.", + "Закрытые позиции, стеснение соперника, старые дебюты.", + "Positions fermées, étouffer l’adversaire, ouvertures anciennes.", + "Geschlossene Stellungen, den Gegner einengen, alte Eröffnungen.", + "Posiciones cerradas, ahogar al rival, aperturas antiguas.", + "Posizioni chiuse, soffocare l’avversario, aperture antiche.", + "Posições fechadas, sufocar o adversário, aberturas antigas.", + "Yopiq pozitsiyalar, raqibni siqish, eski debyutlar.", + "Жабық позициялар, қарсыласты қысу, ескі дебюттер.", + ], + [ + "Hand-written evaluation, no neural network.", + "Оценка, написанная вручную, без нейросети.", + "Évaluation écrite à la main, sans réseau de neurones.", + "Handgeschriebene Bewertung, kein neuronales Netz.", + "Evaluación escrita a mano, sin red neuronal.", + "Valutazione scritta a mano, senza rete neurale.", + "Avaliação escrita à mão, sem rede neural.", + "Qo‘lda yozilgan baholash, neyrotarmoqsiz.", + "Қолмен жазылған бағалау, нейрожелісіз.", + ], + [ + "Attacking style tuned on Tal's games.", + "Атакующий стиль, настроенный по партиям Таля.", + "Style offensif réglé sur les parties de Tal.", + "Angriffsstil, abgestimmt auf Tals Partien.", + "Estilo atacante ajustado con las partidas de Tal.", + "Stile offensivo tarato sulle partite di Tal.", + "Estilo atacante ajustado nas partidas de Tal.", + "Tal o‘yinlari asosida sozlangan hujumkor uslub.", + "Таль ойындары бойынша бапталған шабуыл стилі.", + ], + [ + "A neural network trained on Tal's games.", + "Нейросеть, обученная на партиях Таля.", + "Un réseau de neurones entraîné sur les parties de Tal.", + "Ein neuronales Netz, trainiert mit Tals Partien.", + "Una red neuronal entrenada con las partidas de Tal.", + "Una rete neurale addestrata sulle partite di Tal.", + "Uma rede neural treinada nas partidas de Tal.", + "Tal o‘yinlarida o‘qitilgan neyrotarmoq.", + "Таль ойындарында оқытылған нейрожелі.", + ], + [ + "Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).", + "Rodent V скачивается один раз ({mb} МБ, с github.com — файл самих авторов).", + "Rodent V est téléchargé une seule fois ({mb} Mo, depuis github.com, le fichier des auteurs).", + "Rodent V wird einmalig heruntergeladen ({mb} MB, von github.com, die Datei der Autoren).", + "Rodent V se descarga una sola vez ({mb} MB, desde github.com, el archivo de los autores).", + "Rodent V si scarica una sola volta ({mb} MB, da github.com, il file degli autori).", + "O Rodent V é baixado uma única vez ({mb} MB, de github.com, o arquivo dos autores).", + "Rodent V bir marta yuklab olinadi ({mb} MB, github.com dan — mualliflarning o‘z fayli).", + "Rodent V бір рет жүктеледі ({mb} МБ, github.com сайтынан — авторлардың өз файлы).", + ], + [ + "Unpacking…", + "Распаковка…", + "Décompression…", + "Entpacken…", + "Descomprimiendo…", + "Estrazione…", + "Descompactando…", + "Ochilmoqda…", + "Ашылуда…", + ], + [ + "Could not download Rodent V: {error}", + "Не удалось скачать Rodent V: {error}", + "Impossible de télécharger Rodent V : {error}", + "Rodent V konnte nicht heruntergeladen werden: {error}", + "No se pudo descargar Rodent V: {error}", + "Impossibile scaricare Rodent V: {error}", + "Não foi possível baixar o Rodent V: {error}", + "Rodent V’ni yuklab bo‘lmadi: {error}", + "Rodent V жүктелмеді: {error}", + ], + [ + "it does not start on this computer", + "он не запускается на этом компьютере", + "il ne démarre pas sur cet ordinateur", + "er startet auf diesem Computer nicht", + "no arranca en este ordenador", + "non si avvia su questo computer", + "ele não inicia neste computador", + "u bu kompyuterda ishga tushmaydi", + "ол бұл компьютерде іске қосылмайды", + ], + [ + "Rodent V did not start: {e}", + "Rodent V не запустился: {e}", + "Rodent V n’a pas démarré : {e}", + "Rodent V ist nicht gestartet: {e}", + "Rodent V no se inició: {e}", + "Rodent V non si è avviato: {e}", + "O Rodent V não iniciou: {e}", + "Rodent V ishga tushmadi: {e}", + "Rodent V іске қосылмады: {e}", + ], + [ + "time is up, but Rodent V cannot checkmate", + "время вышло, но Rodent V нечем поставить мат", + "le temps est écoulé, mais Rodent V ne peut pas mater", + "die Zeit ist um, aber Rodent V kann nicht mattsetzen", + "se acabó el tiempo, pero Rodent V no puede dar mate", + "tempo scaduto, ma Rodent V non può dare matto", + "o tempo acabou, mas o Rodent V não pode dar mate", + "vaqt tugadi, lekin Rodent V mot qila olmaydi", + "уақыт бітті, бірақ Rodent V мат қоя алмайды", + ], + [ + "Rodent V's time is up, but you cannot checkmate", + "у Rodent V вышло время, но вам нечем поставить мат", + "le temps de Rodent V est écoulé, mais vous ne pouvez pas mater", + "Rodent Vs Zeit ist um, aber Sie können nicht mattsetzen", + "a Rodent V se le acabó el tiempo, pero no puedes dar mate", + "il tempo di Rodent V è scaduto, ma non puoi dare matto", + "o tempo do Rodent V acabou, mas você não pode dar mate", + "Rodent V ning vaqti tugadi, lekin siz mot qila olmaysiz", + "Rodent V-тің уақыты бітті, бірақ сіз мат қоя алмайсыз", + ], + [ + "Rodent V resigned", + "Rodent V сдался", + "Rodent V a abandonné", + "Rodent V hat aufgegeben", + "Rodent V se rindió", + "Rodent V ha abbandonato", + "O Rodent V desistiu", + "Rodent V taslim bo‘ldi", + "Rodent V берілді", + ], + [ + "Rodent V resigns", + "Rodent V сдаётся", + "Rodent V abandonne", + "Rodent V gibt auf", + "Rodent V se rinde", + "Rodent V abbandona", + "O Rodent V desiste", + "Rodent V taslim bo‘lmoqda", + "Rodent V беріледі", + ], + [ + "Its position is lost. Accept the win, or play to the end?", + "Его позиция проиграна. Принять победу или играть до конца?", + "Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ?", + "Seine Stellung ist verloren. Sieg annehmen oder zu Ende spielen?", + "Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final?", + "La sua posizione è persa. Accettare la vittoria o giocare fino in fondo?", + "A posição dele está perdida. Aceitar a vitória ou jogar até o fim?", + "Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi?", + "Оның позициясы ұтылды. Жеңісті қабылдайсыз ба, әлде соңына дейін ойнайсыз ба?", + ], + [ + "Rodent V plays on and will not offer again in this game", + "Rodent V играет дальше и в этой партии больше не предложит", + "Rodent V continue et ne proposera plus dans cette partie", + "Rodent V spielt weiter und bietet in dieser Partie nicht mehr an", + "Rodent V sigue y no volverá a ofrecer en esta partida", + "Rodent V continua e non lo proporrà più in questa partita", + "O Rodent V continua e não oferecerá de novo nesta partida", + "Rodent V davom etadi va bu o‘yinda boshqa taklif qilmaydi", + "Rodent V жалғастырады және бұл ойында енді ұсынбайды", + ], + [ + "Continued from {game}, after {move}. From here on, a game against {name}.", + "Продолжение партии {game} после {move}. Дальше — партия против {name}.", + "Suite de {game}, après {move}. À partir d’ici, une partie contre {name}.", + "Fortsetzung von {game} nach {move}. Ab hier eine Partie gegen {name}.", + "Continuación de {game} tras {move}. Desde aquí, una partida contra {name}.", + "Seguito di {game} dopo {move}. Da qui, una partita contro {name}.", + "Continuação de {game} após {move}. Daqui em diante, uma partida contra {name}.", + "{game} davomi, {move} dan keyin. Bundan buyon — {name} ga qarshi o‘yin.", + "{game} жалғасы, {move} кейін. Осы жерден — {name} қарсы ойын.", + ], + [ + "Continued after {move}. From here on, a game against {name}.", + "Продолжение после {move}. Дальше — партия против {name}.", + "Suite après {move}. À partir d’ici, une partie contre {name}.", + "Fortsetzung nach {move}. Ab hier eine Partie gegen {name}.", + "Continuación tras {move}. Desde aquí, una partida contra {name}.", + "Seguito dopo {move}. Da qui, una partita contro {name}.", + "Continuação após {move}. Daqui em diante, uma partida contra {name}.", + "{move} dan keyin davomi. Bundan buyon — {name} ga qarshi o‘yin.", + "{move} кейінгі жалғасы. Осы жерден — {name} қарсы ойын.", + ], + [ + "Continued from {game}. From here on, a game against {name}.", + "Продолжение партии {game}. Дальше — партия против {name}.", + "Suite de {game}. À partir d’ici, une partie contre {name}.", + "Fortsetzung von {game}. Ab hier eine Partie gegen {name}.", + "Continuación de {game}. Desde aquí, una partida contra {name}.", + "Seguito di {game}. Da qui, una partita contro {name}.", + "Continuação de {game}. Daqui em diante, uma partida contra {name}.", + "{game} davomi. Bundan buyon — {name} ga qarshi o‘yin.", + "{game} жалғасы. Осы жерден — {name} қарсы ойын.", + ], + [ + "From here on, a game against {name}.", + "Дальше — партия против {name}.", + "À partir d’ici, une partie contre {name}.", + "Ab hier eine Partie gegen {name}.", + "Desde aquí, una partida contra {name}.", + "Da qui, una partita contro {name}.", + "Daqui em diante, uma partida contra {name}.", + "Bundan buyon — {name} ga qarshi o‘yin.", + "Осы жерден — {name} қарсы ойын.", + ], + [ + "Rodent V answers a draw offer with Stockfish's help: none is installed", + "Rodent V отвечает на предложение ничьей с помощью Stockfish, а он не установлен", + "Rodent V répond à une proposition de nulle avec l’aide de Stockfish, qui n’est pas installé", + "Rodent V beantwortet Remisangebote mit Hilfe von Stockfish, der nicht installiert ist", + "Rodent V responde a las tablas con ayuda de Stockfish, que no está instalado", + "Rodent V risponde alla patta con l’aiuto di Stockfish, che non è installato", + "O Rodent V responde ao empate com a ajuda do Stockfish, que não está instalado", + "Rodent V durang taklifiga Stockfish yordamida javob beradi, u o‘rnatilmagan", + "Rodent V тең ойын ұсынысына Stockfish көмегімен жауап береді, ол орнатылмаған", + ], + [ + "Rodent V declined; offer again after two of its moves", + "Rodent V отказался; снова можно предложить через два его хода", + "Rodent V a refusé ; reproposez après deux de ses coups", + "Rodent V hat abgelehnt; nach zwei seiner Züge wieder anbieten", + "Rodent V lo rechazó; ofrece de nuevo tras dos de sus jugadas", + "Rodent V ha rifiutato; riproponi dopo due sue mosse", + "O Rodent V recusou; ofereça de novo após dois lances dele", + "Rodent V rad etdi; uning ikki yurishidan keyin yana taklif qiling", + "Rodent V бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз", + ], + [ + "Rodent V accepts when its position is no better and has settled", + "Rodent V соглашается, когда его позиция не лучше и уже не меняется", + "Rodent V accepte quand sa position n’est pas meilleure et s’est stabilisée", + "Rodent V nimmt an, wenn seine Stellung nicht besser ist und sich beruhigt hat", + "Rodent V acepta cuando su posición no es mejor y se ha estabilizado", + "Rodent V accetta quando la sua posizione non è migliore e si è stabilizzata", + "O Rodent V aceita quando a posição dele não é melhor e se estabilizou", + "Rodent V pozitsiyasi yaxshi bo‘lmasa va o‘zgarmay qolsa, rozi bo‘ladi", + "Rodent V позициясы жақсы болмаса және өзгермей қалса, келіседі", + ], + [ + "Rodent V declines the draw", + "Rodent V отказывается от ничьей", + "Rodent V refuse la nulle", + "Rodent V lehnt das Remis ab", + "Rodent V rechaza las tablas", + "Rodent V rifiuta la patta", + "O Rodent V recusa o empate", + "Rodent V durangdan bosh tortadi", + "Rodent V тең ойыннан бас тартады", + ], + [ + "plays like a human", + "играет как человек", + "joue comme un humain", + "spielt wie ein Mensch", + "juega como una persona", + "gioca come un umano", + "joga como um humano", + "odamdek o‘ynaydi", + "адам сияқты ойнайды", + ], + [ + "strong, with a style", + "сильный, со стилем", + "fort, avec un style", + "stark, mit Stil", + "fuerte, con estilo", + "forte, con uno stile", + "forte, com estilo", + "kuchli, uslubli", + "күшті, стилімен", + ], [ "Maia resigned", "Maia сдалась", diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index f269064..8d12790 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -24,6 +24,7 @@ mod own_db; mod play; mod reference; mod review; +mod rodent_download; mod san; mod settings; mod settings_ui; diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 6e83a84..a86b15d 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -138,6 +138,104 @@ pub struct PlayPrefs { /// field `strength` held her rating input, a different scale, and is dropped). #[serde(rename = "level")] pub strength: u32, + /// The opponent: Maia or Rodent, and Rodent's style (a personality file's name). + pub rival: Rival, + pub style: String, +} + +/// Who plays against the user. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Rival { + /// Maia: human moves of a strength, human mistakes (docs/research/maia-strength.md). + #[default] + Maia, + /// Rodent V: a strong engine with a style (docs/research/rodent.md). + Rodent, +} + +/// Rodent's styles: its personality files, the personality's name (for PGN), what the +/// style is called and does (in the app's language). The players' imitations come last +/// (`player`). +pub struct Style { + pub id: &'static str, + pub name: &'static str, + title: &'static str, + pub about: &'static str, + pub player: bool, +} + +impl Style { + /// The style's name to translate («Attacking»). + pub fn title(&self) -> &'static str { + self.title + } +} + +pub const STYLES: &[Style] = &[ + Style { + id: "rodent", + name: "Rodent", + title: "Balanced", + about: "Even, all-round play with no bias.", + player: false, + }, + Style { + id: "ampere", + name: "Ampere", + title: "Attacking", + about: "Active pieces and attack, sound pawn structure.", + player: false, + }, + Style { + id: "chaotic", + name: "Chaotic", + title: "Chaotic", + about: "Aggressive, tricky openings, careless with pawns.", + player: false, + }, + Style { + id: "nimzoid", + name: "Nimzoid", + title: "Restricting", + about: "Closed positions, cramping the opponent, old openings.", + player: false, + }, + Style { + id: "hector", + name: "Hector", + title: "Classical", + about: "Hand-written evaluation, no neural network.", + player: false, + }, + Style { + id: "tal_hybrid", + name: "Tal", + title: "Tal", + about: "Attacking style tuned on Tal's games.", + player: true, + }, + Style { + id: "tal_nnue", + name: "Tal NNUE", + title: "Tal (network)", + about: "A neural network trained on Tal's games.", + player: true, + }, +]; + +/// «Attacking — Ampere»; a style named as its personality just once («Tal»). +fn style_label(st: &Style) -> String { + let title = tr(st.title()); + if title == st.name || st.title() == st.name { + title.to_owned() + } else { + format!("{title} — {}", st.name) + } +} + +/// The style of this id (the default one for an unknown id). +pub fn style(id: &str) -> &'static Style { + STYLES.iter().find(|s| s.id == id).unwrap_or(&STYLES[0]) } impl Default for PlayPrefs { @@ -149,6 +247,8 @@ impl Default for PlayPrefs { increment: 5, }), strength: 1500, + rival: Rival::Maia, + style: STYLES[0].id.to_owned(), } } } @@ -300,6 +400,8 @@ struct Request { oppo_elo: u32, temperature: f32, pause: Duration, + /// The game for a UCI engine (Rodent): its start and moves. + engine_pos: Option, } /// The engine in a thread of its own: loads Maia once, answers requests after a pause. @@ -361,10 +463,12 @@ impl Opponent { } } - /// Asks for a move in the last of `positions`. + /// Asks for a move in the last of `positions` (`engine_pos`: the same for a UCI + /// engine). pub fn ask( &mut self, positions: Vec, + engine_pos: Option, (self_elo, temperature): (u32, f32), oppo_elo: u32, pause: Duration, @@ -378,9 +482,113 @@ impl Opponent { oppo_elo, temperature, pause, + engine_pos, }); } + /// Rodent V (`exe` in its folder) playing in `style` at `uci_elo` (none: full + /// strength), with its opening book. It thinks during the pause (a game's own clock + /// is not its business: Maia's pause rule paces it), and answers after it. + pub fn start_rodent( + exe: std::path::PathBuf, + style: String, + uci_elo: Option, + 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("rodent".into()) + .spawn(move || { + let fail = |e: String| { + if let Ok(mut g) = err.lock() { + *g = Some(e); + } + ctx.request_repaint(); + }; + let config = uci::EngineConfig { + working_dir: exe.parent().map(|d| d.to_path_buf()), + ..uci::EngineConfig::new(&exe) + }; + let engine = match uci::Engine::spawn_with(config, Box::new(|| {})) { + Ok(e) => e, + Err(e) => return fail(e.to_string()), + }; + let personality = format!("personalities/{style}.txt"); + let mut setup = vec![ + ("PersonalityFile", personality.clone()), + ("OwnBook", "true".to_owned()), + ]; + if let Some(elo) = uci_elo { + setup.push(("UCI_LimitStrength", "true".to_owned())); + setup.push(("UCI_Elo", elo.to_string())); + } + let ready = engine.set_threads(1).and_then(|()| engine.set_hash_mb(64)); + if let Err(e) = ready { + return fail(e.to_string()); + } + for (name, value) in &setup { + if let Err(e) = engine.set_option(name, Some(value)) { + return fail(e.to_string()); + } + } + let _ = engine.new_game(); + while let Ok(mut r) = req_rx.recv() { + while let Ok(newer) = req_rx.try_recv() { + r = newer; + } + let (Some(pos), Some(now)) = + (r.engine_pos.clone(), r.positions.last().cloned()) + else { + continue; + }; + let started = Instant::now(); + let id = uci::SearchId(r.generation); + // Its own limit (from UCI_Elo) ends the search early; at full strength + // it thinks for the pause. + let think = r.pause.max(Duration::from_millis(300)); + if let Err(e) = engine.search(pos, id, uci::SearchLimits::MoveTime(think)) { + return fail(e.to_string()); + } + let best = loop { + match engine.recv_timeout(Duration::from_millis(200)) { + Some(uci::EngineEvent::BestMove { + search_id, best: b, .. + }) if search_id == id => { + break b; + } + Some(uci::EngineEvent::Terminated(e)) => return fail(format!("{e:?}")), + _ if started.elapsed() > think + Duration::from_secs(20) => { + let _ = engine.stop(); + } + _ => {} + } + }; + let m = best + .and_then(|b| b.parse::().ok()) + .and_then(|u| u.to_move(&now).ok()); + std::thread::sleep(r.pause.saturating_sub(started.elapsed())); + let spent = r.pause.max(started.elapsed()); + if ans_tx.send((r.generation, m, spent)).is_err() { + engine.quit(); + return; + } + ctx.request_repaint(); + } + engine.quit(); + }); + Opponent { + tx, + rx, + generation: 0, + error, + thinking: false, + } + } + /// Forgets what was asked (its answer will be dropped). pub fn forget(&mut self) { self.generation += 1; @@ -578,9 +786,10 @@ mod tests { /// A game against Maia in progress (lives in the game screen while it is played). pub struct Session { pub user: Color, - /// Maia's strength (Lichess blitz scale) and the model playing it. + /// The opponent's strength (Lichess blitz scale), what plays it and in which style. pub strength: u32, - pub model: Model, + pub engine: Engine, + pub style: String, pub user_elo: Option, pub clock: Option, pub opponent: Opponent, @@ -604,6 +813,9 @@ pub struct Session { pub struct Start { pub user: Color, pub strength: u32, + pub rival: Rival, + /// Rodent's style (ignored for Maia). + pub style: String, pub user_elo: Option, pub user_name: String, pub clock: Option, @@ -611,6 +823,124 @@ pub struct Start { pub from: Option>, } +impl Start { + /// The opponent as the game names it: «Maia 1500», «Rodent V 2400 (Tal)». + pub fn rival_name(&self) -> String { + rival_name(self.rival, self.strength, &self.style) + } +} + +/// A text about the opponent in the app's language: Maia's, or Rodent's (their own +/// sentences: in Russian and other languages the words agree with her or him). +pub fn said(rival: Rival, maia: &'static str, rodent: &'static str) -> &'static str { + tr(match rival { + Rival::Maia => maia, + Rival::Rodent => rodent, + }) +} + +/// What plays a game: a Maia model, or Rodent V. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Engine { + Maia(Model), + Rodent, +} + +impl Engine { + /// Maia's rating input and temperature for `strength` (Rodent takes its strength as + /// UCI_Elo when it starts: nothing per move). + pub fn input(self, strength: u32) -> (u32, f32) { + match self { + Engine::Maia(m) => (rating_input(m, strength), temperature(m, strength)), + Engine::Rodent => (0, 0.0), + } + } +} + +/// The opponent of `start`, ready to play: its engine and file; `None`: it has to be +/// downloaded first (the dialog offers it). +pub fn engine_for(start: &Start) -> Option<(Engine, std::path::PathBuf)> { + match start.rival { + Rival::Maia => model_for(start.strength) + .ok() + .map(|(m, p)| (Engine::Maia(m), p)), + Rival::Rodent => crate::rodent_download::installed().map(|p| (Engine::Rodent, p)), + } +} + +/// Measured (docs/research/rodent.md, «Замер»): Rodent's UCI_Elo → its strength on the +/// Lichess blitz scale (default personality, its book off). +const RODENT: &[(u32, u32)] = &[(800, 1500), (3000, 2700)]; + +/// The weakest and strongest Rodent plays (its top: full strength). +pub const RODENT_MIN: u32 = 1500; +pub const RODENT_MAX: u32 = 2700; + +/// The UCI_Elo for Rodent to play at `strength` (in proportion between the measured +/// points; `None` at the top: full strength). +pub fn rodent_elo(strength: u32) -> Option { + if strength >= RODENT_MAX { + return None; + } + let (first, last) = (RODENT[0], RODENT[RODENT.len() - 1]); + if strength <= first.1 { + return Some(first.0); + } + if strength >= last.1 { + return Some(last.0); + } + let i = RODENT + .iter() + .position(|p| p.1 >= strength) + .unwrap_or(RODENT.len() - 1); + let ((a_in, a_out), (b_in, b_out)) = (RODENT[i - 1], RODENT[i]); + let t = f64::from(strength - a_out) / f64::from(b_out - a_out); + Some((f64::from(a_in) + t * f64::from(b_in - a_in)).round() as u32) +} + +/// Dev hook `CP_RIVAL=rodent[:style]`: the opponent of a game started by a hook. +pub fn debug_rival() -> (Rival, String) { + match std::env::var("CP_RIVAL") + .ok() + .as_deref() + .map(|v| v.split_once(':').unwrap_or((v, STYLES[0].id))) + { + Some(("rodent", style)) => (Rival::Rodent, style.to_owned()), + _ => (Rival::Maia, STYLES[0].id.to_owned()), + } +} + +/// «Maia 1500», «Rodent V 2400», «Rodent V 2400 (Tal)» (the default style unnamed). +pub fn rival_name(rival: Rival, strength: u32, style_id: &str) -> String { + match rival { + Rival::Maia => format!("Maia {strength}"), + Rival::Rodent if style_id == STYLES[0].id => format!("Rodent V {strength}"), + Rival::Rodent => format!("Rodent V {strength} ({})", style(style_id).name), + } +} + +impl Session { + pub fn rival(&self) -> Rival { + match self.engine { + Engine::Maia(_) => Rival::Maia, + Engine::Rodent => Rival::Rodent, + } + } + + /// The opponent on its bar: «Maia 1500», «Rodent V 2400 · Tal». + pub fn rival_label(&self) -> String { + match self.engine { + Engine::Maia(_) => format!("Maia {}", self.strength), + Engine::Rodent if self.style == STYLES[0].id => format!("Rodent V {}", self.strength), + Engine::Rodent => format!( + "Rodent V {} · {}", + self.strength, + tr(style(&self.style).title()) + ), + } + } +} + /// Where a game against Maia starts when it goes on from a game: its start and the /// moves to the chosen one (the history Maia and the repetitions need). #[derive(Clone, Debug)] @@ -643,6 +973,13 @@ pub struct Dialog { prefs: PlayPrefs, custom: bool, download: Option, + /// Rodent's download (docs/design/rodent-opponent.md §6). + rodent_download: Option, + /// What the dialog just did with the opponent or the strength, said under the slider + /// (§4): an automatic switch, a strength raised or lowered. + event: Option, + /// Rodent was chosen by the slider going past Maia (not by the user's click). + auto_switched: bool, /// «Download and play» was pressed: the game starts once Maia is there. play_after: bool, /// The game goes on from a position of another game. @@ -672,6 +1009,9 @@ impl Dialog { prefs, custom, download: None, + rodent_download: None, + event: None, + auto_switched: false, play_after: false, focus: true, from: None, @@ -699,6 +1039,8 @@ impl Dialog { None => Dialog::new(settings), }; d.prefs.strength = start.strength; + d.prefs.rival = start.rival; + d.prefs.style = start.style.clone(); d.prefs.clock = start.clock; d.custom = start.clock.is_some_and(|c| !PRESETS.contains(&c)); d.prefs.color = match start.user { @@ -741,14 +1083,6 @@ impl Dialog { // A game from a position: that position, instead of the introduction. if let Some(from) = &self.from { position_block(ui, settings, from, self.prefs.color, body_h >= 420.0); - } else if body_h >= 420.0 { - // In a low window the choices matter more than the introduction. - 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(), - ); } // The blocks in the order of the choice: who plays, against whom, which @@ -800,29 +1134,178 @@ impl Dialog { ui.end_row(); }); - // The opponent: Maia's rating, or relative to the user's. + // The opponent (docs/design/rodent-opponent.md): Maia or Rodent V, one strength + // slider for both, Rodent's style. + let rodent_ok = crate::rodent_download::available(); + let rodent = self.prefs.rival == Rival::Rodent; section( ui, - &crate::i18n::trf("Opponent — Maia {elo}", &[("elo", &self.prefs.strength)]), + &if rodent { + crate::i18n::trf("Opponent — Rodent V {elo}", &[("elo", &self.prefs.strength)]) + } else { + crate::i18n::trf("Opponent — Maia {elo}", &[("elo", &self.prefs.strength)]) + }, ); + ui.horizontal(|ui| { + let tile_w = (W - GAP) / 2.0; + // A selectable tile of two centred lines: the name and what it is. + let tile = |ui: &mut egui::Ui, on: bool, enabled: bool, name: &str, about: &str| { + let sense = if enabled { egui::Sense::click() } else { egui::Sense::hover() }; + let (rect, resp) = ui.allocate_exact_size(egui::vec2(tile_w, 48.0), sense); + let v = ui.style().interact_selectable(&resp, on); + let fill = if on { ui.visuals().selection.bg_fill } else { v.weak_bg_fill }; + ui.painter().rect(rect, v.corner_radius, fill, v.bg_stroke, egui::StrokeKind::Inside); + let (text, weak) = if enabled { + (if on { ui.visuals().selection.stroke.color } else { v.text_color() }, ui.visuals().weak_text_color()) + } else { + let c = ui.visuals().weak_text_color(); + (c, c) + }; + let width = tile_w - 12.0; + let line = |t: &str, size: f32, color| { + ui.painter().layout(t.to_owned(), egui::FontId::proportional(size), color, width) + }; + let (top, bottom) = (line(name, 14.0, text), line(about, 11.5, weak)); + let h = top.size().y + bottom.size().y; + let y = rect.center().y - h / 2.0; + ui.painter().galley(egui::pos2(rect.center().x - top.size().x / 2.0, y), top, text); + let y2 = y + h - bottom.size().y; + ui.painter().galley(egui::pos2(rect.center().x - bottom.size().x / 2.0, y2), bottom, weak); + resp + }; + if tile(ui, !rodent, true, "Maia", tr("plays like a human")).clicked() && rodent { + self.prefs.rival = Rival::Maia; + self.auto_switched = false; + self.event = None; + if self.prefs.strength > STRENGTH_MAX { + self.prefs.strength = STRENGTH_MAX; + self.event = Some(crate::i18n::trf( + "Maia plays up to {elo}: the strength is lowered to {elo}.", + &[("elo", &STRENGTH_MAX)], + )); + } + } + let about = if rodent_ok { + tr("strong, with a style") + } else if cfg!(target_os = "macos") { + tr("not yet for macOS") + } else { + tr("not yet for this system") + }; + let r = tile(ui, rodent, rodent_ok, "Rodent V", about).on_hover_text(if rodent_ok { "" } else { tr( + "The authors of Rodent V have no build for this system yet. When there is one, it will be here.", + ) }); + if r.clicked() && !rodent { + self.prefs.rival = Rival::Rodent; + self.auto_switched = false; + self.event = None; + if self.prefs.strength < RODENT_MIN { + self.prefs.strength = RODENT_MIN; + self.event = Some(crate::i18n::trf( + "Rodent V plays from {elo}: the strength is raised to {elo}.", + &[("elo", &RODENT_MIN)], + )); + } + } + }); + // One scale for both: a point of the slider is always the same strength. + let top = if rodent_ok { RODENT_MAX } else { STRENGTH_MAX }; + let before = self.prefs.strength; ui.horizontal(|ui| { let end = |ui: &mut egui::Ui, v: u32| { ui.add_sized([34.0, 18.0], egui::Label::new(RichText::new(v.to_string()).weak())) }; end(ui, STRENGTH_MIN); ui.spacing_mut().slider_width = W - 2.0 * 34.0 - 2.0 * GAP; - ui.add( - egui::Slider::new(&mut self.prefs.strength, STRENGTH_MIN..=STRENGTH_MAX) + let resp = ui.add( + egui::Slider::new(&mut self.prefs.strength, STRENGTH_MIN..=top) .step_by(50.0) .show_value(false), ); - end(ui, STRENGTH_MAX); + // Maia's zone under the track (§4): lit while she is chosen. + if rodent_ok { + let rect = resp.rect; + let pad = rect.height() / 2.0; + let x = |v: u32| { + rect.left() + pad + (v - STRENGTH_MIN) as f32 / (top - STRENGTH_MIN) as f32 * (rect.width() - 2.0 * pad) + }; + let band = egui::Rect::from_min_max( + egui::pos2(x(STRENGTH_MIN), rect.bottom() + 1.0), + egui::pos2(x(STRENGTH_MAX), rect.bottom() + 4.0), + ); + let color = if self.prefs.rival == Rival::Maia { + ui.visuals().selection.bg_fill.gamma_multiply(0.6) + } else { + ui.visuals().widgets.inactive.bg_stroke.color + }; + ui.painter().rect_filled(band, 1.0, color); + } + end(ui, top); }); - ui.label( - RichText::new(tr("Her measured strength, on the Lichess blitz scale.")) - .weak() - .size(11.5), - ); + ui.add_space(4.0); + if self.prefs.strength != before { + // Past Maia's top: Rodent at once (the owner's rule); below Rodent's + // bottom: Maia. Moving back keeps the choice, with a word about it. + if self.prefs.rival == Rival::Maia && self.prefs.strength > STRENGTH_MAX { + self.prefs.rival = Rival::Rodent; + self.auto_switched = true; + self.event = Some(crate::i18n::trf( + "Stronger than {elo} plays Rodent V: Maia does not play that strong.", + &[("elo", &STRENGTH_MAX)], + )); + } else if self.prefs.rival == Rival::Rodent && self.prefs.strength < RODENT_MIN { + self.prefs.rival = Rival::Maia; + self.auto_switched = false; + self.event = Some(crate::i18n::trf("Weaker than {elo} plays Maia.", &[("elo", &RODENT_MIN)])); + } else if self.auto_switched && self.prefs.strength <= STRENGTH_MAX { + self.event = Some(tr("Maia can play here too: choose her if you want human mistakes.").to_owned()); + } + } + let rodent = self.prefs.rival == Rival::Rodent; + let note = self.event.clone().unwrap_or_else(|| match (rodent, rodent_ok) { + (true, _) => tr("Measured strength, on the Lichess blitz scale.").to_owned(), + (false, true) => crate::i18n::trf( + "Her measured strength, on the Lichess blitz scale. Stronger than {elo}: Rodent V.", + &[("elo", &STRENGTH_MAX)], + ), + (false, false) => tr("Her measured strength, on the Lichess blitz scale.").to_owned(), + }); + ui.add(egui::Label::new(RichText::new(note).weak().size(11.5)).truncate()); + // Rodent's style: always in its place (greyed for Maia), so nothing jumps. + ui.add_space(4.0); + ui.add_enabled_ui(rodent, |ui| { + let current = style(&self.prefs.style); + let shown = if rodent { + style_label(current) + } else { + tr("Like a human").to_owned() + }; + egui::ComboBox::from_id_salt("rodent_style") + .width(W) + .height(400.0) + .selected_text(shown) + .show_ui(ui, |ui| { + for (head, player) in [(tr("Style"), false), (tr("As a player"), true)] { + ui.label(RichText::new(head).weak().size(11.5)); + for st in STYLES.iter().filter(|st| st.player == player) { + let text = style_label(st); + ui.selectable_value(&mut self.prefs.style, st.id.to_owned(), text) + .on_hover_text(tr(st.about)); + } + if !player { + ui.separator(); + } + } + }) + .response + .on_disabled_hover_text(tr("The style is chosen for Rodent V")); + }); + let about = if rodent { + tr(style(&self.prefs.style).about) + } else { + tr("Maia does not pick a style: she plays like people of her rating.") + }; + ui.add(egui::Label::new(RichText::new(about).weak().size(11.5)).truncate()); let rating = self.rating(); // Colour. @@ -913,38 +1396,79 @@ impl Dialog { }) .inner; - // Maia itself, downloaded once: under the body, by the buttons, always seen. + // The opponent's file, downloaded once: under the body, by the buttons, always + // seen. The line stays while either Maia's large model or Rodent is missing, + // so that switching the opponent does not change the dialog's height; it is + // about the opponent chosen. + let rodent = self.prefs.rival == Rival::Rodent; let stage = self.download.as_ref().map(|d| d.stage()); - let mut ready = model.is_ok(); + let rstage = self.rodent_download.as_ref().map(|d| d.stage()); + let rodent_there = crate::rodent_download::installed().is_some(); + let mut ready = if rodent { rodent_there } else { model.is_ok() }; // A download going on: no game meanwhile (closing the dialog would cancel it). let busy = matches!( - stage, - Some(crate::maia_download::Stage::Downloading { .. } | crate::maia_download::Stage::Checking) - ); - // While the large model is missing the line stays (also when the small one - // plays the strength chosen), so that the dialog does not jump with the slider. + stage, + Some(crate::maia_download::Stage::Downloading { .. } | crate::maia_download::Stage::Checking) + ) || matches!( + rstage, + Some(crate::engine_download::Stage::Downloading { .. } | crate::engine_download::Stage::Unpacking) + ); let large = crate::maia_download::installed(Model::Large).is_some(); - if !ready || !large { + let rodent_missing = crate::rodent_download::available() && !rodent_there; + if !ready || !large || rodent_missing { ui.add_space(6.0); - match stage { - None => { - ui.label(RichText::new(download_note(model.as_ref().err().copied())).weak()); + if rodent { + match &rstage { + None | Some(crate::engine_download::Stage::Cancelled) if !ready => { + ui.label(RichText::new(crate::i18n::trf( + "Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).", + &[("mb", &crate::rodent_download::size_mb())], + )).weak()); + } + Some(crate::engine_download::Stage::Downloading { done, total }) => { + ui.add(egui::ProgressBar::new(*done as f32 / (*total).max(1) as f32).show_percentage()); + } + Some(crate::engine_download::Stage::Unpacking) => { + ui.horizontal(|ui| { + ui.add(egui::Spinner::new()); + ui.label(tr("Unpacking…")); + }); + } + Some(crate::engine_download::Stage::Done(_)) => ready = true, + Some(crate::engine_download::Stage::Failed(f)) => { + ui.label(RichText::new(crate::i18n::trf( + "Could not download Rodent V: {error}", + &[("error", &download_failure(f))], + )).color(ui.visuals().error_fg_color)); + } + // Ready, but Maia's file is missing: the line keeps its place. + _ => { + ui.label(" "); + } } - Some(crate::maia_download::Stage::Downloading { done }) => { - let size = self.download.as_ref().map_or(1, |d| d.model.size()); - ui.add( - egui::ProgressBar::new(done as f32 / 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(ref e)) => { - ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } else if ready && large { + ui.label(" "); + } else { + match stage { + None => { + ui.label(RichText::new(download_note(model.as_ref().err().copied())).weak()); + } + Some(crate::maia_download::Stage::Downloading { done }) => { + let size = self.download.as_ref().map_or(1, |d| d.model.size()); + ui.add( + egui::ProgressBar::new(done as f32 / 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(ref e)) => { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } } } } @@ -963,13 +1487,22 @@ impl Dialog { .inner; let pressed = !busy && (main.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter))); - if pressed && !ready && let Err(m) = model { - self.download = Some(crate::maia_download::Download::start(ctx, m)); - self.play_after = true; + if pressed && !ready { + if rodent { + self.rodent_download = Some(crate::rodent_download::start(ctx)); + self.play_after = true; + } else if let Err(m) = model { + self.download = Some(crate::maia_download::Download::start(ctx, m)); + self.play_after = true; + } } - // After a download: the game starts when it is done (not when the slider - // moves down to what another model plays). - let downloaded = matches!(stage, Some(crate::maia_download::Stage::Done(_))); + // After a download: the game starts when it is done, only if that opponent + // is still the one chosen (not when the choice moved meanwhile). + let downloaded = if rodent { + matches!(rstage, Some(crate::engine_download::Stage::Done(_))) + } else { + matches!(stage, Some(crate::maia_download::Stage::Done(_))) + }; if ready && (pressed || (self.play_after && downloaded)) { self.play_after = false; let user = match self.prefs.color { @@ -992,6 +1525,8 @@ impl Dialog { settings.play.color = color; } out = Some(DialogOutcome::Play(Start { + rival: self.prefs.rival, + style: self.prefs.style.clone(), user, strength: self.prefs.strength, user_elo: rating, @@ -1109,6 +1644,18 @@ fn position_block( }); } +/// Why Rodent's download failed, in words. +fn download_failure(f: &crate::engine_download::Failure) -> String { + use crate::engine_download::Failure as F; + match f { + F::Network(e) | F::Disk(e) => e.clone(), + F::Server(code) => format!("HTTP {code}"), + F::Broken => tr("it does not start on this computer").to_owned(), + F::Checksum => tr("The file is not the published one").to_owned(), + F::Unsupported => tr("not yet for this system").to_owned(), + } +} + /// What the download button brings: Maia herself, or (the small one being there) the /// large one for the strength chosen. fn download_note(model: Option) -> String { @@ -1158,13 +1705,19 @@ impl End { 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, loser } if loser == self.user => { - tr("time is up, but Maia cannot checkmate") - } - Ending::Time { draw: true, .. } => tr("Maia's time is up, but you cannot checkmate"), + Ending::Time { draw: true, loser } if loser == self.user => said( + self.start.rival, + "time is up, but Maia cannot checkmate", + "time is up, but Rodent V cannot checkmate", + ), + Ending::Time { draw: true, .. } => said( + self.start.rival, + "Maia's time is up, but you cannot checkmate", + "Rodent V's time is up, but you cannot checkmate", + ), Ending::Time { .. } => tr("time is up"), Ending::Resigned { loser } if loser == self.user => "", - Ending::Resigned { .. } => tr("Maia resigned"), + Ending::Resigned { .. } => said(self.start.rival, "Maia resigned", "Rodent V resigned"), Ending::DrawAgreed => tr("by agreement"), } } diff --git a/apps/desktop/src/rodent_download.rs b/apps/desktop/src/rodent_download.rs new file mode 100644 index 0000000..e311706 --- /dev/null +++ b/apps/desktop/src/rodent_download.rs @@ -0,0 +1,189 @@ +//! Downloading Rodent V on request (docs/decisions.md «Соперник с характером»): the +//! official release 1.2 of github.com/nescitus/Rodent-V (GPL-3.0), checked against its +//! SHA-256, unpacked into the user's data directory with its personalities, networks and +//! opening books (the engine finds them from its own folder). Linux and Windows on x86-64 +//! only: the release has no other builds. Nothing is downloaded without the user asking. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use crate::engine_download::{Asset, Download, Failure, Stage, disk, fetch}; + +const TAG: &str = "Rodent_v_1.2"; + +const ARCHIVE: Asset = Asset { + file: "release-1-2.zip", + sha256: "81c46c45d3f26393b375f6be03d60f4207bb79f4f924156e53fee6ac75a7be6d", + size: 48_241_374, + zip: true, +}; + +/// The engine's file in the archive for this platform, if there is one. +fn binary() -> Option<&'static str> { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("linux", "x86_64") => Some("rodent_v_1.2"), + ("windows", "x86_64") => Some("rodent_v_1.2.exe"), + _ => None, + } +} + +#[cfg(windows)] +const EXE: &str = "rodent_v.exe"; +#[cfg(not(windows))] +const EXE: &str = "rodent_v"; + +/// Whether Rodent can be had on this platform. +pub fn available() -> bool { + binary().is_some() +} + +pub fn size_mb() -> u64 { + ARCHIVE.size.div_ceil(1_000_000) +} + +/// `/engines/rodent_v_1.2/` (`CP_RODENT` elsewhere: development). +pub fn dir() -> Option { + if let Some(d) = std::env::var_os("CP_RODENT") { + return Some(PathBuf::from(d)); + } + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("engines").join("rodent_v_1.2")) +} + +/// The installed engine, if it is there (with its personalities beside it). +pub fn installed() -> Option { + let d = dir()?; + let exe = d.join(EXE); + (exe.is_file() && d.join("personalities").is_dir()).then_some(exe) +} + +/// Removes the downloaded engine (a broken one, or to free its space). +pub fn remove() -> std::io::Result<()> { + if std::env::var_os("CP_RODENT").is_some() { + return Ok(()); + } + match dir() { + Some(d) if d.exists() => std::fs::remove_dir_all(d), + _ => Ok(()), + } +} + +pub fn start(ctx: &egui::Context) -> Download { + Download::spawn(ctx, ARCHIVE.size, run) +} + +fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { + let bin = binary().ok_or(Failure::Unsupported)?; + let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; + std::fs::create_dir_all(&dir).map_err(disk)?; + let archive = dir.join(format!("{}.part", ARCHIVE.file)); + let url = format!( + "https://github.com/nescitus/Rodent-V/releases/download/{TAG}/{}", + ARCHIVE.file + ); + let result = fetch(&url, &archive, &ARCHIVE, report, cancel) + .and_then(|()| { + report(Stage::Unpacking); + unpack(&archive, &dir, bin) + }) + .and_then(|exe| check_runs(&exe).map(|()| exe)); + let _ = std::fs::remove_file(&archive); + if result.is_err() { + // Nothing half-installed is left behind. + let _ = std::fs::remove_dir_all(&dir); + } + result +} + +/// Takes this platform's engine and the folders it reads (personalities, nets, books) +/// out of the archive; the other builds and the pictures of the manual stay out. +fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { + let exe = dir.join(EXE); + let file = std::fs::File::open(archive).map_err(disk)?; + let mut z = zip::ZipArchive::new(file).map_err(|e| Failure::Disk(e.to_string()))?; + for i in 0..z.len() { + let mut entry = z.by_index(i).map_err(|e| Failure::Disk(e.to_string()))?; + if !entry.is_file() { + continue; + } + let name = entry + .name() + .map_err(|e| Failure::Disk(e.to_string()))? + .into_owned(); + // "release-1-2/personalities/tal_nnue.txt" → ["personalities", "tal_nnue.txt"]. + let parts: Vec<&str> = name.split(['/', '\\']).filter(|p| !p.is_empty()).collect(); + let dest = match parts.as_slice() { + [_, b] if *b == bin => exe.clone(), + [_, folder, f] + if ["personalities", "nets", "books"].contains(folder) && !f.contains("..") => + { + let d = dir.join(folder); + std::fs::create_dir_all(&d).map_err(disk)?; + d.join(f) + } + _ => continue, + }; + let mut out = std::fs::File::create(&dest).map_err(disk)?; + std::io::copy(&mut entry, &mut out).map_err(disk)?; + } + if !exe.is_file() || !dir.join("personalities").is_dir() { + return Err(Failure::Disk("no engine in the archive".into())); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(disk)?; + } + Ok(exe) +} + +/// Starts the engine once from its folder and waits for its name: it runs here (the +/// release needs AVX2: an older processor fails this). +fn check_runs(exe: &Path) -> Result<(), Failure> { + use std::io::Write; + let mut cmd = std::process::Command::new(exe); + if let Some(d) = exe.parent() { + cmd.current_dir(d); + } + cmd.stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); + } + let mut child = cmd.spawn().map_err(|_| Failure::Broken)?; + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(b"uci\nquit\n"); + } + let out = child.wait_with_output().map_err(|_| Failure::Broken)?; + if String::from_utf8_lossy(&out.stdout).contains("Rodent") { + Ok(()) + } else { + Err(Failure::Broken) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Unpacks the real archive when it is at hand (`RODENT_ZIP=…/release-1-2.zip`). + #[test] + #[ignore = "needs the release archive (RODENT_ZIP)"] + fn unpacks_the_engine_and_its_folders() { + let zip = std::env::var("RODENT_ZIP").expect("RODENT_ZIP"); + let dir = std::env::temp_dir().join(format!("cp-rodent-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let exe = unpack(Path::new(&zip), &dir, "rodent_v_1.2").unwrap(); + assert!(exe.is_file()); + assert!(dir.join("personalities/tal_nnue.txt").is_file()); + assert!(dir.join("nets/rodent_4kb_768hl_8ob_v2.bin").is_file()); + assert!(dir.join("books/rodent.bin").is_file()); + assert!(!dir.join("rodent_v_1.2.exe").exists()); + check_runs(&exe).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/mobile-api/src/play.rs b/crates/mobile-api/src/play.rs index 7527e05..3d627f8 100644 --- a/crates/mobile-api/src/play.rs +++ b/crates/mobile-api/src/play.rs @@ -76,10 +76,18 @@ pub fn maia_game_tags( } else { shakmaty::Color::Black }; - ::play::game_tags(&event, user, &user_name, None, strength, "-") - .into_iter() - .map(|(name, value)| crate::Tag { name, value }) - .collect() + ::play::game_tags( + &event, + user, + &user_name, + None, + &format!("Maia {strength}"), + strength, + "-", + ) + .into_iter() + .map(|(name, value)| crate::Tag { name, value }) + .collect() } /// Maia's turns in a row with her position hopeless before she offers to resign. diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index 21c47a4..c823594 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -131,18 +131,20 @@ pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Dur // ----- the game's tags ----------------------------------------------------------------- -/// The tags of a game against Maia (as Lichess writes a game against a program): -/// `event` in the app's language, the user's name ("?" unknown) and rating, Maia's -/// strength, the time control in PGN ("-": none). The rest (date, result) is the game's. +/// The tags of a game against a program (as Lichess writes one): `event` in the app's +/// language, the user's name ("?" unknown) and rating, the program's name («Maia 1500», +/// «Rodent V 2400 (Tal)») and strength, the time control in PGN ("-": none). The rest +/// (date, result) is the game's. pub fn game_tags( event: &str, user: Color, user_name: &str, user_elo: Option, + program: &str, strength: u32, time_control: &str, ) -> Vec<(String, String)> { - let maia = format!("Maia {strength}"); + let maia = program.to_owned(); let you = if user_name.trim().is_empty() { "?".to_owned() } else { diff --git a/docs/design/rodent-opponent.md b/docs/design/rodent-opponent.md new file mode 100644 index 0000000..b4db2b9 --- /dev/null +++ b/docs/design/rodent-opponent.md @@ -0,0 +1,170 @@ +# Rodent V в диалоге «Играть с компьютером» (компьютер) + +Статус: проект дизайнера, 2026-10-26. Основание: `docs/decisions.md` («Соперник с характером: Rodent V», «Предложение ничьей»), `docs/research/rodent.md`, текущий `Dialog::show` в `apps/desktop/src/play.rs`, правила `docs/design/play-mode.md` и `docs/design/maia-models.md` (диалог не прыгает, ряды фиксированной высоты, плитки делят ширину ряда). Только компьютер; на телефоне остаётся Maia. + +Числа силы Rodent ниже — **заглушки для компоновки** (`RODENT_MIN = 1100`, `RODENT_MAX = 2700`); разработчик подставляет измеренные. Граница Maia — `MAIA_MAX = 2100` (большая модель), как сейчас `STRENGTH_MAX`. + +## 1. Путь пользователя + +1. Открывает «Играть с компьютером». Впервые выбрана Maia 1500 (как сейчас); дальше — последний выбор: соперник, сила, стиль Rodent. +2. Хочет сильнее: тянет ползунок вправо. Перейдя 2100, сразу (во время перетаскивания) соперником становится Rodent V, ряд «Стиль» оживает, строка под ползунком объясняет почему. +3. Хочет «Таля» на 1600: щёлкает плитку «Rodent V» (сила остаётся 1600), в «Стиль» выбирает «Таль». +4. Rodent не скачан: внизу строка «скачивается один раз, 48 МБ», кнопка «Скачать и играть»; после загрузки партия начинается сама (как у Maia). +5. Играет: в полосе игрока «Rodent V 2400 · Таль»; ничья, сдача, реванш — как с Maia. + +## 2. Компоновка тела диалога + +Порядок блоков прежний: «Вы» → «Соперник» → «Ваш цвет» → «Время». Вводная фраза про Maia (`body_h >= 420`) **убирается**: её смысл переходит в подписи плиток соперника. Это возвращает высоту, которую берёт новый ряд «Стиль». + +``` +Соперник — Rodent V 2400 (заголовок секции, как сейчас) +┌──────────────────────────┐┌──────────────────────────┐ +│ Maia ││ Rodent V │ две плитки 227 × 48 +│ играет как человек ││ сильный движок с характером│ +└──────────────────────────┘└──────────────────────────┘ +Сила: 1100 [━━━━━━━━━━━━━━━━━━━━━━━●━━━━━━━━] 2700 + ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ полоса «зона Maia» 1100–2100 + Сильнее 2100 играет Rodent V: Maia так сильно не играет. (1 строка) +Стиль: [ Таль — гибрид ▾] ComboBox, высота 32 + Атакующий стиль, настроенный по партиям Таля. (1 строка) +``` + +- Заголовок секции: `Соперник — Maia {elo}` / `Соперник — Rodent V {elo}`. Стиль в заголовок не идёт (длинно); он виден в своём ряду. +- «Сила:» и «Стиль:» — сетка из двух колонок, как «Имя:/Рейтинг:» в «Вы» (подписи выровнены по левому краю одной колонки). +- **Ряд «Стиль» есть всегда**, высота постоянная (комбо 32 + одна строка описания). Диалог не прыгает ни при переключении соперника, ни при автопереходе. +- Для Maia комбо **выключено** и показывает «Как человек»; описание: «Maia не выбирает стиль: она играет, как люди её рейтинга.» Выключенный ряд честно говорит, что стиль — свойство Rodent, и подсказывает, где его искать. Подсказка при наведении: «Стиль выбирается у Rodent V». +- Все строки-пояснения — одна строка на ширине 460 при 11,5 pt (тексты ниже подобраны короткими; переводчикам — то же ограничение, при переполнении обрезка с «…» и полный текст во всплывающей подсказке). + +## 3. Выбор соперника + +Две плитки `Button::selectable`, рамка всегда (как цвет и время), 227 × 48, две строки: имя 14 pt полужирное, подпись 11,5 pt приглушённая. + +| Плитка | Подпись RU | Подпись EN | +|---|---|---| +| Maia | играет как человек, с типичными ошибками | plays like a human, typical mistakes included | +| Rodent V | сильный движок с характером: сила и стиль | a strong engine with character: strength and style | + +Щелчок по плитке: +- **Maia при силе > 2100** → сила становится 2100 (её предел); строка под ползунком: «Maia играет до 2100 — сила снижена до 2100.» Выбор пользователя явный, поэтому менять силу можно, но молча — нельзя. +- **Rodent при силе < `RODENT_MIN`** (если замер покажет нижнюю границу выше 1100) → сила поднимается до `RODENT_MIN`, строка: «Rodent V играет от {min} — сила поднята до {min}.» +- Иначе сила не меняется. + +Клавиатура: плитки в порядке Tab; Enter/Space выбирает; Enter вне комбо — «Играть» (как сейчас). + +## 4. Ползунок силы — один на обоих + +- **Диапазон всегда один**: `min(Maia_min, RODENT_MIN) … RODENT_MAX`, шаг 50. Шкала не меняется от смены соперника: точка ползунка всегда значит одно и то же число. Концы подписаны (как сейчас, 34 px). +- **Полоса «зона Maia»**: 3 px под дорожкой ползунка от 1100 до 2100 (рисуется painter'ом по прямоугольнику ответа слайдера, высота зарезервирована всегда). Цвет: акцент с прозрачностью ~35 %, когда выбрана Maia; цвет обводки неактивных виджетов, когда Rodent. Без подписи на ней — объясняет строка под ползунком. +- **Автопереход вверх** (обязательное требование владельца): Maia выбрана и значение стало > 2100 (мышь, стрелки, Home/End) → `opponent = Rodent` сразу, стиль — последний выбранный у Rodent (впервые «Сбалансированный»). Ставится флаг `auto_switched` (только на время диалога). +- **Обратно ниже 2100 — остаётся Rodent**, без молчаливого возврата. Строка: «Здесь может играть и Maia — выберите её, если хотите человечных ошибок.» +- **Автопереход вниз** (симметрично, только если `RODENT_MIN > 1100`): Rodent выбран, значение < `RODENT_MIN` → Maia, строка «Слабее {min} играет Maia.» +- Если у Rodent верхняя точка — «без ограничения» (полная сила), подпись конца — измеренное число, а не «∞»: шкала везде честная. + +**Строка под ползунком** — одна, фиксированной высоты; содержание по приоритету: + +1. последнее событие диалога (автопереход, снижение/подъём силы при выборе плитки) — держится до следующего изменения соперника или силы через плитку; +2. Rodent выбран, сила ≤ 2100 и был автопереход → «Здесь может играть и Maia…»; +3. иначе обычная: Maia — «Её измеренная сила, по шкале блица Lichess. Сильнее 2100 — Rodent V.»; Rodent — «Измеренная сила, по шкале блица Lichess.» + +## 5. Выбор стиля + +Элемент — **выпадающий список** (`egui::ComboBox`, ширина ряда), а не плитки: семь пунктов плитками — два ряда непонятных имён и +80 px; список растёт без перекомпоновки (исследование предлагает добавлять личности). В закрытом виде: «{стиль} — {имя личности}» приглушённым хвостом, например «Атакующий — Ampere». В списке два раздела с некликабельными заголовками (11,5 pt, приглушённо) и разделителем; каждый пункт — две строки: название и описание. + +**Стиль** (по умолчанию «Сбалансированный»): + +| Файл | Название RU / EN | Описание RU | Описание EN | +|---|---|---|---| +| rodent | Сбалансированный / Balanced | Ровная универсальная игра, без перекосов. | Even, all-round play with no bias. | +| ampere | Атакующий / Attacking | Активные фигуры и атака, крепкая пешечная структура. | Active pieces and attack, sound pawn structure. | +| chaotic | Хаотичный / Chaotic | Агрессия и хитрые дебюты, пешки не бережёт. | Aggressive, tricky openings, careless with pawns. | +| nimzoid | Сковывающий / Restricting | Закрытые позиции, стеснение соперника, старые дебюты. | Closed positions, cramping the opponent, old openings. | +| hector | Классический / Classical | Оценка, написанная вручную, без нейросети. | Hand-written evaluation, no neural network. | + +**Как игрок:** + +| Файл | Название RU / EN | Описание RU | Описание EN | +|---|---|---|---| +| tal_hybrid | Таль / Tal | Атакующий стиль, настроенный по партиям Таля. | Attacking style tuned on Tal's games. | +| tal_nnue | Таль (сеть) / Tal (network) | Нейросеть, обученная на партиях Таля. | A neural network trained on Tal's games. | + +- Описание выбранного пункта — строка под комбо (одна строка). Имена личностей (Ampere, Hector…) не переводятся. +- Стиль не меняет шкалу силы (сила — UCI_Elo, стиль — `PersonalityFile`, они разведены). См. открытый вопрос 1. +- Клавиатура: Tab до комбо, Space/Enter открывает, стрелки, Enter выбирает, Esc закрывает список (не диалог). + +## 6. Загрузка Rodent + +Та же строка состояния над кнопками, что у Maia, и та же кнопка «Скачать и играть». + +- **Резерв строки**: строка есть, пока не установлен хоть один из нужных файлов (Rodent или большая Maia) — тогда переключение соперника её не добавляет и не убирает. Если активный соперник готов, а не хватает другого — строка пустая той же высоты. +- Содержание относится **только к выбранному сопернику**: + - Rodent нет: «Rodent V скачивается один раз (48 МБ, с github.com, файл авторов).» + - идёт загрузка: полоса с процентами; затем «Проверка…», затем «Распаковка…» (спиннер); + - ошибка загрузки: красным «Не удалось скачать Rodent V: {error}»; кнопка остаётся «Скачать и играть» (повтор); + - ошибка распаковки/записи: красным «Не удалось распаковать Rodent V: {error}». +- Во время загрузки «Играть» выключена (как сейчас); плитки и ползунок доступны. Партия стартует сама по окончании, **только если** выбран всё ещё Rodent; иначе `play_after` сбрасывается, кнопка просто показывает состояние нового выбора. Закрытие диалога отменяет загрузку (как у Maia). +- **macOS** (сборки авторов нет): плитка Rodent выключена, подпись «пока нет для macOS»; подсказка: «У авторов Rodent V ещё нет сборки для macOS. Когда появится, он будет здесь.» Диапазон ползунка — только Maia (1100–2100), полосы зоны нет, автоперехода нет; строка под ползунком — обычная Maia без хвоста «Сильнее 2100 — Rodent V». Ряд «Стиль» остаётся выключенным, как для Maia. +- Rodent не запустился при старте партии: как с Maia (`Dialog::for_start` с тем же выбором), красным в строке состояния «Rodent V не запустился: {e}». + +## 7. В партии + +- Полоса игрока (сейчас `{king} Maia {strength}`): `{king} Rodent V {strength} · {стиль}`; для «Сбалансированного» стиль не пишется: `Rodent V 2400`. +- PGN (имена не переводятся, это обменный формат): `White/Black "Rodent V 2400 (Tal)"`; для `rodent` без скобок; в скобках — имя личности: Ampere, Chaotic, Nimzoid, Hector, Tal, Tal NNUE. `WhiteElo/BlackElo` = измеренная сила, `…Type "program"` — как у Maia. +- Ничья и сдача — тот же скрытый Stockfish и `accepts_draw`; кнопки и правила те же. +- Реванш и «Играть отсюда» открывают диалог с тем же соперником, силой и стилем. +- Темп ответа: Rodent на лимите узлов отвечает мгновенно — темп как у Maia (если у Maia есть минимальная пауза, та же пауза). +- **Тексты с «Maia» внутри** не обобщать через `{name}`: в русском и других языках род согласуется («Maia сдалась» / «Rodent V сдался»). Для Rodent — отдельные строки (список ниже). + +## 8. Тексты для i18n (EN-ключ → RU) + +Диалог: +- `Opponent` → «Соперник» (если заголовок без имени понадобится), `Opponent — Rodent V {elo}` → «Соперник — Rodent V {elo}» +- `plays like a human, typical mistakes included` → «играет как человек, с типичными ошибками» +- `a strong engine with character: strength and style` → «сильный движок с характером: сила и стиль» +- `Strength:` → «Сила:»; `Style:` → «Стиль:» +- `Like a human` → «Как человек» +- `Maia does not pick a style: she plays like people of her rating.` → «Maia не выбирает стиль: она играет, как люди её рейтинга.» +- `The style is chosen for Rodent V` → «Стиль выбирается у Rodent V» +- `Style` → «Стиль»; `As a player` → «Как игрок» (заголовки разделов списка) +- 7 названий и 7 описаний — таблицы §5 +- `Her measured strength, on the Lichess blitz scale. Stronger than {elo}: Rodent V.` → «Её измеренная сила, по шкале блица Lichess. Сильнее {elo} — Rodent V.» (заменяет нынешнюю строку; на macOS — старая без хвоста) +- `Measured strength, on the Lichess blitz scale.` → «Измеренная сила, по шкале блица Lichess.» +- `Stronger than {elo} plays Rodent V: Maia does not play that strong.` → «Сильнее {elo} играет Rodent V: Maia так сильно не играет.» +- `Maia can play here too — choose her if you want human mistakes.` → «Здесь может играть и Maia — выберите её, если хотите человечных ошибок.» +- `Maia plays up to {elo}: the strength is lowered to {elo}.` → «Maia играет до {elo} — сила снижена до {elo}.» +- `Rodent V plays from {elo}: the strength is raised to {elo}.` → «Rodent V играет от {elo} — сила поднята до {elo}.» +- `Weaker than {elo} plays Maia.` → «Слабее {elo} играет Maia.» +- `Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).` → «Rodent V скачивается один раз ({mb} МБ, с github.com, файл авторов).» +- `Unpacking…` → «Распаковка…» +- `Could not download Rodent V: {error}` → «Не удалось скачать Rodent V: {error}» +- `Could not unpack Rodent V: {error}` → «Не удалось распаковать Rodent V: {error}» +- `not yet for macOS` → «пока нет для macOS» +- `The authors of Rodent V have no macOS build yet. When there is one, it will be here.` → «У авторов Rodent V ещё нет сборки для macOS. Когда появится, он будет здесь.» + +Партия (пары к строкам Maia): +- `Rodent V did not start: {e}` → «Rodent V не запустился: {e}» +- `Rodent V resigned` → «Rodent V сдался»; `Rodent V resigns` → «Rodent V сдаётся» +- `Rodent V's time is up, but you cannot checkmate` → «У Rodent V кончилось время, но вам нечем поставить мат» +- `Rodent V plays on and will not offer again in this game` → «Rodent V играет дальше и в этой партии больше не предложит» +- `From here on, a game against Rodent V {elo}.` и три варианта «Continued…» — как у Maia +- ответы на предложение ничьей, если в них есть «Maia», — пары для Rodent V + +## 9. Снимки для проверки (харнесс скриншотов) + +1. Maia 1500, всё скачано: зона Maia подсвечена, «Стиль» выключен. +2. Maia 2050 → перетянуто на 2200: Rodent выбран, строка автоперехода, «Стиль» включён. +3. После (2) обратно на 1800: Rodent остаётся, строка «Здесь может играть и Maia…». +4. Rodent 1600, «Таль», открытый список (оба раздела). +5. Rodent не скачан: строка 48 МБ, «Скачать и играть»; затем загрузка 40 %; «Распаковка…»; ошибка. +6. Rodent 2500 → щелчок Maia: сила 2100, строка «снижена до 2100». +7. macOS-состояние (принудительно флагом): плитка Rodent выключена, ползунок 1100–2100. +8. Диалог «Играть отсюда» с Rodent и низкое окно (прокрутка тела, кнопки видны). +9. Полоса игрока «Rodent V 2400 · Таль» и полоса для «Сбалансированного» без стиля. +10. Наложение снимков 1–3 и 5: высота диалога и положение кнопок совпадают до пикселя. +11. Самый длинный язык (de/ru): строки под ползунком и под комбо в одну строку или с «…». + +## 10. Открытые вопросы + +1. **Сила по стилям.** Шкала мерится, вероятно, на «Сбалансированном». Hector без сети заметно слабее на том же UCI_Elo; если замер покажет разницу > ~100, нужно либо мерить каждую личность (свой `RODENT_MAX` у стиля, ползунок ограничивается со строкой «Классический играет до {elo}»), либо прятать слабые стили выше их предела. До замера — одна шкала. +2. Какой из двух Талей ставить первым и как подписать — по впечатлению владельца от партий. +3. Нижняя граница Rodent: если замер даст ≥ 1100, автопереход вниз не нужен (§4). +4. Настройки: `settings.play.opponent` (`Maia | Rodent`), `settings.play.rodent_style`; сила общая. Кнопка «Сбросить» не нужна.