Play: Rodent V as an opponent (desktop): downloaded on request, strength and style
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

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 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-26 03:02:55 +03:00
parent b90bcdf3a3
commit 73593ddfc5
10 changed files with 1660 additions and 117 deletions

View file

@ -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;
};

View file

@ -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<Asset> {
@ -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<PathBuf, Failure>,
) -> 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<PathBuf, Failure>
}
/// 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())
}

View file

@ -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<std::path::PathBuf>,
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(),
));
}
}
}

View file

@ -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 сдалась",

View file

@ -24,6 +24,7 @@ mod own_db;
mod play;
mod reference;
mod review;
mod rodent_download;
mod san;
mod settings;
mod settings_ui;

View file

@ -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<uci::EnginePosition>,
}
/// 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<Chess>,
engine_pos: Option<uci::EnginePosition>,
(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<u32>,
ctx: &egui::Context,
) -> Opponent {
let (tx, req_rx) = channel::<Request>();
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::<shakmaty::uci::UciMove>().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<u32>,
pub clock: Option<Clock>,
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<u32>,
pub user_name: String,
pub clock: Option<TimeControl>,
@ -611,6 +823,124 @@ pub struct Start {
pub from: Option<Box<StartFrom>>,
}
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<u32> {
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<crate::maia_download::Download>,
/// Rodent's download (docs/design/rodent-opponent.md §6).
rodent_download: Option<crate::engine_download::Download>,
/// 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<String>,
/// 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<Model>) -> 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"),
}
}

View file

@ -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)
}
/// `<local data dir>/engines/rodent_v_1.2/` (`CP_RODENT` elsewhere: development).
pub fn dir() -> Option<PathBuf> {
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<PathBuf> {
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<PathBuf, Failure> {
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<PathBuf, Failure> {
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);
}
}