From 3fe82551cea8a723827b888a32c83f431d622bdb Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 26 Oct 2026 20:53:49 +0300 Subject: [PATCH] Play: Rodent IV's characters and players in Rodent's list of styles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner: «заюзаем rodent 4 со всеми его стилями». One opponent «Rodent»: its list gets Rodent IV's 13 characters and 22 players (sorted by their names as shown, the Tals side by side); the engine follows the style (Rodent IV's UCI_Elo 800–2800), «Rodent IV 2000 (Petrosian)» in the record. Texts say «Rodent» where they said «Rodent V». Rodent IV's authors publish no builds for Linux and Windows: the workflow rodent-iv.yml builds it from their sources at a pinned commit (with one fix, packaging/rodent-iv/home-dir.patch: on Linux it now and then took a wrong home folder and played without its personality) into a pre-release that is never «latest». The app downloads that build and the personalities and books from the authors' repository at the same commit (scripts/rodent4-manifest.py → rodent4_files.rs), each checked; three misnamed books get a copy under the name their personality reads. Until the build's sums are written in, Rodent IV's styles are not shown. Reviewed (tester and designer in one) with a local build (CP_RODENT4). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/rodent-iv.yml | 102 +++ CHANGELOG.md | 7 + THIRD_PARTY_NOTICES.md | 21 + apps/desktop/src/game_view.rs | 22 +- apps/desktop/src/i18n.rs | 975 ++++++++++++++++++++++----- apps/desktop/src/library.rs | 2 +- apps/desktop/src/main.rs | 2 + apps/desktop/src/play.rs | 562 +++++++++++++-- apps/desktop/src/rodent4_download.rs | 188 ++++++ apps/desktop/src/rodent4_files.rs | 454 +++++++++++++ apps/desktop/src/rodent_download.rs | 2 +- docs/decisions.md | 7 + docs/dev/desktop.md | 2 +- packaging/rodent-iv/home-dir.patch | 16 + scripts/rodent4-manifest.py | 43 ++ 15 files changed, 2165 insertions(+), 240 deletions(-) create mode 100644 .github/workflows/rodent-iv.yml create mode 100644 apps/desktop/src/rodent4_download.rs create mode 100644 apps/desktop/src/rodent4_files.rs create mode 100644 packaging/rodent-iv/home-dir.patch create mode 100644 scripts/rodent4-manifest.py diff --git a/.github/workflows/rodent-iv.yml b/.github/workflows/rodent-iv.yml new file mode 100644 index 0000000..cd6f0c5 --- /dev/null +++ b/.github/workflows/rodent-iv.yml @@ -0,0 +1,102 @@ +# Builds Rodent IV (github.com/nescitus/rodent-iv, GPL-3.0) from the authors' sources at a +# pinned commit for Linux, Windows and macOS: its authors publish no builds for them +# (docs/decisions.md «Rodent IV»). ChessPenguin downloads the engine from this release on +# request, checked against the SHA-256 pinned in apps/desktop/src/rodent4_download.rs; the +# personalities and books come from the authors' repository at the same commit. +# +# Tag rodent-iv- to publish. The release is a pre-release that is never "latest": +# the app's update check and the website look for the latest release of ChessPenguin. +name: Rodent IV + +on: + push: + tags: ["rodent-iv-*"] + workflow_dispatch: + +permissions: + contents: write + +env: + # The authors' last commit (2021-04-29, Rodent IV 0.33). + COMMIT: e8d84c8c8c189a1cf4eb27c578fc573af3b916d2 + +jobs: + build: + strategy: + matrix: + include: + # An older glibc, so that the engine runs on the distributions ChessPenguin runs on. + - os: ubuntu-22.04 + name: rodent-iv-linux-x86_64 + - os: windows-latest + name: rodent-iv-windows-x86_64.exe + - os: macos-14 + name: rodent-iv-macos-arm64 + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + with: + path: cp + - name: Sources at the pinned commit, with our one fix + shell: bash + # packaging/rodent-iv/home-dir.patch: on Linux the engine now and then took a + # wrong home folder and played without its personality and books. + run: | + git clone https://github.com/nescitus/rodent-iv.git src + git -C src checkout "$COMMIT" + git -C src apply ../cp/packaging/rodent-iv/home-dir.patch + - name: Windows compiler (MinGW-w64, linked statically) + if: runner.os == 'Windows' + uses: msys2/setup-msys2@v2 + with: + msystem: UCRT64 + install: mingw-w64-ucrt-x86_64-gcc + - name: Build (Linux, macOS) + if: runner.os != 'Windows' + shell: bash + run: | + cd src/sources + extra="" + if [ "$RUNNER_OS" = "Linux" ]; then extra="-static-libstdc++ -static-libgcc"; fi + c++ -O3 -w -pipe -DNDEBUG -fno-rtti -finline-functions -std=c++14 $extra src/*.cpp -o "../../${{ matrix.name }}" -lm + strip "../../${{ matrix.name }}" || true + - name: Build (Windows) + if: runner.os == 'Windows' + shell: msys2 {0} + run: | + cd src/sources + g++ -O3 -w -pipe -DNDEBUG -fno-rtti -finline-functions -std=c++14 -static src/*.cpp -o "../../${{ matrix.name }}" -lm + strip "../../${{ matrix.name }}" + - name: It answers UCI + shell: bash + run: printf 'uci\nquit\n' | "./${{ matrix.name }}" | grep -q "Rodent IV" + - uses: actions/upload-artifact@v7 + with: + name: ${{ matrix.name }} + path: ${{ matrix.name }} + + publish: + needs: build + if: github.ref_type == 'tag' + runs-on: ubuntu-24.04 + steps: + - uses: actions/download-artifact@v8 + with: + path: dist + merge-multiple: true + - name: Checksums and the source offer + run: | + cd dist && sha256sum * > SHA256SUMS.txt + cat > "${RUNNER_TEMP}/notes.md" < Opponent::start(file, ctx), - crate::play::Engine::Rodent => { + crate::play::Engine::Rodent(_) => { Opponent::start_rodent(file, start.style.clone(), Some(start.strength), ctx) } }, @@ -2290,7 +2290,7 @@ impl GameView { .as_ref() .map_or(crate::play::Rival::Maia, |s| s.rival()); ui.label( - RichText::new(crate::play::said(rival, "Maia resigns", "Rodent V resigns")) + RichText::new(crate::play::said(rival, "Maia resigns", "Rodent resigns")) .strong() .size(16.0), ); @@ -2323,7 +2323,7 @@ impl GameView { .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", + "Rodent plays on and will not offer again in this game", )) .clicked() { @@ -2527,9 +2527,9 @@ impl GameView { 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}" + crate::play::Engine::Rodent(g) => { + g.remove(); + "Rodent did not start: {e}" } }; actions.push(GameAction::Toast(trf(text, &[("e", &err)]))); @@ -3283,15 +3283,15 @@ impl GameView { let hint = match judge { 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", + "Rodent 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", + "Rodent 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", + "Rodent accepts when its position is no better and has settled", ), }; if ui @@ -3309,7 +3309,7 @@ impl GameView { self.finish_play(crate::play::Ending::DrawAgreed, actions); } else { actions.push(GameAction::Toast( - said("Maia declines the draw", "Rodent V declines the draw").into(), + said("Maia declines the draw", "Rodent declines the draw").into(), )); } } @@ -3361,7 +3361,7 @@ impl GameView { crate::play::said( end.start.rival, "Left: you {you} · Maia {maia}", - "Left: you {you} · Rodent V {maia}", + "Left: you {you} · Rodent {maia}", ), &[ ("you", &crate::play::clock_text(you)), diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 2c94874..d8b32a6 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -10958,15 +10958,15 @@ const ROWS: &[[&str; 9]] = &[ "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}", + "Opponent — Rodent {elo}", + "Соперник — Rodent {elo}", + "Adversaire — Rodent {elo}", + "Gegner — Rodent {elo}", + "Rival — Rodent {elo}", + "Avversario — Rodent {elo}", + "Adversário — Rodent {elo}", + "Raqib — Rodent {elo}", + "Қарсылас — Rodent {elo}", ], [ "not yet for macOS", @@ -10991,15 +10991,15 @@ const ROWS: &[[&str; 9]] = &[ "бұл жүйе үшін әзірге жоқ", ], [ - "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 авторларында бұл жүйеге әзірге нұсқа жоқ. Шыққанда осында болады.", + "Rodent is not available for this system yet. When it is, it will be here.", + "Для этой системы Rodent пока нет. Когда появится, он будет здесь.", + "Rodent n’est pas encore disponible pour ce système. Dès qu’il le sera, il sera ici.", + "Rodent gibt es für dieses System noch nicht. Sobald es ihn gibt, ist er hier.", + "Rodent aún no está disponible para este sistema. Cuando lo esté, estará aquí.", + "Rodent non è ancora disponibile per questo sistema. Quando lo sarà, sarà qui.", + "O Rodent ainda não está disponível para este sistema. Quando estiver, estará aqui.", + "Bu tizim uchun Rodent hali yo‘q. Paydo bo‘lsa, shu yerda bo‘ladi.", + "Бұл жүйе үшін Rodent әзірге жоқ. Пайда болғанда, осында болады.", ], [ "Maia plays up to {elo}: the strength is lowered to {elo}.", @@ -11012,17 +11012,6 @@ const ROWS: &[[&str; 9]] = &[ "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} дейін көтерілді.", - ], [ "Weaker than {elo} plays Maia.", "Слабее {elo} играет Maia.", @@ -11056,17 +11045,6 @@ const ROWS: &[[&str; 9]] = &[ "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", "Как человек", @@ -11101,15 +11079,15 @@ const ROWS: &[[&str; 9]] = &[ "Ойыншы сияқты", ], [ - "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 үшін таңдалады", + "The style is chosen for Rodent", + "Стиль выбирается у Rodent", + "Le style se choisit pour Rodent", + "Der Stil wird für Rodent gewählt", + "El estilo se elige para Rodent", + "Lo stile si sceglie per Rodent", + "O estilo é escolhido para o Rodent", + "Uslub Rodent uchun tanlanadi", + "Стиль Rodent үшін таңдалады", ], [ "Maia does not pick a style: she plays like people of her rating.", @@ -11280,15 +11258,15 @@ const ROWS: &[[&str; 9]] = &[ "Ашылуда…", ], [ - "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}", + "Could not download Rodent: {error}", + "Не удалось скачать Rodent: {error}", + "Impossible de télécharger Rodent : {error}", + "Rodent konnte nicht heruntergeladen werden: {error}", + "No se pudo descargar Rodent: {error}", + "Impossibile scaricare Rodent: {error}", + "Não foi possível baixar o Rodent: {error}", + "Rodent’ni yuklab bo‘lmadi: {error}", + "Rodent жүктелмеді: {error}", ], [ "it does not start on this computer", @@ -11302,59 +11280,59 @@ const ROWS: &[[&str; 9]] = &[ "ол бұл компьютерде іске қосылмайды", ], [ - "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}", + "Rodent did not start: {e}", + "Rodent не запустился: {e}", + "Rodent n’a pas démarré : {e}", + "Rodent ist nicht gestartet: {e}", + "Rodent no se inició: {e}", + "Rodent non si è avviato: {e}", + "O Rodent não iniciou: {e}", + "Rodent ishga tushmadi: {e}", + "Rodent іске қосылмады: {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 мат қоя алмайды", + "time is up, but Rodent cannot checkmate", + "время вышло, но Rodent нечем поставить мат", + "le temps est écoulé, mais Rodent ne peut pas mater", + "die Zeit ist um, aber Rodent kann nicht mattsetzen", + "se acabó el tiempo, pero Rodent no puede dar mate", + "tempo scaduto, ma Rodent non può dare matto", + "o tempo acabou, mas o Rodent não pode dar mate", + "vaqt tugadi, lekin Rodent mot qila olmaydi", + "уақыт бітті, бірақ Rodent мат қоя алмайды", ], [ - "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", - "Die Zeit von Rodent V 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's time is up, but you cannot checkmate", + "у Rodent вышло время, но вам нечем поставить мат", + "le temps de Rodent est écoulé, mais vous ne pouvez pas mater", + "Die Zeit von Rodent ist um, aber Sie können nicht mattsetzen", + "a Rodent se le acabó el tiempo, pero no puedes dar mate", + "il tempo di Rodent è scaduto, ma non puoi dare matto", + "o tempo do Rodent acabou, mas você não pode dar mate", + "Rodent ning vaqti tugadi, lekin siz mot qila olmaysiz", + "Rodent-тің уақыты бітті, бірақ сіз мат қоя алмайсыз", ], [ - "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 resigned", + "Rodent сдался", + "Rodent a abandonné", + "Rodent hat aufgegeben", + "Rodent se rindió", + "Rodent ha abbandonato", + "O Rodent desistiu", + "Rodent taslim bo‘ldi", + "Rodent берілді", ], [ - "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 беріледі", + "Rodent resigns", + "Rodent сдаётся", + "Rodent abandonne", + "Rodent gibt auf", + "Rodent se rinde", + "Rodent abbandona", + "O Rodent desiste", + "Rodent taslim bo‘lmoqda", + "Rodent беріледі", ], [ "Its position is lost. Accept the win, or play to the end?", @@ -11368,15 +11346,15 @@ const ROWS: &[[&str; 9]] = &[ "Оның позициясы ұтылды. Жеңісті қабылдайсыз ба, әлде соңына дейін ойнайсыз ба?", ], [ - "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 жалғастырады және бұл ойында енді ұсынбайды", + "Rodent plays on and will not offer again in this game", + "Rodent играет дальше и в этой партии больше не предложит", + "Rodent continue et ne proposera plus dans cette partie", + "Rodent spielt weiter und bietet in dieser Partie nicht mehr an", + "Rodent sigue y no volverá a ofrecer en esta partida", + "Rodent continua e non lo proporrà più in questa partita", + "O Rodent continua e não oferecerá de novo nesta partida", + "Rodent davom etadi va bu o‘yinda boshqa taklif qilmaydi", + "Rodent жалғастырады және бұл ойында енді ұсынбайды", ], [ "Continued from {game}, after {move}. From here on, a game against {name}.", @@ -11423,48 +11401,48 @@ const ROWS: &[[&str; 9]] = &[ "Осы жерден — {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 answers a draw offer with Stockfish's help: none is installed", + "Rodent отвечает на предложение ничьей с помощью Stockfish, а он не установлен", + "Rodent répond à une proposition de nulle avec l’aide de Stockfish, qui n’est pas installé", + "Rodent beantwortet Remisangebote mit Hilfe von Stockfish, der nicht installiert ist", + "Rodent responde a las tablas con ayuda de Stockfish, que no está instalado", + "Rodent risponde alla patta con l’aiuto di Stockfish, che non è installato", + "O Rodent responde ao empate com a ajuda do Stockfish, que não está instalado", + "Rodent durang taklifiga Stockfish yordamida javob beradi, u o‘rnatilmagan", + "Rodent тең ойын ұсынысына 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 declined; offer again after two of its moves", + "Rodent отказался; снова можно предложить через два его хода", + "Rodent a refusé ; reproposez après deux de ses coups", + "Rodent hat abgelehnt; nach zwei seiner Züge wieder anbieten", + "Rodent lo rechazó; ofrece de nuevo tras dos de sus jugadas", + "Rodent ha rifiutato; riproponi dopo due sue mosse", + "O Rodent recusou; ofereça de novo após dois lances dele", + "Rodent rad etdi; uning ikki yurishidan keyin yana taklif qiling", + "Rodent бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз", ], [ - "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 accepts when its position is no better and has settled", + "Rodent соглашается, когда его позиция не лучше и уже не меняется", + "Rodent accepte quand sa position n’est pas meilleure et s’est stabilisée", + "Rodent nimmt an, wenn seine Stellung nicht besser ist und sich beruhigt hat", + "Rodent acepta cuando su posición no es mejor y se ha estabilizado", + "Rodent accetta quando la sua posizione non è migliore e si è stabilizzata", + "O Rodent aceita quando a posição dele não é melhor e se estabilizou", + "Rodent pozitsiyasi yaxshi bo‘lmasa va o‘zgarmay qolsa, rozi bo‘ladi", + "Rodent позициясы жақсы болмаса және өзгермей қалса, келіседі", ], [ - "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 тең ойыннан бас тартады", + "Rodent declines the draw", + "Rodent отказывается от ничьей", + "Rodent refuse la nulle", + "Rodent lehnt das Remis ab", + "Rodent rechaza las tablas", + "Rodent rifiuta la patta", + "O Rodent recusa o empate", + "Rodent durangdan bosh tortadi", + "Rodent тең ойыннан бас тартады", ], [ "plays like a human", @@ -11500,15 +11478,15 @@ const ROWS: &[[&str; 9]] = &[ "{elo}-ден күштірек Rodent V ойнайды, {min} бастап: Maia мұндай күшті ойнамайды.", ], [ - "Left: you {you} · Rodent V {maia}", - "Осталось: вы {you} · Rodent V {maia}", - "Restant : vous {you} · Rodent V {maia}", - "Verbleibend: Sie {you} · Rodent V {maia}", - "Queda: tú {you} · Rodent V {maia}", - "Rimasto: tu {you} · Rodent V {maia}", - "Restante: você {you} · Rodent V {maia}", - "Qoldi: siz {you} · Rodent V {maia}", - "Қалды: сіз {you} · Rodent V {maia}", + "Left: you {you} · Rodent {maia}", + "Осталось: вы {you} · Rodent {maia}", + "Restant : vous {you} · Rodent {maia}", + "Verbleibend: Sie {you} · Rodent {maia}", + "Queda: tú {you} · Rodent {maia}", + "Rimasto: tu {you} · Rodent {maia}", + "Restante: você {you} · Rodent {maia}", + "Qoldi: siz {you} · Rodent {maia}", + "Қалды: сіз {you} · Rodent {maia}", ], [ "it stopped while playing", @@ -11522,15 +11500,15 @@ const ROWS: &[[&str; 9]] = &[ "ол ойын кезінде тоқтады", ], [ - "A game against the computer: Maia, who plays like a human, or Rodent V, strong and with a style (Ctrl+G)", - "Партия с компьютером: Maia играет как человек, Rodent V — сильно и со стилем (Ctrl+G)", - "Une partie contre l’ordinateur : Maia joue comme un humain, Rodent V fort et avec un style (Ctrl+G)", - "Eine Partie gegen den Computer: Maia spielt wie ein Mensch, Rodent V stark und mit Stil (Strg+G)", - "Una partida contra el ordenador: Maia juega como una persona, Rodent V fuerte y con estilo (Ctrl+G)", - "Una partita contro il computer: Maia gioca come un umano, Rodent V forte e con uno stile (Ctrl+G)", - "Uma partida contra o computador: a Maia joga como um humano, o Rodent V forte e com estilo (Ctrl+G)", - "Kompyuter bilan o‘yin: Maia odamdek o‘ynaydi, Rodent V — kuchli va uslubli (Ctrl+G)", - "Компьютермен ойын: Maia адам сияқты ойнайды, Rodent V — күшті және стилімен (Ctrl+G)", + "A game against the computer: Maia, who plays like a human, or Rodent, strong and with a style (Ctrl+G)", + "Партия с компьютером: Maia играет как человек, Rodent — сильно и со стилем (Ctrl+G)", + "Une partie contre l’ordinateur : Maia joue comme un humain, Rodent fort et avec un style (Ctrl+G)", + "Eine Partie gegen den Computer: Maia spielt wie ein Mensch, Rodent stark und mit Stil (Strg+G)", + "Una partida contra el ordenador: Maia juega como una persona, Rodent fuerte y con estilo (Ctrl+G)", + "Una partita contro il computer: Maia gioca come un umano, Rodent forte e con uno stile (Ctrl+G)", + "Uma partida contra o computador: a Maia joga como um humano, o Rodent forte e com estilo (Ctrl+G)", + "Kompyuter bilan o‘yin: Maia odamdek o‘ynaydi, Rodent — kuchli va uslubli (Ctrl+G)", + "Компьютермен ойын: Maia адам сияқты ойнайды, Rodent — күшті және стилімен (Ctrl+G)", ], [ "A game against the computer from this position", @@ -11753,15 +11731,15 @@ const ROWS: &[[&str; 9]] = &[ "Аяқталмаған ойын (бағдарлама жабылды) «{db}» базасына жазылды, № {n}", ], [ - "Rodent V's own rating (UCI_Elo): it does not match a person's Elo.", - "Собственный рейтинг Rodent V (UCI_Elo): он не равен Эло человека.", - "Le classement propre de Rodent V (UCI_Elo) : il ne correspond pas à l’Elo d’une personne.", - "Die eigene Wertung von Rodent V (UCI_Elo): sie entspricht nicht der Elo eines Menschen.", - "El rating propio de Rodent V (UCI_Elo): no equivale al Elo de una persona.", - "Il rating proprio di Rodent V (UCI_Elo): non corrisponde all’Elo di una persona.", - "O rating próprio do Rodent V (UCI_Elo): não corresponde ao Elo de uma pessoa.", - "Rodent V ning o‘z reytingi (UCI_Elo): u odamning Elo reytingiga teng emas.", - "Rodent V-тің өз рейтингі (UCI_Elo): ол адамның Эло рейтингіне сәйкес келмейді.", + "Rodent's own rating (UCI_Elo): it does not match a person's Elo.", + "Собственный рейтинг Rodent (UCI_Elo): он не равен Эло человека.", + "Le classement propre de Rodent (UCI_Elo) : il ne correspond pas à l’Elo d’une personne.", + "Die eigene Wertung von Rodent (UCI_Elo): sie entspricht nicht der Elo eines Menschen.", + "El rating propio de Rodent (UCI_Elo): no equivale al Elo de una persona.", + "Il rating proprio di Rodent (UCI_Elo): non corrisponde all’Elo di una persona.", + "O rating próprio do Rodent (UCI_Elo): não corresponde ao Elo de uma pessoa.", + "Rodent ning o‘z reytingi (UCI_Elo): u odamning Elo reytingiga teng emas.", + "Rodent-тің өз рейтингі (UCI_Elo): ол адамның Эло рейтингіне сәйкес келмейді.", ], [ "Maia's own rating: it does not match a person's Elo.", @@ -11774,6 +11752,636 @@ const ROWS: &[[&str; 9]] = &[ "Maia ning o‘z reytingi: u odamning Elo reytingiga teng emas.", "Maia-ның өз рейтингі: ол адамның Эло рейтингіне сәйкес келмейді.", ], + [ + "Character", + "Характер", + "Caractère", + "Charakter", + "Carácter", + "Carattere", + "Caráter", + "Xarakter", + "Мінез", + ], + [ + "Rodent IV is downloaded once ({mb} MB): the engine built from its authors' sources, its characters and books from their repository.", + "Rodent IV скачивается один раз ({mb} МБ): движок, собранный из исходников авторов, его характеры и книги — из их репозитория.", + "Rodent IV se télécharge une seule fois ({mb} Mo) : le moteur compilé depuis les sources de ses auteurs, ses caractères et livres depuis leur dépôt.", + "Rodent IV wird einmalig heruntergeladen ({mb} MB): die aus den Quellen der Autoren gebaute Engine, Charaktere und Bücher aus deren Repository.", + "Rodent IV se descarga una sola vez ({mb} MB): el motor compilado desde las fuentes de sus autores, sus caracteres y libros desde su repositorio.", + "Rodent IV si scarica una sola volta ({mb} MB): il motore compilato dai sorgenti degli autori, caratteri e libri dal loro repository.", + "O Rodent IV é baixado uma única vez ({mb} MB): o motor compilado a partir das fontes dos autores, os caráteres e livros do repositório deles.", + "Rodent IV bir marta yuklab olinadi ({mb} MB): mualliflar manbasidan yig‘ilgan dvigatel, xarakterlar va kitoblar ularning omboridan.", + "Rodent IV бір рет жүктеледі ({mb} МБ): авторлардың бастапқы кодынан жиналған қозғалтқыш, мінездер мен кітаптар олардың репозиторийінен.", + ], + [ + "Attacks first, then plays for active pieces.", + "Сначала атакует, потом играет на активность фигур.", + "Attaque d’abord, puis joue pour l’activité des pièces.", + "Greift zuerst an, spielt dann auf aktive Figuren.", + "Primero ataca, luego busca piezas activas.", + "Prima attacca, poi gioca per l’attività dei pezzi.", + "Primeiro ataca, depois joga pela atividade das peças.", + "Avval hujum qiladi, keyin donalar faolligi uchun o‘ynaydi.", + "Алдымен шабуылдайды, кейін фигуралар белсенділігіне ойнайды.", + ], + [ + "Likes closed positions.", + "Любит закрытые позиции.", + "Aime les positions fermées.", + "Mag geschlossene Stellungen.", + "Le gustan las posiciones cerradas.", + "Ama le posizioni chiuse.", + "Gosta de posições fechadas.", + "Yopiq pozitsiyalarni yaxshi ko‘radi.", + "Жабық позицияларды ұнатады.", + ], + [ + "Defends well and likes her bishops.", + "Хорошо защищается и любит слонов.", + "Défend bien et aime ses fous.", + "Verteidigt gut und mag ihre Läufer.", + "Defiende bien y le gustan sus alfiles.", + "Difende bene e ama i suoi alfieri.", + "Defende bem e gosta dos seus bispos.", + "Yaxshi himoyalanadi va filllarini yaxshi ko‘radi.", + "Жақсы қорғанады және пілдерін ұнатады.", + ], + [ + "Solid and careful; content with a draw.", + "Надёжный и осторожный, согласен на ничью.", + "Solide et prudent ; se contente de la nulle.", + "Solide und vorsichtig; mit Remis zufrieden.", + "Sólido y prudente; se conforma con tablas.", + "Solido e prudente; si accontenta della patta.", + "Sólido e cuidadoso; contenta-se com o empate.", + "Mustahkam va ehtiyotkor; duranga rozi.", + "Сенімді әрі сақ; тең ойынға келіседі.", + ], + [ + "Attacks, likes bishops, sacrifices now and then.", + "Атакует, любит слонов, время от времени жертвует.", + "Attaque, aime les fous, sacrifie de temps en temps.", + "Greift an, mag Läufer, opfert ab und zu.", + "Ataca, le gustan los alfiles, sacrifica de vez en cuando.", + "Attacca, ama gli alfieri, sacrifica di tanto in tanto.", + "Ataca, gosta de bispos, sacrifica de vez em quando.", + "Hujum qiladi, fillarni yaxshi ko‘radi, ba’zan qurbon qiladi.", + "Шабуылдайды, пілдерді ұнатады, анда-санда құрбан етеді.", + ], + [ + "Attack and restraint; likes blocked positions, avoids draws.", + "Атака и сковывание; любит запертые позиции, избегает ничьих.", + "Attaque et restriction ; aime les positions bloquées, évite la nulle.", + "Angriff und Einengung; mag blockierte Stellungen, meidet Remis.", + "Ataque y restricción; le gustan las posiciones bloqueadas, evita las tablas.", + "Attacco e restrizione; ama le posizioni bloccate, evita la patta.", + "Ataque e restrição; gosta de posições bloqueadas, evita empates.", + "Hujum va siqish; yopiq pozitsiyalarni yoqtiradi, durangdan qochadi.", + "Шабуыл мен қысу; бітелген позицияларды ұнатады, тең ойыннан қашады.", + ], + [ + "Attacks after quiet, stealthy openings.", + "Атакует после тихих, неприметных дебютов.", + "Attaque après des ouvertures calmes et discrètes.", + "Greift nach ruhigen, unauffälligen Eröffnungen an.", + "Ataca tras aperturas tranquilas y discretas.", + "Attacca dopo aperture tranquille e discrete.", + "Ataca depois de aberturas calmas e discretas.", + "Sokin, sezilmas debyutlardan keyin hujum qiladi.", + "Тыныш, байқалмайтын дебюттерден кейін шабуылдайды.", + ], + [ + "Balanced, but gives up pawns more readily.", + "Сбалансированный, но охотнее отдаёт пешки.", + "Équilibré, mais cède plus volontiers des pions.", + "Ausgewogen, gibt aber eher Bauern her.", + "Equilibrado, pero entrega peones con más facilidad.", + "Equilibrato, ma cede pedoni più volentieri.", + "Equilibrado, mas entrega peões com mais facilidade.", + "Muvozanatli, lekin piyodalarni osonroq beradi.", + "Теңгерімді, бірақ пешкаларды оңай береді.", + ], + [ + "Pawns, defence and restraint.", + "Пешки, защита и сковывание.", + "Pions, défense et restriction.", + "Bauern, Verteidigung und Einengung.", + "Peones, defensa y restricción.", + "Pedoni, difesa e restrizione.", + "Peões, defesa e restrição.", + "Piyodalar, himoya va siqish.", + "Пешкалар, қорғаныс және қысу.", + ], + [ + "A materialistic, moderate attacker.", + "Материалист, атакует умеренно.", + "Un attaquant matérialiste et modéré.", + "Ein materialistischer, maßvoller Angreifer.", + "Un atacante materialista y moderado.", + "Un attaccante materialista e moderato.", + "Um atacante materialista e moderado.", + "Materialist, o‘rtacha hujumchi.", + "Материалист, қалыпты шабуылшы.", + ], + [ + "The most computer-like: plain, sound chess.", + "Самый «компьютерный»: простые, правильные шахматы.", + "Le plus « ordinateur » : un jeu simple et sain.", + "Am computerhaftesten: schlichtes, solides Schach.", + "El más «computadora»: ajedrez sencillo y sólido.", + "Il più «computer»: scacchi semplici e solidi.", + "O mais «computador»: xadrez simples e sólido.", + "Eng «kompyuterona»: oddiy, to‘g‘ri shaxmat.", + "Ең «компьютерлік»: қарапайым, дұрыс шахмат.", + ], + [ + "Sharp and aggressive.", + "Острый и агрессивный.", + "Tranchant et agressif.", + "Scharf und aggressiv.", + "Agudo y agresivo.", + "Tagliente e aggressivo.", + "Agudo e agressivo.", + "O‘tkir va tajovuzkor.", + "Өткір және агрессивті.", + ], + [ + "A boa constrictor: squeezes slowly, very human-like.", + "Удав: медленно душит, очень по-человечески.", + "Un boa : étouffe lentement, très humain.", + "Eine Würgeschlange: würgt langsam, sehr menschlich.", + "Una boa: asfixia despacio, muy humano.", + "Un boa: stringe lentamente, molto umano.", + "Uma jiboia: aperta devagar, muito humano.", + "Bo‘g‘ma ilon: sekin siqadi, juda insoniy.", + "Айдаһар-жылан: баяу қысады, өте адамға ұқсас.", + ], + [ + "Dynamic attacks and deep combinations.", + "Динамичные атаки и глубокие комбинации.", + "Attaques dynamiques et combinaisons profondes.", + "Dynamische Angriffe und tiefe Kombinationen.", + "Ataques dinámicos y combinaciones profundas.", + "Attacchi dinamici e combinazioni profonde.", + "Ataques dinâmicos e combinações profundas.", + "Dinamik hujumlar va chuqur kombinatsiyalar.", + "Серпінді шабуылдар мен терең комбинациялар.", + ], + [ + "Quick, universal play with sharp openings.", + "Быстрая, универсальная игра с острыми дебютами.", + "Jeu rapide et universel, ouvertures tranchantes.", + "Schnelles, universelles Spiel mit scharfen Eröffnungen.", + "Juego rápido y universal con aperturas agudas.", + "Gioco rapido e universale con aperture taglienti.", + "Jogo rápido e universal com aberturas agudas.", + "Tez, universal o‘yin, o‘tkir debyutlar bilan.", + "Жылдам, әмбебап ойын, өткір дебюттермен.", + ], + [ + "A romantic attacker of the 19th century: sacrifices.", + "Романтик-атакёр XIX века: жертвы.", + "Un attaquant romantique du XIXe siècle : sacrifices.", + "Ein romantischer Angreifer des 19. Jahrhunderts: Opfer.", + "Un atacante romántico del siglo XIX: sacrificios.", + "Un attaccante romantico dell’Ottocento: sacrifici.", + "Um atacante romântico do século XIX: sacrifícios.", + "XIX asrning romantik hujumchisi: qurbonlar.", + "XIX ғасырдың романтик шабуылшысы: құрбандар.", + ], + [ + "Offbeat openings and creative blitz play.", + "Необычные дебюты и творческая блиц-игра.", + "Ouvertures originales et blitz créatif.", + "Ausgefallene Eröffnungen und kreatives Blitzspiel.", + "Aperturas poco habituales y blitz creativo.", + "Aperture insolite e blitz creativo.", + "Aberturas incomuns e blitz criativo.", + "Noodatiy debyutlar va ijodiy blits.", + "Әдеттен тыс дебюттер және шығармашыл блиц.", + ], + [ + "Scientific, strategic play from deep preparation.", + "Научная стратегическая игра на глубокой подготовке.", + "Jeu stratégique et scientifique, préparation profonde.", + "Wissenschaftliches, strategisches Spiel aus tiefer Vorbereitung.", + "Juego estratégico y científico, preparación profunda.", + "Gioco strategico e scientifico, preparazione profonda.", + "Jogo estratégico e científico, preparação profunda.", + "Chuqur tayyorgarlikka asoslangan ilmiy, strategik o‘yin.", + "Терең дайындыққа негізделген ғылыми, стратегиялық ойын.", + ], + [ + "Clear, classical and precise.", + "Ясная, классическая и точная игра.", + "Clair, classique et précis.", + "Klar, klassisch und präzise.", + "Claro, clásico y preciso.", + "Chiaro, classico e preciso.", + "Claro, clássico e preciso.", + "Aniq, klassik va puxta.", + "Анық, классикалық және дәл.", + ], + [ + "Positional squeeze, prophylaxis and technique.", + "Позиционное давление, профилактика и техника.", + "Étau positionnel, prophylaxie et technique.", + "Positioneller Druck, Prophylaxe und Technik.", + "Presión posicional, profilaxis y técnica.", + "Morsa posizionale, profilassi e tecnica.", + "Pressão posicional, profilaxia e técnica.", + "Pozitsion bosim, profilaktika va texnika.", + "Позициялық қысым, профилактика және техника.", + ], + [ + "Initiative and powerful attack.", + "Инициатива и мощная атака.", + "Initiative et attaque puissante.", + "Initiative und kraftvoller Angriff.", + "Iniciativa y ataque poderoso.", + "Iniziativa e attacco potente.", + "Iniciativa e ataque poderoso.", + "Tashabbus va kuchli hujum.", + "Бастама және қуатты шабуыл.", + ], + [ + "A tenacious defender and counter-attacker.", + "Упорный защитник и мастер контратаки.", + "Un défenseur tenace et contre-attaquant.", + "Ein zäher Verteidiger und Konterspieler.", + "Un defensor tenaz y contraatacante.", + "Un difensore tenace e contrattaccante.", + "Um defensor tenaz e contra-atacante.", + "Qat’iyatli himoyachi va qarshi hujumchi.", + "Табанды қорғаушы және қарсы шабуылшы.", + ], + [ + "Original and risky, with offbeat openings.", + "Оригинальный и рискованный, с необычными дебютами.", + "Original et risqué, aux ouvertures insolites.", + "Originell und riskant, mit ausgefallenen Eröffnungen.", + "Original y arriesgado, con aperturas inusuales.", + "Originale e rischioso, con aperture insolite.", + "Original e arriscado, com aberturas incomuns.", + "O‘ziga xos va tavakkalchi, noodatiy debyutlar bilan.", + "Өзгеше және тәуекелшіл, әдеттен тыс дебюттермен.", + ], + [ + "A practical, psychological fighter.", + "Практичный боец-психолог.", + "Un combattant pratique et psychologue.", + "Ein praktischer, psychologischer Kämpfer.", + "Un luchador práctico y psicológico.", + "Un combattente pratico e psicologico.", + "Um lutador prático e psicológico.", + "Amaliy, psixolog kurashchi.", + "Практикалық, психолог күрескер.", + ], + [ + "A swashbuckling attacker with gambits.", + "Лихой атакёр с гамбитами.", + "Un attaquant fougueux, amateur de gambits.", + "Ein verwegener Angreifer mit Gambits.", + "Un atacante audaz, amigo de los gambitos.", + "Un attaccante spavaldo con i gambetti.", + "Um atacante ousado com gambitos.", + "Gambitlar bilan dadil hujumchi.", + "Гамбиттері бар батыл шабуылшы.", + ], + [ + "Quick development and open lines.", + "Быстрое развитие и открытые линии.", + "Développement rapide et lignes ouvertes.", + "Schnelle Entwicklung und offene Linien.", + "Desarrollo rápido y líneas abiertas.", + "Sviluppo rapido e linee aperte.", + "Desenvolvimento rápido e linhas abertas.", + "Tez rivojlanish va ochiq chiziqlar.", + "Жылдам дамыту және ашық сызықтар.", + ], + [ + "Restraint, blockade and overprotection.", + "Сковывание, блокада и сверхзащита.", + "Restriction, blocus et surprotection.", + "Einengung, Blockade und Überdeckung.", + "Restricción, bloqueo y sobreprotección.", + "Restrizione, blocco e sovraprotezione.", + "Restrição, bloqueio e superproteção.", + "Siqish, blokada va ortiqcha himoya.", + "Қысу, блокада және артық қорғау.", + ], + [ + "Prophylaxis and safety first.", + "Профилактика и безопасность прежде всего.", + "Prophylaxie et sécurité avant tout.", + "Prophylaxe und Sicherheit zuerst.", + "Profilaxis y seguridad ante todo.", + "Profilassi e sicurezza prima di tutto.", + "Profilaxia e segurança acima de tudo.", + "Profilaktika va xavfsizlik birinchi.", + "Профилактика және қауіпсіздік бірінші.", + ], + [ + "Hypermodern: controls the centre from afar.", + "Гиперсовременный: контролирует центр издалека.", + "Hypermoderne : contrôle le centre à distance.", + "Hypermodern: kontrolliert das Zentrum aus der Ferne.", + "Hipermoderno: controla el centro a distancia.", + "Ipermoderno: controlla il centro da lontano.", + "Hipermoderno: controla o centro à distância.", + "Gipermodern: markazni uzoqdan nazorat qiladi.", + "Гиперзаманауи: орталықты алыстан бақылайды.", + ], + [ + "Classical positional play, great in endgames.", + "Классическая позиционная игра, силён в эндшпиле.", + "Jeu positionnel classique, excellent en finale.", + "Klassisches Positionsspiel, stark im Endspiel.", + "Juego posicional clásico, gran finalista.", + "Gioco posizionale classico, ottimo nei finali.", + "Jogo posicional clássico, ótimo em finais.", + "Klassik pozitsion o‘yin, endshpilda kuchli.", + "Классикалық позициялық ойын, эндшпильде мықты.", + ], + [ + "A universal player, at home in any position.", + "Универсал, в любой позиции как дома.", + "Un joueur universel, à l’aise partout.", + "Ein Universalspieler, in jeder Stellung zu Hause.", + "Un jugador universal, cómodo en cualquier posición.", + "Un giocatore universale, a suo agio ovunque.", + "Um jogador universal, à vontade em qualquer posição.", + "Universal o‘yinchi, har qanday pozitsiyada o‘zini uydagidek his qiladi.", + "Әмбебап ойыншы, кез келген позицияда өзін үйдегідей сезінеді.", + ], + [ + "The founder of positional play, a stubborn defender.", + "Основатель позиционной игры, упрямый защитник.", + "Le fondateur du jeu positionnel, défenseur obstiné.", + "Der Begründer des Positionsspiels, ein hartnäckiger Verteidiger.", + "El fundador del juego posicional, un defensor obstinado.", + "Il fondatore del gioco posizionale, difensore ostinato.", + "O fundador do jogo posicional, um defensor obstinado.", + "Pozitsion o‘yin asoschisi, qaysar himoyachi.", + "Позициялық ойынның негізін салушы, қыңыр қорғаушы.", + ], + [ + "The magician from Riga: sacrifices and attack.", + "Рижский волшебник: жертвы и атака.", + "Le magicien de Riga : sacrifices et attaque.", + "Der Zauberer aus Riga: Opfer und Angriff.", + "El mago de Riga: sacrificios y ataque.", + "Il mago di Riga: sacrifici e attacco.", + "O mágico de Riga: sacrifícios e ataque.", + "Rigalik sehrgar: qurbonlar va hujum.", + "Ригалық сиқыршы: құрбандар мен шабуыл.", + ], + [ + "Classical rules: space, development, active pieces.", + "Классические правила: пространство, развитие, активные фигуры.", + "Règles classiques : espace, développement, pièces actives.", + "Klassische Regeln: Raum, Entwicklung, aktive Figuren.", + "Reglas clásicas: espacio, desarrollo, piezas activas.", + "Regole classiche: spazio, sviluppo, pezzi attivi.", + "Regras clássicas: espaço, desenvolvimento, peças ativas.", + "Klassik qoidalar: makon, rivojlanish, faol donalar.", + "Классикалық ережелер: кеңістік, дамыту, белсенді фигуралар.", + ], + [ + "Aggressive and dynamic, sacrifices the exchange.", + "Агрессивный и динамичный, жертвует качество.", + "Agressif et dynamique, sacrifie la qualité.", + "Aggressiv und dynamisch, opfert die Qualität.", + "Agresivo y dinámico, sacrifica la calidad.", + "Aggressivo e dinamico, sacrifica la qualità.", + "Agressivo e dinâmico, sacrifica a qualidade.", + "Tajovuzkor va dinamik, sifatni qurbon qiladi.", + "Агрессивті және серпінді, сапаны құрбан етеді.", + ], + [ + "Tal (classic)", + "Таль (классика)", + "Tal (classique)", + "Tal (klassisch)", + "Tal (clásico)", + "Tal (classico)", + "Tal (clássico)", + "Tal (klassik)", + "Таль (классика)", + ], + [ + "Anand", + "Ананд", + "Anand", + "Anand", + "Anand", + "Anand", + "Anand", + "Anand", + "Ананд", + ], + [ + "Anderssen", + "Андерсен", + "Anderssen", + "Anderssen", + "Anderssen", + "Anderssen", + "Anderssen", + "Anderssen", + "Андерсен", + ], + [ + "Bosboom", + "Босбум", + "Bosboom", + "Bosboom", + "Bosboom", + "Bosboom", + "Bosboom", + "Bosboom", + "Босбум", + ], + [ + "Botvinnik", + "Ботвинник", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Botvinnik", + "Ботвинник", + ], + [ + "Fischer", + "Фишер", + "Fischer", + "Fischer", + "Fischer", + "Fischer", + "Fischer", + "Fischer", + "Фишер", + ], + [ + "Karpov", + "Карпов", + "Karpov", + "Karpov", + "Karpov", + "Karpov", + "Karpov", + "Karpov", + "Карпов", + ], + [ + "Kasparov", + "Каспаров", + "Kasparov", + "Kasparov", + "Kasparov", + "Kasparov", + "Kasparov", + "Kasparov", + "Каспаров", + ], + [ + "Kortchnoi", + "Корчной", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Kortchnoi", + "Корчной", + ], + [ + "Larsen", + "Ларсен", + "Larsen", + "Larsen", + "Larsen", + "Larsen", + "Larsen", + "Larsen", + "Ларсен", + ], + [ + "Lasker", + "Ласкер", + "Lasker", + "Lasker", + "Lasker", + "Lasker", + "Lasker", + "Lasker", + "Ласкер", + ], + [ + "Marshall", + "Маршалл", + "Marshall", + "Marshall", + "Marshall", + "Marshall", + "Marshall", + "Marshall", + "Маршалл", + ], + [ + "Morphy", + "Морфи", + "Morphy", + "Morphy", + "Morphy", + "Morphy", + "Morphy", + "Morphy", + "Морфи", + ], + [ + "Nimzowitsch", + "Нимцович", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Nimzowitsch", + "Нимцович", + ], + [ + "Petrosian", + "Петросян", + "Petrosian", + "Petrosian", + "Petrosian", + "Petrosian", + "Petrosian", + "Petrosian", + "Петросян", + ], + [ + "Reti", "Рети", "Reti", "Reti", "Reti", "Reti", "Reti", "Reti", "Рети", + ], + [ + "Rubinstein", + "Рубинштейн", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Rubinstein", + "Рубинштейн", + ], + [ + "Spassky", + "Спасский", + "Spassky", + "Spassky", + "Spassky", + "Spassky", + "Spassky", + "Spassky", + "Спасский", + ], + [ + "Steinitz", + "Стейниц", + "Steinitz", + "Steinitz", + "Steinitz", + "Steinitz", + "Steinitz", + "Steinitz", + "Стейниц", + ], + [ + "Tarrasch", + "Тарраш", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Tarrasch", + "Тарраш", + ], + [ + "Topalov", + "Топалов", + "Topalov", + "Topalov", + "Topalov", + "Topalov", + "Topalov", + "Topalov", + "Топалов", + ], [ "Maia resigned", "Maia сдалась", @@ -12782,6 +13390,23 @@ mod tests { assert!(missing.is_empty(), "untranslated keys: {missing:?}"); } + /// Rodent's styles are shown through `tr` of their fields, out of the scanner's sight. + #[test] + fn every_style_is_translated() { + for st in crate::play::STYLES { + for key in [st.title(), st.about] { + // Rodent IV's characters are called by their names in every language. + if key == st.name { + continue; + } + assert!( + ROWS.iter().any(|row| row[0] == key), + "untranslated style text: {key}" + ); + } + } + } + #[test] fn rows_are_unique_and_complete() { let mut seen = std::collections::HashSet::new(); diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 675b666..7492cc9 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -726,7 +726,7 @@ impl Library { .on_hover_text(shelf_hint( icons, tr("♞ Play"), - tr("A game against the computer: Maia, who plays like a human, or Rodent V, strong and with a style (Ctrl+G)"), + tr("A game against the computer: Maia, who plays like a human, or Rodent, strong and with a style (Ctrl+G)"), )) .clicked() { diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 73461b3..2dc51a9 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -25,6 +25,8 @@ mod play; mod player_games; mod reference; mod review; +mod rodent4_download; +mod rodent4_files; mod rodent_download; mod san; mod settings; diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index d59ac7c..76251f9 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -162,6 +162,71 @@ pub struct Style { title: &'static str, pub about: &'static str, pub player: bool, + /// Which Rodent plays it: V (a personality file of its own) or IV (a personality of + /// its list, `personality`; docs/decisions.md «Rodent IV»). + pub rodent: Gen, + pub personality: &'static str, +} + +/// Rodent V or Rodent IV: each downloaded on its own, each on its own scale of strength. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Gen { + V, + IV, +} + +impl Gen { + /// «Rodent V», «Rodent IV»: in the game's record and on the bar. + pub fn name(self) -> &'static str { + match self { + Gen::V => "Rodent V", + Gen::IV => "Rodent IV", + } + } + + /// Its UCI_Elo. + pub fn range(self) -> (u32, u32) { + match self { + Gen::V => (RODENT_MIN, RODENT_MAX), + Gen::IV => (RODENT_MIN, RODENT_IV_MAX), + } + } + + pub fn available(self) -> bool { + match self { + Gen::V => crate::rodent_download::available(), + Gen::IV => crate::rodent4_download::available(), + } + } + + pub fn installed(self) -> Option { + match self { + Gen::V => crate::rodent_download::installed(), + Gen::IV => crate::rodent4_download::installed(), + } + } + + pub fn size_mb(self) -> u64 { + match self { + Gen::V => crate::rodent_download::size_mb(), + Gen::IV => crate::rodent4_download::size_mb(), + } + } + + pub fn start(self, ctx: &egui::Context) -> crate::engine_download::Download { + match self { + Gen::V => crate::rodent_download::start(ctx), + Gen::IV => crate::rodent4_download::start(ctx), + } + } + + /// A file that does not start goes: the dialog offers the download again. + pub fn remove(self) { + let _ = match self { + Gen::V => crate::rodent_download::remove(), + Gen::IV => crate::rodent4_download::remove(), + }; + } } impl Style { @@ -178,6 +243,8 @@ pub const STYLES: &[Style] = &[ title: "Balanced", about: "Even, all-round play with no bias.", player: false, + rodent: Gen::V, + personality: "", }, Style { id: "ampere", @@ -185,6 +252,8 @@ pub const STYLES: &[Style] = &[ title: "Attacking", about: "Active pieces and attack, sound pawn structure.", player: false, + rodent: Gen::V, + personality: "", }, Style { id: "chaotic", @@ -192,6 +261,8 @@ pub const STYLES: &[Style] = &[ title: "Chaotic", about: "Aggressive, tricky openings, careless with pawns.", player: false, + rodent: Gen::V, + personality: "", }, Style { id: "nimzoid", @@ -199,6 +270,8 @@ pub const STYLES: &[Style] = &[ title: "Restricting", about: "Closed positions, cramping the opponent, old openings.", player: false, + rodent: Gen::V, + personality: "", }, Style { id: "hector", @@ -206,6 +279,8 @@ pub const STYLES: &[Style] = &[ title: "Classical", about: "Hand-written evaluation, no neural network.", player: false, + rodent: Gen::V, + personality: "", }, Style { id: "tal_hybrid", @@ -213,6 +288,8 @@ pub const STYLES: &[Style] = &[ title: "Tal", about: "Attacking style tuned on Tal's games.", player: true, + rodent: Gen::V, + personality: "", }, Style { id: "tal_nnue", @@ -220,14 +297,333 @@ pub const STYLES: &[Style] = &[ title: "Tal (network)", about: "A neural network trained on Tal's games.", player: true, + rodent: Gen::V, + personality: "", + }, + // Rodent IV's characters, then the players it imitates (its personality list). + Style { + id: "iv_amanda", + name: "Amanda", + title: "Amanda", + about: "Attacks first, then plays for active pieces.", + player: false, + rodent: Gen::IV, + personality: "Amanda", + }, + Style { + id: "iv_cloe", + name: "Cloe", + title: "Cloe", + about: "Likes closed positions.", + player: false, + rodent: Gen::IV, + personality: "Cloe", + }, + Style { + id: "iv_deborah", + name: "Deborah", + title: "Deborah", + about: "Defends well and likes her bishops.", + player: false, + rodent: Gen::IV, + personality: "Deborah", + }, + Style { + id: "iv_defender", + name: "Defender", + title: "Defender", + about: "Solid and careful; content with a draw.", + player: false, + rodent: Gen::IV, + personality: "Defender", + }, + Style { + id: "iv_dynamic", + name: "Dynamic", + title: "Dynamic", + about: "Attacks, likes bishops, sacrifices now and then.", + player: false, + rodent: Gen::IV, + personality: "Dynamic", + }, + Style { + id: "iv_grumpy", + name: "Grumpy", + title: "Grumpy", + about: "Attack and restraint; likes blocked positions, avoids draws.", + player: false, + rodent: Gen::IV, + personality: "Grumpy", + }, + Style { + id: "iv_partisan", + name: "Partisan", + title: "Partisan", + about: "Attacks after quiet, stealthy openings.", + player: false, + rodent: Gen::IV, + personality: "Partisan", + }, + Style { + id: "iv_pawnsacker", + name: "Pawnsacker", + title: "Pawnsacker", + about: "Balanced, but gives up pawns more readily.", + player: false, + rodent: Gen::IV, + personality: "Pawnsacker", + }, + Style { + id: "iv_pedrita", + name: "Pedrita", + title: "Pedrita", + about: "Pawns, defence and restraint.", + player: false, + rodent: Gen::IV, + personality: "Pedrita", + }, + Style { + id: "iv_preston", + name: "Preston", + title: "Preston", + about: "A materialistic, moderate attacker.", + player: false, + rodent: Gen::IV, + personality: "Preston", + }, + Style { + id: "iv_simple", + name: "Simple", + title: "Simple", + about: "The most computer-like: plain, sound chess.", + player: false, + rodent: Gen::IV, + personality: "Simple", + }, + Style { + id: "iv_spitfire", + name: "Spitfire", + title: "Spitfire", + about: "Sharp and aggressive.", + player: false, + rodent: Gen::IV, + personality: "Spitfire", + }, + Style { + id: "iv_strangler", + name: "Strangler", + title: "Strangler", + about: "A boa constrictor: squeezes slowly, very human-like.", + player: false, + rodent: Gen::IV, + personality: "Strangler", + }, + Style { + id: "iv_alekhine", + name: "Alekhine", + title: "Alekhine", + about: "Dynamic attacks and deep combinations.", + player: true, + rodent: Gen::IV, + personality: "Alekhine", + }, + Style { + id: "iv_anand", + name: "Anand", + title: "Anand", + about: "Quick, universal play with sharp openings.", + player: true, + rodent: Gen::IV, + personality: "Anand", + }, + Style { + id: "iv_anderssen", + name: "Anderssen", + title: "Anderssen", + about: "A romantic attacker of the 19th century: sacrifices.", + player: true, + rodent: Gen::IV, + personality: "Anderssen", + }, + Style { + id: "iv_bosboom", + name: "Bosboom", + title: "Bosboom", + about: "Offbeat openings and creative blitz play.", + player: true, + rodent: Gen::IV, + personality: "Bosboom.txt", + }, + Style { + id: "iv_botvinnik", + name: "Botvinnik", + title: "Botvinnik", + about: "Scientific, strategic play from deep preparation.", + player: true, + rodent: Gen::IV, + personality: "Botvinnik", + }, + Style { + id: "iv_fischer", + name: "Fischer", + title: "Fischer", + about: "Clear, classical and precise.", + player: true, + rodent: Gen::IV, + personality: "Fischer", + }, + Style { + id: "iv_karpov", + name: "Karpov", + title: "Karpov", + about: "Positional squeeze, prophylaxis and technique.", + player: true, + rodent: Gen::IV, + personality: "Karpov", + }, + Style { + id: "iv_kasparov", + name: "Kasparov", + title: "Kasparov", + about: "Initiative and powerful attack.", + player: true, + rodent: Gen::IV, + personality: "Kasparov", + }, + Style { + id: "iv_kortchnoi", + name: "Kortchnoi", + title: "Kortchnoi", + about: "A tenacious defender and counter-attacker.", + player: true, + rodent: Gen::IV, + personality: "Kortchnoi", + }, + Style { + id: "iv_larsen", + name: "Larsen", + title: "Larsen", + about: "Original and risky, with offbeat openings.", + player: true, + rodent: Gen::IV, + personality: "Larsen", + }, + Style { + id: "iv_lasker", + name: "Lasker", + title: "Lasker", + about: "A practical, psychological fighter.", + player: true, + rodent: Gen::IV, + personality: "Lasker", + }, + Style { + id: "iv_marshall", + name: "Marshall", + title: "Marshall", + about: "A swashbuckling attacker with gambits.", + player: true, + rodent: Gen::IV, + personality: "Marshall", + }, + Style { + id: "iv_morphy", + name: "Morphy", + title: "Morphy", + about: "Quick development and open lines.", + player: true, + rodent: Gen::IV, + personality: "Morphy", + }, + Style { + id: "iv_nimzowitsch", + name: "Nimzowitsch", + title: "Nimzowitsch", + about: "Restraint, blockade and overprotection.", + player: true, + rodent: Gen::IV, + personality: "Nimzowitsch", + }, + Style { + id: "iv_petrosian", + name: "Petrosian", + title: "Petrosian", + about: "Prophylaxis and safety first.", + player: true, + rodent: Gen::IV, + personality: "Petrosian", + }, + Style { + id: "iv_reti", + name: "Reti", + title: "Reti", + about: "Hypermodern: controls the centre from afar.", + player: true, + rodent: Gen::IV, + personality: "Reti", + }, + Style { + id: "iv_rubinstein", + name: "Rubinstein", + title: "Rubinstein", + about: "Classical positional play, great in endgames.", + player: true, + rodent: Gen::IV, + personality: "Rubinstein", + }, + Style { + id: "iv_spassky", + name: "Spassky", + title: "Spassky", + about: "A universal player, at home in any position.", + player: true, + rodent: Gen::IV, + personality: "Spassky", + }, + Style { + id: "iv_steinitz", + name: "Steinitz", + title: "Steinitz", + about: "The founder of positional play, a stubborn defender.", + player: true, + rodent: Gen::IV, + personality: "Steinitz", + }, + Style { + id: "iv_tal", + name: "Tal", + title: "Tal (classic)", + about: "The magician from Riga: sacrifices and attack.", + player: true, + rodent: Gen::IV, + personality: "Tal", + }, + Style { + id: "iv_tarrasch", + name: "Tarrasch", + title: "Tarrasch", + about: "Classical rules: space, development, active pieces.", + player: true, + rodent: Gen::IV, + personality: "Tarrasch", + }, + Style { + id: "iv_topalov", + name: "Topalov", + title: "Topalov", + about: "Aggressive and dynamic, sacrifices the exchange.", + player: true, + rodent: Gen::IV, + personality: "Topalov", }, ]; /// «Attacking — Ampere»; «Balanced», «Tal»: no name twice. fn style_label(st: &Style) -> String { let title = tr(st.title()); - // The default one is Rodent himself, the players' are named by their title. - if st.player || st.id == "rodent" { + // The default one is Rodent himself, the players' are named by their title, and so + // are Rodent IV's characters (their names are their titles). + if st.player || st.id == "rodent" || st.title == st.name { title.to_owned() } else { format!("{title} — {}", st.name) @@ -266,12 +662,14 @@ pub const MAIA_MAX: u32 = 2600; /// Rodent's UCI_Elo. pub const RODENT_MIN: u32 = 800; pub const RODENT_MAX: u32 = 3000; +/// Rodent IV's UCI_Elo goes to 2800 (and plays at full strength there). +pub const RODENT_IV_MAX: u32 = 2800; -/// The strengths `rival` plays. -pub fn range(rival: Rival) -> (u32, u32) { +/// The strengths `rival` plays (Rodent's by the engine of the style chosen). +pub fn range(rival: Rival, style_id: &str) -> (u32, u32) { match rival { Rival::Maia => (MAIA_MIN, MAIA_MAX), - Rival::Rodent => (RODENT_MIN, RODENT_MAX), + Rival::Rodent => style(style_id).rodent.range(), } } @@ -531,11 +929,18 @@ impl Opponent { Ok(e) => e, Err(e) => return fail(start_failure(&e.to_string())), }; - let personality = format!("personalities/{style}.txt"); - let mut setup = vec![ - ("PersonalityFile", personality.clone()), - ("OwnBook", "true".to_owned()), - ]; + // V reads a personality file; IV picks one of its list (with its books). + let st = self::style(&style); + let mut setup = match st.rodent { + Gen::V => vec![ + ("PersonalityFile", format!("personalities/{style}.txt")), + ("OwnBook", "true".to_owned()), + ], + Gen::IV => vec![ + ("Personality", st.personality.to_owned()), + ("UseBook", "true".to_owned()), + ], + }; if let Some(elo) = uci_elo { setup.push(("UCI_LimitStrength", "true".to_owned())); setup.push(("UCI_Elo", elo.to_string())); @@ -832,7 +1237,7 @@ pub fn said(rival: Rival, maia: &'static str, rodent: &'static str) -> &'static #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Engine { Maia(Model), - Rodent, + Rodent(Gen), } impl Engine { @@ -841,7 +1246,7 @@ impl Engine { pub fn input(self, strength: u32) -> (u32, f32) { match self { Engine::Maia(_) => (strength, 1.0), - Engine::Rodent => (0, 0.0), + Engine::Rodent(_) => (0, 0.0), } } } @@ -851,7 +1256,10 @@ impl Engine { pub fn engine_for(start: &Start) -> Option<(Engine, std::path::PathBuf)> { match start.rival { Rival::Maia => model_for().ok().map(|(m, p)| (Engine::Maia(m), p)), - Rival::Rodent => crate::rodent_download::installed().map(|p| (Engine::Rodent, p)), + Rival::Rodent => { + let g = style(&start.style).rodent; + g.installed().map(|p| (Engine::Rodent(g), p)) + } } } @@ -867,12 +1275,14 @@ pub fn debug_rival() -> (Rival, String) { } } -/// «Maia 1500», «Rodent V 2400», «Rodent V 2400 (Tal)» (the default style unnamed). +/// «Maia 1500», «Rodent V 2400», «Rodent V 2400 (Tal)», «Rodent IV 2000 (Petrosian)» +/// (the default style unnamed). pub fn rival_name(rival: Rival, strength: u32, style_id: &str) -> String { + let st = style(style_id); 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), + Rival::Rodent if style_id == STYLES[0].id => format!("{} {strength}", st.rodent.name()), + Rival::Rodent => format!("{} {strength} ({})", st.rodent.name(), st.name), } } @@ -880,7 +1290,7 @@ impl Session { pub fn rival(&self) -> Rival { match self.engine { Engine::Maia(_) => Rival::Maia, - Engine::Rodent => Rival::Rodent, + Engine::Rodent(_) => Rival::Rodent, } } @@ -888,13 +1298,13 @@ impl Session { pub fn rival_label(&self) -> String { match self.engine { Engine::Maia(_) => format!("Maia {}", self.strength), - Engine::Rodent => format!("Rodent V {}", self.strength), + Engine::Rodent(g) => format!("{} {}", g.name(), self.strength), } } /// Rodent's style, under his name on the bar (none for Maia and the default style). pub fn rival_style(&self) -> Option<&'static str> { - (self.engine == Engine::Rodent && self.style != STYLES[0].id) + (self.rival() == Rival::Rodent && self.style != STYLES[0].id) .then(|| tr(style(&self.style).title())) } } @@ -931,8 +1341,8 @@ pub struct Dialog { prefs: PlayPrefs, custom: bool, download: Option, - /// Rodent's download (docs/design/rodent-opponent.md §6). - rodent_download: Option, + /// Rodent's download (docs/design/rodent-opponent.md §6): which one, and how it goes. + rodent_download: Option<(Gen, crate::engine_download::Download)>, /// «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. @@ -961,11 +1371,14 @@ impl Dialog { } // A remembered strength the opponent does not play (another build's range, an // edited file): to the nearest one that is played. - let rodent_ok = crate::rodent_download::available(); - if prefs.rival == Rival::Rodent && !rodent_ok { - prefs.rival = Rival::Maia; + // A style whose Rodent is not for this system: one that is, else Maia. + if prefs.rival == Rival::Rodent && !style(&prefs.style).rodent.available() { + match STYLES.iter().find(|s| s.rodent.available()) { + Some(s) => prefs.style = s.id.to_owned(), + None => prefs.rival = Rival::Maia, + } } - let (min, max) = range(prefs.rival); + let (min, max) = range(prefs.rival, &prefs.style); prefs.strength = prefs.strength.clamp(min, max); let custom = prefs.clock.is_some_and(|c| !PRESETS.contains(&c)); Dialog { @@ -1213,12 +1626,12 @@ impl Dialog { // 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_ok = Gen::V.available() || Gen::IV.available(); let rodent = self.prefs.rival == Rival::Rodent; section( ui, &if rodent { - crate::i18n::trf("Opponent — Rodent V {elo}", &[("elo", &self.prefs.strength)]) + crate::i18n::trf("Opponent — Rodent {elo}", &[("elo", &self.prefs.strength)]) } else { crate::i18n::trf("Opponent — Maia {elo}", &[("elo", &self.prefs.strength)]) }, @@ -1267,16 +1680,22 @@ impl Dialog { } 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.", + let r = tile(ui, rodent, rodent_ok, "Rodent", about).on_hover_text(if rodent_ok { "" } else { tr( + "Rodent is not available for this system yet. When it is, it will be here.", ) }); if r.clicked() && !rodent { self.prefs.rival = Rival::Rodent; - self.prefs.strength = self.prefs.strength.clamp(RODENT_MIN, RODENT_MAX); + if !style(&self.prefs.style).rodent.available() + && let Some(st) = STYLES.iter().find(|s| s.rodent.available()) + { + self.prefs.style = st.id.to_owned(); + } + let (min, max) = range(Rival::Rodent, &self.prefs.style); + self.prefs.strength = self.prefs.strength.clamp(min, max); } }); // Each engine on its own scale (its authors'): not a person's Elo, said under it. - let (min, max) = range(self.prefs.rival); + let (min, max) = range(self.prefs.rival, &self.prefs.style); 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())) @@ -1292,7 +1711,7 @@ impl Dialog { }); ui.add_space(4.0); let note = if self.prefs.rival == Rival::Rodent { - tr("Rodent V's own rating (UCI_Elo): it does not match a person's Elo.") + tr("Rodent's own rating (UCI_Elo): it does not match a person's Elo.") } else { tr("Maia's own rating: it does not match a person's Elo.") }; @@ -1313,20 +1732,44 @@ impl Dialog { .height(400.0) .selected_text(shown) .show_ui(ui, |ui| { - for (head, player) in [(tr("Style"), false), (tr("As a player"), true)] { + // Rodent V's styles, Rodent IV's characters, then the players both + // imitate; a style whose Rodent is not for this system is greyed. + let groups = [ + (tr("Style"), false, Some(Gen::V)), + (tr("Character"), false, Some(Gen::IV)), + (tr("As a player"), true, None), + ]; + for (k, (head, player, only)) in groups.into_iter().enumerate() { + // Only what this system plays, in the order of the names as shown + // (the Tals side by side). + let mut group: Vec<&Style> = STYLES + .iter() + .filter(|st| st.player == player && only.is_none_or(|g| st.rodent == g) && st.rodent.available()) + .collect(); + if group.is_empty() { + continue; + } + if player { + group.sort_by_key(|st| style_label(st).to_lowercase()); + } + if k > 0 { + ui.separator(); + } ui.label(RichText::new(head).weak().size(11.5)); - for st in STYLES.iter().filter(|st| st.player == player) { + for st in group { ui.selectable_value(&mut self.prefs.style, st.id.to_owned(), style_label(st)) .on_hover_text(tr(st.about)); } - if !player { - ui.separator(); - } } }) .response - .on_disabled_hover_text(tr("The style is chosen for Rodent V")); + .on_disabled_hover_text(tr("The style is chosen for Rodent")); }); + // Another Rodent may play another range. + if rodent { + let (min, max) = range(self.prefs.rival, &self.prefs.style); + self.prefs.strength = self.prefs.strength.clamp(min, max); + } let about = if rodent { tr(style(&self.prefs.style).about).to_owned() } else { @@ -1434,8 +1877,18 @@ impl Dialog { } let rodent = self.prefs.rival == Rival::Rodent; let stage = self.download.as_ref().map(|d| d.stage()); - let rstage = self.rodent_download.as_ref().map(|d| d.stage()); - let rodent_there = crate::rodent_download::installed().is_some(); + // The Rodent of the style chosen: its download, if that one is going on. + let which = style(&self.prefs.style).rodent; + let rstage = self + .rodent_download + .as_ref() + .filter(|(g, _)| *g == which) + .map(|(_, d)| d.stage()); + let other_busy = self.rodent_download.as_ref().is_some_and(|(g, d)| { + *g != which + && matches!(d.stage(), crate::engine_download::Stage::Downloading { .. } | crate::engine_download::Stage::Unpacking) + }); + let rodent_there = which.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!( @@ -1444,18 +1897,25 @@ impl Dialog { ) || matches!( rstage, Some(crate::engine_download::Stage::Downloading { .. } | crate::engine_download::Stage::Unpacking) - ); + ) || other_busy; let large = crate::maia_download::installed(Model::Large).is_some(); - let rodent_missing = crate::rodent_download::available() && !rodent_there; + let rodent_missing = which.available() && !rodent_there; if !ready || !large || rodent_missing { ui.add_space(6.0); 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()); + let note = match which { + Gen::V => crate::i18n::trf( + "Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).", + &[("mb", &which.size_mb())], + ), + Gen::IV => crate::i18n::trf( + "Rodent IV is downloaded once ({mb} MB): the engine built from its authors' sources, its characters and books from their repository.", + &[("mb", &which.size_mb())], + ), + }; + ui.label(RichText::new(note).weak()); } Some(crate::engine_download::Stage::Downloading { done, total }) => { ui.add(egui::ProgressBar::new(*done as f32 / (*total).max(1) as f32).show_percentage()); @@ -1469,7 +1929,7 @@ impl Dialog { 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}", + "Could not download Rodent: {error}", &[("error", &download_failure(f))], )).color(ui.visuals().error_fg_color)); } @@ -1523,7 +1983,7 @@ impl Dialog { && (main.clicked() || (free && ui.input(|i| i.key_pressed(egui::Key::Enter)))); if pressed && !ready { if rodent { - self.rodent_download = Some(crate::rodent_download::start(ctx)); + self.rodent_download = Some((which, which.start(ctx))); self.play_after = true; } else if let Err(m) = model { self.download = Some(crate::maia_download::Download::start(ctx, m)); @@ -1743,16 +2203,16 @@ impl End { 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", + "time is up, but Rodent 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", + "Rodent's time is up, but you cannot checkmate", ), Ending::Time { .. } => tr("time is up"), Ending::Resigned { loser } if loser == self.user => "", - Ending::Resigned { .. } => said(self.start.rival, "Maia resigned", "Rodent V resigned"), + Ending::Resigned { .. } => said(self.start.rival, "Maia resigned", "Rodent resigned"), Ending::DrawAgreed => tr("by agreement"), } } diff --git a/apps/desktop/src/rodent4_download.rs b/apps/desktop/src/rodent4_download.rs new file mode 100644 index 0000000..0be0256 --- /dev/null +++ b/apps/desktop/src/rodent4_download.rs @@ -0,0 +1,188 @@ +//! Downloading Rodent IV on request (docs/decisions.md «Rodent IV»): its authors publish +//! no builds for Linux and Windows, so the engine is built from their sources at a pinned +//! commit by our workflow (.github/workflows/rodent-iv.yml) and published as a release of +//! its own; its personalities and opening books come from the authors' repository at the +//! same commit. Every file is checked against its SHA-256. Nothing is downloaded without +//! the user asking. + +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; + +use crate::engine_download::{Asset, Download, Failure, Stage, disk, fetch}; +use crate::rodent4_files::{COMMIT, FILES}; + +/// The release of our builds. +const TAG: &str = "rodent-iv-0.33"; + +/// This platform's build in the release, if there is one (checked against its SHA-256). +fn binary() -> Option { + let (file, sha256, size) = match (std::env::consts::OS, std::env::consts::ARCH) { + ("linux", "x86_64") => ("rodent-iv-linux-x86_64", "", 0), + ("windows", "x86_64") => ("rodent-iv-windows-x86_64.exe", "", 0), + ("macos", "aarch64") => ("rodent-iv-macos-arm64", "", 0), + _ => return None, + }; + // Not offered until the build is published and its sum written here. + (!sha256.is_empty()).then_some(Asset { + file, + sha256, + size, + zip: false, + }) +} + +#[cfg(windows)] +const EXE: &str = "rodent_iv.exe"; +#[cfg(not(windows))] +const EXE: &str = "rodent_iv"; + +/// Whether Rodent IV can be had on this platform (or is at hand for development). +pub fn available() -> bool { + std::env::var_os("CP_RODENT4").is_some() || binary().is_some() +} + +/// The download in all: the engine, its personalities and books. +fn total() -> u64 { + binary().map_or(0, |b| b.size) + FILES.iter().map(|f| f.1).sum::() +} + +pub fn size_mb() -> u64 { + (total() + 500_000) / 1_000_000 +} + +/// `/engines/rodent_iv_0.33/` (`CP_RODENT4` elsewhere: development). +pub fn dir() -> Option { + if let Some(d) = std::env::var_os("CP_RODENT4") { + return Some(PathBuf::from(d)); + } + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("engines").join("rodent_iv_0.33")) +} + +/// Written last, once the engine started from its folder with everything beside it. +const COMPLETE: &str = ".complete"; + +/// The installed engine, if it is all there. +pub fn installed() -> Option { + let d = dir()?; + let exe = d.join(EXE); + let whole = d.join("personalities").join("basic.ini").is_file(); + let marked = std::env::var_os("CP_RODENT4").is_some() || d.join(COMPLETE).is_file(); + (exe.is_file() && whole && marked).then_some(exe) +} + +/// Removes the downloaded engine (a broken one). +pub fn remove() -> std::io::Result<()> { + if std::env::var_os("CP_RODENT4").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, total(), run) +} + +/// Books three personalities name by a path not in the authors' files (a case or a dash +/// off): a copy goes under that name, so that they open their book (the engine takes +/// books only from the personality's file). (file in the repository, name it is read by) +const BOOK_NAMES: &[(&str, &str)] = &[ + ("books/guide/Strangler.bin", "books/guide/strangler.bin"), + ( + "books/players/ph-spassky2.bin", + "books/players/ph_spassky2.bin", + ), + ("books/guide.bin", "books/guide/guide.bin"), +]; + +/// A path of the repository as it goes into a URL («#readme.txt» has a «#»). +fn url_path(path: &str) -> String { + path.replace('#', "%23").replace(' ', "%20") +} + +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 grand = total(); + let mut base = 0u64; + // One file's progress as part of the whole. + let step = |base: u64| { + move |s: Stage| match s { + Stage::Downloading { done, .. } => report(Stage::Downloading { + done: base + done, + total: grand, + }), + other => report(other), + } + }; + let result = (|| { + let exe = dir.join(EXE); + let url = format!( + "https://github.com/vrubelroman/chessPenguin/releases/download/{TAG}/{}", + bin.file + ); + fetch(&url, &exe, &bin, &step(base), cancel)?; + base += bin.size; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(disk)?; + } + for &(path, size, sha256) in FILES { + let dest = dir.join(path); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent).map_err(disk)?; + } + let asset = Asset { + file: path, + sha256, + size, + zip: false, + }; + let url = format!( + "https://raw.githubusercontent.com/nescitus/rodent-iv/{COMMIT}/{}", + url_path(path) + ); + fetch(&url, &dest, &asset, &step(base), cancel)?; + base += size; + } + report(Stage::Unpacking); + for (file, name) in BOOK_NAMES { + // Where names do not differ by case (Windows, macOS) it is the same file. + if !dir.join(name).exists() { + std::fs::copy(dir.join(file), dir.join(name)).map_err(disk)?; + } + } + crate::rodent_download::check_runs(&exe)?; + std::fs::write(dir.join(COMPLETE), TAG).map_err(disk)?; + Ok(exe) + })(); + if result.is_err() { + // Nothing half-installed is left behind. + let _ = std::fs::remove_dir_all(&dir); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_file_is_where_the_engine_looks_for_it() { + assert_eq!(COMMIT.len(), 40); + assert!(FILES.iter().any(|f| f.0 == "personalities/basic.ini")); + assert!(FILES.iter().any(|f| f.0 == "personalities/tal.txt")); + assert!(FILES.iter().any(|f| f.0 == "books/rodent.bin")); + assert!(FILES.iter().all(|f| f.2.len() == 64 && !f.0.contains(".."))); + assert_eq!(url_path("books/#readme.txt"), "books/%23readme.txt"); + // The books copied under the names the personalities use are downloaded. + for (file, _) in BOOK_NAMES { + assert!(FILES.iter().any(|f| f.0 == *file), "{file}"); + } + } +} diff --git a/apps/desktop/src/rodent4_files.rs b/apps/desktop/src/rodent4_files.rs new file mode 100644 index 0000000..e7d3611 --- /dev/null +++ b/apps/desktop/src/rodent4_files.rs @@ -0,0 +1,454 @@ +//! Generated by scripts/rodent4-manifest.py: the personalities and opening books of +//! Rodent IV as they are in the authors' repository at `COMMIT`, with their sizes and +//! SHA-256 (each is checked as it is downloaded). + +pub const COMMIT: &str = "e8d84c8c8c189a1cf4eb27c578fc573af3b916d2"; + +/// (path in the repository, bytes, SHA-256). +pub const FILES: &[(&str, u64, &str)] = &[ + ( + "books/#readme.txt", + 190, + "48d94c1e55cb6f98476bccaf9432166d3bb07aea664bf595c4b85a65ef43a714", + ), + ( + "books/guide.bin", + 3056, + "168abc6dc0af6cf5c1719403e51e367cc56c5929531c8f35b8000dcda0de84ba", + ), + ( + "books/guide/#readme.txt", + 1263, + "7a73f72ac924f4988b88da2ea6ad3168c99107202a690905e011b0f3e66f1875", + ), + ( + "books/guide/Strangler.bin", + 10144, + "35303138aacbea4ce768414f4b7c709e5705e7d17f57a487136d6575634dfbf1", + ), + ( + "books/guide/active.bin", + 298368, + "4ce06ffe8208ea462623d4aa2cd76e5fffb43fee568eec926dda58c49de39a74", + ), + ( + "books/guide/cat.bin", + 3280, + "6b38a429a10d9214b2bef03ddff3f1d07ba29486e47d2b23a52ca256b7af4929", + ), + ( + "books/guide/closed.bin", + 1312, + "eb663e1ed1e6cffbfcc33f2aed8b080df70dd6fe3e0f549a3ad20938f37f2da6", + ), + ( + "books/guide/cs.bin", + 4336, + "ea213e6c49e32b0b0e6ab1ce48b91fff354a05893d3a7fcaef595c1b82c8ee32", + ), + ( + "books/guide/empty.bin", + 16, + "60c69a3e87bf5c4f1e546bec45f262690bcf5494c4ecac2616bf2f731afa152a", + ), + ( + "books/guide/exchange.bin", + 1824, + "98b191cbb8426bf4098c7330861d441315687325e5f27d7f9dc623c163c2ff39", + ), + ( + "books/guide/flank.bin", + 186144, + "da019cc249e2f5e9559067faa7cbfeadde405cdd5f77dabd8059589329d88243", + ), + ( + "books/guide/grandpa.bin", + 11584, + "2c2d177e4695e32e22915dc4d2d624e834d59a75aef889f9a3d2190b6d9de71e", + ), + ( + "books/guide/low.bin", + 2432, + "549b341172c980aa7b47750b8caafa9e5e4df8161f9e9a3ae84df65a7db135a5", + ), + ( + "books/guide/ph-exoticbook.bin", + 9361568, + "fa0f55de6bd345521633f1ad0f3171823f4ff36c8784b123c9963278bc0cac13", + ), + ( + "books/guide/ph-gambitbook.bin", + 8407936, + "f2dddc37343b155624fddb08a7743965e806b717ac87985f887643e126119f14", + ), + ( + "books/guide/simple.bin", + 1136, + "5c5655286dfb7828ecdc516ec5a04bc7ff82ee6d4d6d3b1e6737eea0a2a3f01c", + ), + ( + "books/guide/solid.bin", + 702704, + "b6ed13b48ede300b9c33944e12d899daaab1fc120d129379bfe234f2f65dffc8", + ), + ( + "books/guide/tricky.bin", + 236128, + "ea008c67e321c3460298777be6b4ad6d21384589c148bec16c8295b84870ab63", + ), + ( + "books/hist/#readme.txt", + 285, + "7997dfcd3f1f1afd8da16ddddada703eca0a74c0e57b7ef7357e90f075c0b6e3", + ), + ( + "books/hist/_31to80.bin", + 588640, + "c51764eab0ad6ab0659c6aba8bdfa7cec930e88dfc5887efce1e31a5ca80e81f", + ), + ( + "books/hist/_81to06.bin", + 1393952, + "ddd3fe064d17ee52e6653dbafbd6280d2d85f09da50352366c3515585c0c8d19", + ), + ( + "books/hist/_post06.bin", + 1474384, + "b3b1fb48054e4737b80acebe8851c152188243439bc7194b3faa01be85116ee9", + ), + ( + "books/hist/_pre30.bin", + 169856, + "77aeca2bd8ee5996cd95683531f008b4e038c6f8a1d41550d5b02c73d4f17257", + ), + ( + "books/main/micro.bin", + 76400, + "40b063b1a2dfff9964b3e43f76e321863a3bc40d79c9ec71d604116d5cb0fb0e", + ), + ( + "books/main/mini.bin", + 154576, + "cde1a83f2f8d067920d9bd63bd6e66840ec8b74b4e85ed43b26e3dfcb5c0ba1d", + ), + ( + "books/main/small.bin", + 311296, + "ef9c73df2d1df15cfd70bea5f6ed074298a583fb2248a2ea626f008bbad55148", + ), + ( + "books/players/#readme.txt", + 908, + "fb5a69bee93feec68ee8ca24a86f7877b008a01b8438ffe5d0ae8f6874a387ad", + ), + ( + "books/players/bn-bosboom.bin", + 538960, + "c75133dc14d07034d73e7faace7adbe6a2f8ea3a5b55ff6e2f3b6cd8b3c13b48", + ), + ( + "books/players/morphy.bin", + 1440, + "57e6e7619ac7647acaf561e0ebc2f065c32835cadca2029386ea4bbb347f58b0", + ), + ( + "books/players/nimzowitsch.bin", + 261040, + "64f43e651515f68c5a8e5eb1c970cfc6b49b47e30abf3a078659b5465bf79459", + ), + ( + "books/players/petrosian.bin", + 850048, + "0393a98eaa0a86203066494447d9a90255518499ba702933118b72af281a364e", + ), + ( + "books/players/ph-anand2.bin", + 1998384, + "ca5d7a52b33f78e857fb44f6157ac83b943dcd2e36c630c77e107a7c8d5f94ad", + ), + ( + "books/players/ph-anderssen2.bin", + 8539632, + "7edf078361d6462584107b0b37d9c24ee6dec297936bacc6f4085069687256eb", + ), + ( + "books/players/ph-botvinnik2.bin", + 1764656, + "dd041dad209ae2278f94ea3bd3d59aa280b07ee5b6f5e856aef87cb800bdd7e7", + ), + ( + "books/players/ph-fischer2.bin", + 1728896, + "1b8bc31b15a135c0cef705e633524583cea304f4c44cf705bb7b0a58d0be1279", + ), + ( + "books/players/ph-karpov2.bin", + 2287088, + "aed5d14526826482414ae9a8334cf84ee812de6da01e9f50ad14b48d3ebd7668", + ), + ( + "books/players/ph-larsen2.bin", + 2086640, + "c88749872fa2d8f99b699d21c30e8e4b61b1a5cd84feef9eebd3354be70f37c3", + ), + ( + "books/players/ph-lasker2.bin", + 1752464, + "7c11cc10212424fb8dd24da6e6e4fabdb6f9689d5e0eb9cd4c8d7b7494a44ef9", + ), + ( + "books/players/ph-reti2.bin", + 1644768, + "50837dc5bed4f94a35449732c676dba3bafde132b219b63ea683b1159988f9f2", + ), + ( + "books/players/ph-rubinstein2.bin", + 1705984, + "3dd2f06df72c2666d37ef3e397bec296add5d4e3de45bfeed6c07823de21cb36", + ), + ( + "books/players/ph-spassky2.bin", + 2021984, + "d0c981ea25e3ab6e48984bcdd587e74d08aa6bced545b15b0d4cf3d29b8e2e3b", + ), + ( + "books/players/ph-tal2.bin", + 2062464, + "2e7923a363a4d24fa10cda6991dc5c289cde57d536b358b45b29a157690c9c04", + ), + ( + "books/players/ph-tarrasch2.bin", + 1677472, + "16954ddd54e2aa82dddd418fba651a6f19052205d7aa203fe9d6098a60c700b4", + ), + ( + "books/players/ph-topalov2.bin", + 1828864, + "5a07a21d75424b59b7c1a51387868bbd0f55cf0e3eb83d223b9f0bdac410dfdf", + ), + ( + "books/players/rj-alekhine.bin", + 865072, + "df46561ddcd723f3f01fc7c6fbab290b0c9eb2a3594a87c79eadbd87fdcc2737", + ), + ( + "books/players/rj-kasparov.bin", + 1617072, + "06e06f3b061f31002a58a39ddf26a9fd5064b827522b06cedde25198d54d9d45", + ), + ( + "books/players/rj-kortchnoi.bin", + 135424, + "4e2ff5a5be4aee43c56998015cc800f3537d16371dfab4be3726734b252727c9", + ), + ( + "books/players/rj-marshall.bin", + 300688, + "c11f9dab58a0ef1efe655ca92ef010b4384e819affc7116c6ba110f33622312c", + ), + ( + "books/players/steinitz.bin", + 81280, + "14d96f0b54b578bdead1cd214bc8fc6442f5a09a7a99f3a9ea129f47df17aa2b", + ), + ( + "books/rodent.bin", + 10179008, + "4a65869ba4081398bfa0804b953502352815dcfae49ad5af9726a69d46047786", + ), + ( + "personalities/alekhine.txt", + 3517, + "3d618e0a35cbcdc2467f5f114790646fe40050bea78c62c5520e888a02553bb8", + ), + ( + "personalities/amanda.txt", + 2510, + "ff04a71cd2f1eb626d8805d37f2dd3a6904d93a1c93c5290553431453fea26b6", + ), + ( + "personalities/ampere.txt", + 2498, + "a9ce7312c0fb8f3b0c46e3ff58e79cb10a6fd092f1cb69c480e102461861e912", + ), + ( + "personalities/anand.txt", + 3366, + "f01b264bf221118af21f8576c8234fc7259ee32b008d7f604764f14abd38965a", + ), + ( + "personalities/anderssen.txt", + 3274, + "5d4235febae596783c0d68c2567900440addfebf6697c48ad5d0ada2eb94cceb", + ), + ( + "personalities/basic.ini", + 2719, + "abe0ebe031c00009d3d3bbce7daf218e54f0422a8e6ded3c29d6e9c3350551bd", + ), + ( + "personalities/bosboom.txt", + 2904, + "172d473052ee04141235b90bceb2eace235c1c33f7c46aae292a22ceeebbaa85", + ), + ( + "personalities/botvinnik.txt", + 3385, + "e4de674084b289e6a5eca65edce542c948e3e75ffa25c155c7af56069ff8816e", + ), + ( + "personalities/cloe.txt", + 2483, + "dfe5a303071440c531b91437d81a47a0be1d51b4e63bdeb64794a7c2d4f504a9", + ), + ( + "personalities/deborah.txt", + 2489, + "7d2203efdd3972a1b9bd836dc9237121873de26200f515378bc24850446f85f7", + ), + ( + "personalities/default.txt", + 1091, + "1470a3e385b26efdd37d7ba30aae50e008a35eea78f03f683db82d02d1a2df2e", + ), + ( + "personalities/defender.txt", + 2455, + "7b0d1e377d0862d18f8101e2068eed8486558416997fe596c42f589c525aae7c", + ), + ( + "personalities/dynamic.txt", + 2543, + "1edd02be3baddba2f5056db8fdabfe549488c0f9832e553677227e98b3a0f404", + ), + ( + "personalities/fischer.txt", + 3333, + "ee2ab4e175f0dbee88f2f12595393d14001915670e086198139d15ad86eae577", + ), + ( + "personalities/grumpy.txt", + 2531, + "0ff254a3439d947756fdf748b94fcceb82cc202b46ded10e839a7204fbce3c03", + ), + ( + "personalities/karpov.txt", + 2893, + "9ea8a26ddd30ebb7085193d2c94119bdeb9535cd7b43a283741ad27244c78aee", + ), + ( + "personalities/kasparov.txt", + 2949, + "0167481c1a12c5ee50dcaae8d9a5de80ca5baccb44114e603ae8395cd4244f43", + ), + ( + "personalities/kortchnoi.txt", + 3084, + "36fa917d841447df9aa2168f4f736c80d1506afe270c015ceba6a013c80802ad", + ), + ( + "personalities/larsen.txt", + 3430, + "e0ae364f22630da9bfbe4a415ad05555a19c526a8efba2e0e716c23b603bc60b", + ), + ( + "personalities/lasker.txt", + 2850, + "2f522070cc68bede8c77d6e7040939c0ba24aba7017988d417b37ec9a424c388", + ), + ( + "personalities/marshall.txt", + 2960, + "38dfc223a8067f5a041e011c25c914e56bebbfd78e0dc10648c6a73a228f5711", + ), + ( + "personalities/morphy.txt", + 2486, + "8e6d9aa1658deda43c280bef69ec6e0914c883e57f118a22c7a5edbe7cfef7de", + ), + ( + "personalities/nimzowitsch.txt", + 2475, + "53b1825b4dd6ea709b5fcfc401ce9ab920ffcd03b9e54936e8fa3c36812ceae1", + ), + ( + "personalities/partisan.txt", + 2504, + "483d94226b4d5b42105db4c28c0f078ae096a6f26777ee558e5c7afabc8730fe", + ), + ( + "personalities/pawnsacker.txt", + 2563, + "bf92b869e67fce75d967f8c385787ef52ac62ffa612917184d7b6f75caff7941", + ), + ( + "personalities/pedrita.txt", + 2482, + "3f9858b2e7912e666d4b48b6f6509d712b63428db06902b83e45aadef2988ad3", + ), + ( + "personalities/petrosian.txt", + 3350, + "e4558a9035d0e21afa9bbd453f5ded76d22fb274ca39889cf2163d7472879ef4", + ), + ( + "personalities/preston.txt", + 2487, + "a232ea602749587fbd15889a8948403c5ac2687234caca538d3aa6b641741944", + ), + ( + "personalities/reti.txt", + 3327, + "8d15e479e118903309afe215cd070faaa2e4337b2b62809a26476113a9469d20", + ), + ( + "personalities/rubinstein.txt", + 3384, + "efb9dda6d01b824ba39260881deb18a22c22774d7946eeb6adbd3d4d4c18ca39", + ), + ( + "personalities/simple.txt", + 2510, + "19f83fb05f96039a34e0e9a36bf66fc841693f70d73ee2a243df42e90caf1613", + ), + ( + "personalities/spassky.txt", + 3347, + "000da9c591c8e63fe5e4b11c812c42d3e700032e034f75934d67faba089b4bbd", + ), + ( + "personalities/spitfire.txt", + 2448, + "5b42cac56aa4fbab4b6dff48e86fbfec8744e27bb310475b9bc9e91746e519f6", + ), + ( + "personalities/steinitz.txt", + 2572, + "f7ab0efd23c94f96f025104dc82eab993163d7a7523cab8b612add1d85d1b338", + ), + ( + "personalities/strangler.txt", + 2526, + "3ed1809e19ba622c165b9fbf8eb10f056a3acbb3a0ee2a4c32b9488919d85409", + ), + ( + "personalities/swapper.txt", + 2513, + "d1b8ec5e016452f002609c32bc575fb9ee47ba4e0db671f82215009c731187fc", + ), + ( + "personalities/tal.txt", + 2459, + "f6b58d7cc9e7d2fcdbbc24a20ea72035d05ca5ed5e3401bda240b1b298ce149d", + ), + ( + "personalities/tarrasch.txt", + 2546, + "6fafaf4cb8ec37439c2471a26b9be471a35d5e14faf1a624bb2fe9edb6f3f496", + ), + ( + "personalities/topalov.txt", + 3358, + "0e5a9fc33d3ade50d7eaa68a06d29131151d270d5d0f3afd5d408bfb9081e4d8", + ), +]; diff --git a/apps/desktop/src/rodent_download.rs b/apps/desktop/src/rodent_download.rs index 146856d..c7a6dbc 100644 --- a/apps/desktop/src/rodent_download.rs +++ b/apps/desktop/src/rodent_download.rs @@ -152,7 +152,7 @@ fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { /// 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> { +pub(crate) 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() { diff --git a/docs/decisions.md b/docs/decisions.md index 250165b..4067043 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -117,6 +117,13 @@ - **Только на компьютере**; на телефоне остаётся Maia. - Перед реализацией — замер силы Rodent V по шкале Lichess (как у Maia) и проверка сборки на Linux, Windows, macOS. +## Rodent IV: его персонажи — в списке стилей Rodent (2026-10-26) + +Владелец: «заюзаем rodent 4 со всеми его стилями… людям хочется больше персонажей». Согласовано: +- **Один соперник «Rodent»** в диалоге игры: его список расширяется персонажами Rodent IV — характеры (Amanda, Defender, Strangler…) к стилям, 22 великих шахматиста (Алехин… Таль) к «Как игрок». Какой движок играет (V или IV), программа выбирает по персонажу; сила — по шкале движка (IV 800–2800, V 800–3000). +- **Движок IV собираем сами** из исходников авторов (GPL-3, зафиксированная версия) в нашем CI для Linux, Windows и macOS и выкладываем отдельным выпуском на GitHub; программа скачивает его по кнопке с проверкой суммы. Персонажи и книги скачиваются из репозитория авторов на той же версии, каждый файл с проверкой суммы. На macOS Rodent появляется впервые (V там нет). +- **На телефоне** — только Maia (игра) и Stockfish (анализ), других движков нет. + ## Сила соперника — по шкале самого движка (2026-10-26) Владелец: «запарился с калибровкой движков» — в диалоге игры два движка, Maia и Rodent V, у каждого **своя шкала, как её заявляют авторы**: Maia 600–2600 (рейтинг, на котором обучена сеть; ходы — выбором по её вероятностям, температура 1), Rodent V 800–3000 (UCI_Elo; у Rodent по-прежнему выбирается стиль). Под ползунком сказано, что это рейтинги самих движков и Эло человека они не соответствуют. Автопереключения Maia → Rodent за 2100 больше нет; при смене движка сила приводится в его диапазон. Пересчёт по замерам (`research/maia-strength.md`, `research/rodent.md`) остаётся исследованием и в программе не используется На телефоне — так же, Maia 600–2600 (владелец, 2026-10-26). diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 727e697..e693cbb 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -51,7 +51,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно, `=ask` — как кнопка «Анализировать»: окно или, если параметры уже выбирали, сразу анализ), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_COMMENT_EDIT=1` — открыть редактор комментария на текущем ходе, `CP_SHAPE=Ge2e4,Rd5` — нарисовать стрелки/круги на доске у текущего хода (как правой кнопкой), `CP_TYPE=текст` — напечатать текст в поле с фокусом через 2,5 с (после `CP_KEYS`, которые начинаются со 2-й секунды, если их мало), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_PLAY=white|black[,5+3|none][,1500]` — сразу начать партию с Maia (`CP_PLAY=dialog` — открыть диалог «Игра с компьютером»), `CP_MAIA=путь/maia3-5m.pt` — веса Maia из этого файла вместо скачанных, `CP_RIVAL=rodent[:стиль]` — соперник партии, начатой хуком `CP_PLAY`/`CP_PLAY_FROM` (стиль — имя файла личности: `tal_hybrid`, `ampere`…), `CP_RODENT=папка` — Rodent V из этой папки (`rodent_v` и `personalities/`, `nets/`, `books/`) вместо скачанного; пустая папка — «не скачан», загрузка пойдёт в неё, `CP_PLAY_AUTO=1` — за пользователя тоже ходит Maia, быстро (партия до конца без мыши), `CP_PREMOVE=e7e5` — в начале партии поставить этот предход (виден подсветкой, играется сразу после ответа Maia, если легален), `CP_PASTE_LINE="<текст>"` — после `CP_OPEN`/`CP_PLY` вставить текст как вариант, как Ctrl+V (`docs/design/paste-variation.md`), `CP_PLAY_FROM=dialog|white|black[,сила]` — «Играть отсюда…» с хода `CP_PLY`: диалог или сразу партия, `CP_TRAIN=1` — «Учить дебют до этого хода» с хода `CP_PLY`, `CP_TRAIN_MOVES="e2e4 e7e5"` — ходы тренировки как с доски (UCI; неверный — ошибка), `CP_TRAIN_KEEP=1` — последний неверный ход хука остаётся показанным, `CP_TRAINING_FILE=путь` — статистика тренировок в этом файле вместо `training.json`, `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно, `=ask` — как кнопка «Анализировать»: окно или, если параметры уже выбирали, сразу анализ), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_COMMENT_EDIT=1` — открыть редактор комментария на текущем ходе, `CP_SHAPE=Ge2e4,Rd5` — нарисовать стрелки/круги на доске у текущего хода (как правой кнопкой), `CP_TYPE=текст` — напечатать текст в поле с фокусом через 2,5 с (после `CP_KEYS`, которые начинаются со 2-й секунды, если их мало), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_PLAY=white|black[,5+3|none][,1500]` — сразу начать партию с Maia (`CP_PLAY=dialog` — открыть диалог «Игра с компьютером»), `CP_MAIA=путь/maia3-5m.pt` — веса Maia из этого файла вместо скачанных, `CP_RIVAL=rodent[:стиль]` — соперник партии, начатой хуком `CP_PLAY`/`CP_PLAY_FROM` (стиль — `id` из `STYLES` в `play.rs`: у Rodent V имя файла личности, `tal_hybrid`, `ampere`…; у Rodent IV `iv_` и имя, `iv_petrosian`, `iv_amanda`…), `CP_RODENT4=папка` — Rodent IV из этой папки (`rodent_iv`, `personalities/`, `books/`) вместо скачанного, `CP_RODENT=папка` — Rodent V из этой папки (`rodent_v` и `personalities/`, `nets/`, `books/`) вместо скачанного; пустая папка — «не скачан», загрузка пойдёт в неё, `CP_PLAY_AUTO=1` — за пользователя тоже ходит Maia, быстро (партия до конца без мыши), `CP_PREMOVE=e7e5` — в начале партии поставить этот предход (виден подсветкой, играется сразу после ответа Maia, если легален), `CP_PASTE_LINE="<текст>"` — после `CP_OPEN`/`CP_PLY` вставить текст как вариант, как Ctrl+V (`docs/design/paste-variation.md`), `CP_PLAY_FROM=dialog|white|black[,сила]` — «Играть отсюда…» с хода `CP_PLY`: диалог или сразу партия, `CP_TRAIN=1` — «Учить дебют до этого хода» с хода `CP_PLY`, `CP_TRAIN_MOVES="e2e4 e7e5"` — ходы тренировки как с доски (UCI; неверный — ошибка), `CP_TRAIN_KEEP=1` — последний неверный ход хука остаётся показанным, `CP_TRAINING_FILE=путь` — статистика тренировок в этом файле вместо `training.json`, `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки diff --git a/packaging/rodent-iv/home-dir.patch b/packaging/rodent-iv/home-dir.patch new file mode 100644 index 0000000..f85e614 --- /dev/null +++ b/packaging/rodent-iv/home-dir.patch @@ -0,0 +1,16 @@ +diff --git a/sources/src/rodenthome.cpp b/sources/src/rodenthome.cpp +index 058cdaa..e8018b7 100755 +--- a/sources/src/rodenthome.cpp ++++ b/sources/src/rodenthome.cpp +@@ -199,7 +199,10 @@ void SetRodentHomeDir() { + } else { + char exe_path[1024]; + // getting the current executable location ... +- readlink("/proc/self/exe", exe_path, sizeof(exe_path)); ++ // The link's target is not null-terminated: terminate it, or stray bytes ++ // after it make a wrong home directory now and then. ++ ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1); ++ exe_path[len > 0 ? len : 0] = '\0'; + *(strrchr(exe_path, '/') + 1) = '\0'; + + RodentHomeDirWStr = CStr2WStr(exe_path); diff --git a/scripts/rodent4-manifest.py b/scripts/rodent4-manifest.py new file mode 100644 index 0000000..c19dfbe --- /dev/null +++ b/scripts/rodent4-manifest.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""The files of Rodent IV that ChessPenguin downloads from the authors' repository +(personalities and opening books, docs/decisions.md «Rodent IV»), with sizes and SHA-256, +written as apps/desktop/src/rodent4_files.rs. + + git clone https://github.com/nescitus/rodent-iv /tmp/rodent-iv + git -C /tmp/rodent-iv checkout + python3 -I scripts/rodent4-manifest.py /tmp/rodent-iv +""" +import hashlib +import os +import subprocess +import sys + +repo = sys.argv[1] +root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +commit = subprocess.run(["git", "-C", repo, "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() +files = [] +for top in ("personalities", "books"): + for dirpath, _, names in os.walk(os.path.join(repo, top)): + for n in sorted(names): + path = os.path.join(dirpath, n) + rel = os.path.relpath(path, repo).replace(os.sep, "/") + # Chess960 is not played here. + if rel.endswith("guide_960.bin"): + continue + data = open(path, "rb").read() + files.append((rel, len(data), hashlib.sha256(data).hexdigest())) +files.sort() +out = [ + "//! Generated by scripts/rodent4-manifest.py: the personalities and opening books of", + "//! Rodent IV as they are in the authors' repository at `COMMIT`, with their sizes and", + "//! SHA-256 (each is checked as it is downloaded).", + "", + f'pub const COMMIT: &str = "{commit}";', + "", + "/// (path in the repository, bytes, SHA-256).", + "pub const FILES: &[(&str, u64, &str)] = &[", +] +out += [f' ("{p}", {s}, "{h}"),' for p, s, h in files] +out += ["];", ""] +open(os.path.join(root, "apps", "desktop", "src", "rodent4_files.rs"), "w").write("\n".join(out)) +print(len(files), "files,", sum(s for _, s, _ in files) // 1_000_000, "MB, commit", commit)