Android: Rodent IV as a second opponent, with its characters and famous players
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

The play sheet chooses Maia or Rodent IV, and Rodent's character in a full-screen
list (docs/design/android-rodent.md, docs/decisions.md «Rodent IV на телефоне»).
The engine is built from its authors' sources by androidApp/scripts/rodent4.sh
(patches: no wordexp.h on bionic; the search thread took its parameter by reference,
which clang builds read after it was gone) and ships in both APKs; the opening books
are one checked download. Rodent's tables, its book manifest and its opponent loop
move from the desktop into crates/play, shared by both apps; uci's EngineConfig takes
an environment (RODENT4HOME).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-27 03:03:02 +03:00
parent 3dac4a185b
commit b3774d1651
42 changed files with 4098 additions and 951 deletions

View file

@ -4,6 +4,11 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
## [Unreleased]
- Android: Rodent IV joins Maia as an opponent. «Play» opens the sheet with the choice of
Maia or Rodent IV and, for Rodent, one of its 13 characters or 22 famous players (Tal,
Kasparov, Karpov…), each with its own strength scale (Rodent: 800–2800). The engine is
inside both APKs; its opening books are one download of 59 MB, removable in Settings,
and «No book» plays without them. Rematches and put-aside games keep the opponent.
- A game against the computer can be put aside and continued later: «⏸ Put aside» in
the game, the main answer of «The game is on», and closing the window put it aside;
a card on the library's shelf continues it with the clocks as they were. A game a

View file

@ -108,15 +108,25 @@ personality), by `.github/workflows/rodent-iv.yml`, and published as the release
`rodent-iv-0.33` of this repository. On the user's request the program downloads
that build (SHA-256 pinned in `apps/desktop/src/rodent4_download.rs`) and the engine's
personalities and opening books from the authors' repository at the same commit (each file's
SHA-256 pinned in `apps/desktop/src/rodent4_files.rs`) into the user's data directory. It runs
SHA-256 pinned in `crates/play/src/rodent4_files.rs`) into the user's data directory. It runs
as a separate program through UCI.
On Android the engine is built from the same commit with the same fix and two more,
`packaging/rodent-iv/think-thread.patch` (the search thread read its position from a dead
stack frame; clang builds searched garbage) and `packaging/rodent-iv/android.patch` (bionic has
no `wordexp`), by `androidApp/scripts/rodent4.sh`; the executable and the personalities are in
the APK (both builds), with the license, the authors' README and the credits of the books
(`licenses/rodent-iv` among the APK's assets). The opening books the characters use are
downloaded on the user's request from the authors' repository at the same commit, each file
checked against its SHA-256.
- License: GNU General Public License version 3 (https://github.com/nescitus/rodent-iv/blob/master/LICENSE);
source: the commit above.
- The opening books come as the authors publish them, with their own credits (`#readme.txt`
in each folder of `books/`).
- Three personalities (Strangler, Spassky, Deborah) name their book by a path not in the
authors' files; the program puts a copy of the book under that name.
authors' files; the program puts a copy of the book under that name (on Android the book is
saved under that name).
## Stockfish (engine)

View file

@ -68,6 +68,17 @@ val stockfish = tasks.register<Exec>("stockfish") {
outputs.dir(stockfishOut)
}
/// Rodent IV for Android (scripts/rodent4.sh, docs/design/android-rodent.md): the executable
/// and its personalities in both builds; its opening books are downloaded on request.
val rodent4Out = layout.buildDirectory.dir("rodent4")
val rodent4 = tasks.register<Exec>("rodent4") {
environment("ANDROID_NDK_HOME", ndkHome)
commandLine(File(rootDir, "scripts/rodent4.sh").path, rodent4Out.get().asFile.path)
inputs.file(File(rootDir, "scripts/rodent4.sh"))
inputs.dir(File(repo, "packaging/rodent-iv"))
outputs.dir(rodent4Out)
}
/// The sample games, the piece sets, the board images and sounds of the desktop app, as
/// app assets.
val bundleAssets = tasks.register<Copy>("bundleAssets") {
@ -95,7 +106,14 @@ val bundleAssets = tasks.register<Copy>("bundleAssets") {
from(stockfishOut.map { it.dir("source") }) {
into("licenses/stockfish")
}
dependsOn(stockfish)
// Rodent IV's personalities, copied into its home folder on the phone (RodentFiles).
from(rodent4Out.map { it.dir("home/personalities") }) {
into("rodent4/personalities")
}
from(rodent4Out.map { it.dir("source") }) {
into("licenses/rodent-iv")
}
dependsOn(stockfish, rodent4)
into(bundled)
}
@ -183,6 +201,7 @@ android {
getByName("main") {
jniLibs.directories.add(rustLibs.get().asFile.path)
jniLibs.directories.add(stockfishOut.get().dir("jniLibs").asFile.path)
jniLibs.directories.add(rodent4Out.get().dir("jniLibs").asFile.path)
kotlin.directories.add(bindings.get().asFile.path)
assets.directories.add(bundled.get().asFile.path)
}
@ -191,7 +210,8 @@ android {
}
}
packaging {
// Unpacked at install: Stockfish runs from nativeLibraryDir as its own process.
// Unpacked at install: Stockfish and Rodent IV run from nativeLibraryDir as their
// own processes.
jniLibs {
useLegacyPackaging = true
}
@ -206,7 +226,7 @@ kotlin {
}
tasks.named("preBuild") {
dependsOn(uniffiBindings, bundleAssets, stockfish)
dependsOn(uniffiBindings, bundleAssets, stockfish, rodent4)
}
dependencies {

View file

@ -12,6 +12,7 @@ import io.github.vrubelroman.chesspenguin.data.EngineFiles
import io.github.vrubelroman.chesspenguin.data.MaiaFiles
import io.github.vrubelroman.chesspenguin.data.MaiaGames
import io.github.vrubelroman.chesspenguin.data.PlayerGames
import io.github.vrubelroman.chesspenguin.data.RodentFiles
import io.github.vrubelroman.chesspenguin.data.Sounds
import io.github.vrubelroman.chesspenguin.data.Library
import io.github.vrubelroman.chesspenguin.data.OnlineDownloads
@ -36,7 +37,9 @@ class ChessPenguinApp : Application() {
val engineFiles by lazy { EngineFiles(this, scope) }
/// Maia's weights, downloaded on request (android-play.md §31).
val maiaFiles by lazy { MaiaFiles(this, scope) }
/// The game against Maia in hand (android-play.md §31.7).
/// Rodent IV's home and its book pack (android-rodent.md).
val rodentFiles by lazy { RodentFiles(this, scope) }
/// The game against the computer in hand (android-play.md §31.7).
val maiaGames by lazy { MaiaGames(this) }
/// The players' databases: games against Maia written by themselves (player-games.md).
val playerGames by lazy { PlayerGames(this, library) }

View file

@ -33,7 +33,7 @@ sealed interface NetState {
}
/// A file of known size and SHA-256 fetched on request into the app's storage: the
/// engine's network, Maia's weights.
/// engine's network, Maia's weights, a book of Rodent IV.
data class FileSpec(
/// Folder in the app's files, and the file's name.
val dir: String,
@ -45,6 +45,9 @@ data class FileSpec(
val title: String,
/// The preferences that keep the system's download id (one file each).
val prefs: String,
/// The folder is the file's own: other files there (of other versions) are removed.
/// Not for a folder of several files (Rodent's books: their pack sees to them).
val ownFolder: Boolean = true,
)
/// The download is the system's (DownloadManager): it goes on with the app closed,
@ -65,7 +68,7 @@ class CheckedDownload(private val context: Context, private val scope: Coroutine
init {
// Files of other versions (kept before an update) are of no use to this one.
dir.listFiles()?.filter { it.name != file.name && it.name != part.name }?.forEach { it.delete() }
if (spec.ownFolder) dir.listFiles()?.filter { it.name != file.name && it.name != part.name }?.forEach { it.delete() }
when {
installed() -> _state.value = NetState.Ready
downloadId() != NO_DOWNLOAD -> {

View file

@ -6,13 +6,22 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
/// A game against Maia: her strength, the user's colour and name; `floor`: the half-moves
/// that came from another game ("Play on from here", not taken back); `over`: it ended.
data class PlayMeta(val strength: Int, val userWhite: Boolean, val name: String, val floor: Int, val over: Boolean = false)
/// A game against the computer: the opponent (Maia, or Rodent IV in the character
/// `style`), its strength, the user's colour and name; `floor`: the half-moves that came
/// from another game ("Play on from here", not taken back); `over`: it ended.
data class PlayMeta(
val strength: Int,
val userWhite: Boolean,
val name: String,
val floor: Int,
val over: Boolean = false,
val rival: Opponent = Opponent.Maia,
val style: String = "",
)
/// The game against Maia being played (android-play.md §31.7): its PGN is written after
/// every move, so that "back" puts it aside and it outlives the app being closed. One at
/// a time.
/// The game against the computer being played (android-play.md §31.7, android-rodent.md
/// §6.5): its PGN is written after every move, so that "back" puts it aside and it
/// outlives the app being closed. One at a time. (Named when Maia was the only opponent.)
class MaiaGames(context: Context) {
private val file = File(context.filesDir, "play/current.pgn")
private val prefs = context.getSharedPreferences("play", Context.MODE_PRIVATE)
@ -28,6 +37,9 @@ class MaiaGames(context: Context) {
name = prefs.getString("name", "") ?: "",
floor = prefs.getInt("floor", 0),
over = prefs.getBoolean("over", false),
// A game put aside before Rodent came is a game against Maia.
rival = Opponent.entries.firstOrNull { it.key == prefs.getString("rival", null) } ?: Opponent.Maia,
style = prefs.getString("style", "") ?: "",
)
}
@ -51,6 +63,8 @@ class MaiaGames(context: Context) {
.putString("name", meta.name)
.putInt("floor", meta.floor)
.putBoolean("over", meta.over)
.putString("rival", meta.rival.key)
.putString("style", meta.style)
.apply()
_current.value = meta
}

View file

@ -0,0 +1,168 @@
package io.github.vrubelroman.chesspenguin.data
import android.content.Context
import io.github.vrubelroman.chesspenguin.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
/// Rodent IV on the phone (android-rodent.md): the engine is a "library" of the APK
/// (scripts/rodent4.sh), its personalities come with the APK and are copied into its
/// home folder, its opening books are one pack downloaded on request from the authors'
/// repository ([BookPack]). The engine finds both in its home (RODENT4HOME).
class RodentFiles(private val context: Context, scope: CoroutineScope) {
/// The engine's home: `personalities/` and `books/`.
val home = File(context.filesDir, "rodent4")
/// The executable, unpacked by the installer (useLegacyPackaging).
val executable: String get() = context.applicationInfo.nativeLibraryDir + "/librodent4.so"
val books = BookPack(context, scope, home)
/// Copies the personalities out of the APK when they are not there or are of another
/// version (written beside, then moved in: a cut-off copy is not taken for whole).
/// False when they could not be (no space): Rodent then does not start.
suspend fun prepare(): Boolean = withContext(Dispatchers.IO) {
val version = uniffi.mobile_api.rodentVersion()
val dir = File(home, "personalities")
val mark = File(home, "personalities.version")
if (dir.isDirectory && runCatching { mark.readText() }.getOrNull() == version) return@withContext true
val fresh = File(home, "personalities.new")
try {
fresh.deleteRecursively()
fresh.mkdirs()
val assets = context.assets
for (name in assets.list(ASSETS).orEmpty()) {
assets.open("$ASSETS/$name").use { input -> File(fresh, name).outputStream().use { input.copyTo(it) } }
}
dir.deleteRecursively()
if (!fresh.renameTo(dir)) throw IOException("cannot move the personalities into place")
mark.writeText(version)
true
} catch (e: IOException) {
fresh.deleteRecursively()
false
}
}
private companion object {
const val ASSETS = "rodent4/personalities"
}
}
/// Rodent IV's opening books as one pack (android-rodent.md §5): the books its characters
/// open, each a [CheckedDownload] of the system's, fetched one after another and each
/// checked by its SHA-256. A file checked stays: after a cancel or a break only the rest
/// is fetched. The pack is ready only when every file is there.
class BookPack(context: Context, private val scope: CoroutineScope, home: File) {
private val files: List<CheckedDownload> = uniffi.mobile_api.rodentBookPack().map { b ->
val local = File(home, b.local)
CheckedDownload(
context,
scope,
FileSpec(
dir = local.parentFile!!.relativeTo(context.filesDir).path,
name = local.name,
url = b.url,
size = b.size.toLong(),
sha256 = b.sha256,
title = context.getString(R.string.books_notification),
prefs = "rodent4-book-" + local.name,
ownFolder = false,
),
)
}
/// The pack in all (bytes).
val size: Long = files.sumOf { it.size }
private val _state = MutableStateFlow<NetState>(if (installed()) NetState.Ready else NetState.Missing)
/// Missing (some or all of it), Loading (of what was left when it began), Failed, Ready.
val state: StateFlow<NetState> = _state.asStateFlow()
private var job: Job? = null
private val books = File(home, "books")
init {
sweep()
// A download of the system's still going on from before: the pack goes on.
if (files.any { it.state.value is NetState.Loading }) download()
}
fun installed() = files.all { it.installed() }
/// Files of another version of the pack (or left half-written) go, and folders left
/// empty.
private fun sweep() {
val known = files.flatMap { listOf(it.file.path, it.file.path + ".part") }.toSet()
books.walkBottomUp().forEach { f ->
if (f.isFile && f.path !in known) f.delete()
if (f.isDirectory && f != books && f.list().isNullOrEmpty()) f.delete()
}
}
/// What is left to download (bytes).
fun remaining(): Long = files.filterNot { it.installed() }.sumOf { it.size }
/// Fetches the files not there yet, one after another; stops at the first failure.
fun download() {
if (_state.value == NetState.Ready || _state.value is NetState.Loading) return
val left = files.filterNot { it.installed() }
val total = left.sumOf { it.size }
_state.value = NetState.Loading(0, total)
job = scope.launch(Dispatchers.Main.immediate) {
var done = 0L
for (f in left) {
f.download()
// Its progress as part of the whole, until it is in place or fails.
val end = f.state.first { s ->
if (s is NetState.Loading) _state.value = NetState.Loading(done + s.done, total)
s !is NetState.Loading
}
when (end) {
NetState.Ready -> done += f.size
is NetState.Failed -> {
_state.value = end
return@launch
}
// Removed in the system's list of downloads.
else -> {
_state.value = NetState.Missing
return@launch
}
}
}
_state.value = if (installed()) NetState.Ready else NetState.Missing
}
}
/// The failure of an earlier attempt is forgotten (the network may be back): the pack
/// is offered again as it is.
fun forgetFailure() {
if (_state.value is NetState.Failed) _state.value = if (installed()) NetState.Ready else NetState.Missing
}
/// Stops the download; the files checked so far stay.
fun cancel() {
job?.cancel()
job = null
files.forEach { if (it.state.value is NetState.Loading) it.cancel() }
_state.value = if (installed()) NetState.Ready else NetState.Missing
}
/// Removes the books (Settings → Engine).
fun delete() {
cancel()
files.forEach { it.delete() }
sweep()
_state.value = NetState.Missing
}
}

View file

@ -7,6 +7,9 @@ import kotlinx.coroutines.flow.asStateFlow
enum class Theme { System, Light, Dark }
/// Who plays against the user (android-rodent.md): kept by these names.
enum class Opponent(val key: String) { Maia("maia"), Rodent("rodent4") }
/// How moves are written on the screen (PGN keeps K Q R B N).
enum class Notation { Latin, Figurines, Local }
@ -29,14 +32,19 @@ data class Prefs(
/// The engine's speed per thread measured by the last game analysis (0 = not yet),
/// for the time estimate.
val reviewNps: Long = 0,
/// The last choices of a game against Maia (android-play.md §31.1): her strength,
/// the user's colour (-1 Black, 0 at random, 1 White), the user's name.
/// The last choices of a game against the computer (android-play.md §31.1,
/// android-rodent.md §7.1): the opponent, each one's strength on its own scale,
/// Rodent's character ("" = never chosen), the user's colour (-1 Black, 0 at
/// random, 1 White), the user's name.
val opponent: Opponent = Opponent.Maia,
val maiaStrength: Int = 1500,
val maiaColor: Int = 0,
val rodentStrength: Int = 1500,
val rodentPersonality: String = "",
val playColor: Int = 0,
val yourName: String = "",
/// Sounds of moves and of the end of a game (§33).
val sound: Boolean = true,
/// Games against Maia go by themselves into the player's database (player-games.md).
/// Games against the computer go by themselves into the player's database (player-games.md).
val recordGames: Boolean = true,
)
@ -74,8 +82,12 @@ class Settings(context: Context) {
engineHashMb = store.getInt("engineHashMb", d.engineHashMb),
reviewQuality = store.getInt("reviewQuality", d.reviewQuality).coerceIn(0, REVIEW_NODES.size - 1),
reviewNps = store.getLong("reviewNps", d.reviewNps),
opponent = Opponent.entries.firstOrNull { it.key == store.getString("opponent", null) } ?: d.opponent,
maiaStrength = store.getInt("maiaStrength", d.maiaStrength),
maiaColor = store.getInt("maiaColor", d.maiaColor).coerceIn(-1, 1),
rodentStrength = store.getInt("rodentStrength", d.rodentStrength),
rodentPersonality = store.getString("rodentPersonality", d.rodentPersonality) ?: d.rodentPersonality,
// Kept as `maiaColor` up to 1.7, when Maia was the only opponent.
playColor = store.getInt("playColor", store.getInt("maiaColor", d.playColor)).coerceIn(-1, 1),
yourName = store.getString("yourName", d.yourName) ?: d.yourName,
sound = store.getBoolean("sound", d.sound),
recordGames = store.getBoolean("recordGames", d.recordGames),
@ -99,8 +111,12 @@ class Settings(context: Context) {
.putInt("engineHashMb", p.engineHashMb)
.putInt("reviewQuality", p.reviewQuality)
.putLong("reviewNps", p.reviewNps)
.putString("opponent", p.opponent.key)
.putInt("maiaStrength", p.maiaStrength)
.putInt("maiaColor", p.maiaColor)
.putInt("rodentStrength", p.rodentStrength)
.putString("rodentPersonality", p.rodentPersonality)
.putInt("playColor", p.playColor)
.remove("maiaColor")
.putString("yourName", p.yourName)
.putBoolean("sound", p.sound)
.putBoolean("recordGames", p.recordGames)

View file

@ -51,6 +51,8 @@ private val NOTICES = listOf(
"Board images" to "AGPLv3+ · the lila authors and pirouetti (Lichess)",
"Sounds (SFX)" to "AGPLv3+ · Enigmahack (via Lichess)",
"Sound of a wrong move" to "CC0-1.0 · Kenney, kenney.nl",
"Rodent IV 0.33" to "GPL-3.0 · Paweł Koziol, Bernhard C. Maerz (based on Sungorus by Pablo Vázquez) · github.com/nescitus/rodent-iv",
"Rodent IV opening books (downloaded from its authors on request)" to "Their authors' credits in the books' folders · github.com/nescitus/rodent-iv",
"Maia-3 (downloaded from its authors on request)" to "CSSLab, University of Toronto · huggingface.co/UofTCSSLab",
"Figurines, Noto Sans Math" to "SIL Open Font License 1.1",
"Jetpack Compose, AndroidX, Kotlin" to "Apache-2.0 · Google, JetBrains",

View file

@ -203,10 +203,10 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
}
val eventText = stringResource(R.string.play_event)
if (playing) {
PlaySheet(null, onPlay = { strength, white, name ->
PlaySheet(null, onPlay = { choice ->
playing = false
val s = uniffi.mobile_api.GameSession.newGame("")
beginMaiaGame(theApp, s, strength, white, name, 0, eventText, null)
beginComputerGame(theApp, s, choice.meta(0), eventText, null)
s.close()
onPlay()
}, onDismiss = { playing = false })
@ -273,15 +273,18 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
) {
// A newer version of the app (android-ui.md §25.2): the first item of the list.
update?.let { u -> item(key = "update") { UpdateCard(u, onDismissed = onUpdateDismissed, modifier = Modifier.animateItem()) } }
// A game against Maia put aside (§31.7): go on with it, or let it go.
// A game against the computer put aside (§31.7): go on with it, or let it go.
adjourned?.takeIf { !it.over }?.let { m ->
item(key = "adjourned") {
// The game's position on a small board, the side and the move, and
// «Continue» as the screen's main action while it waits (android-lists.md §5.4).
val shownAt = remember(m) { adjournedPosition(theApp.maiaGames.pgn()) }
val sideText = stringResource(if (m.userWhite) R.string.play_as_white else R.string.play_as_black)
val sub = shownAt?.second?.let { sideText + " · " + stringResource(R.string.play_move_n, it) } ?: sideText
val title = stringResource(R.string.play_adjourned_title, m.strength.toString())
// «you play Black · move 2», Rodent's character first, as the game's header
// says it (android-rodent.md §6.5): «Tal · you play Black · move 2».
val played = shownAt?.second?.let { stringResource(R.string.play_adjourned_sub, sideText, stringResource(R.string.play_move_n, it)) } ?: sideText
val sub = listOfNotNull(m.styleShown(), played).joinToString(" · ")
val title = stringResource(R.string.play_adjourned_title, m.label())
Row(
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp)
.clip(RoundedCornerShape(16.dp))
@ -336,10 +339,17 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
contentColor = MaterialTheme.colorScheme.onSurface,
)
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
FilledTonalButton(onClick = { if (adjourned?.over == false) askingAdjourned = true else playing = true }, modifier = Modifier.weight(1f).heightIn(min = 56.dp), shape = RoundedCornerShape(16.dp), colors = quiet) {
// «Play»: the opponent is chosen on the sheet (android-rodent.md, question 6).
val playLabel = stringResource(R.string.play_button_cd)
FilledTonalButton(
onClick = { if (adjourned?.over == false) askingAdjourned = true else playing = true },
modifier = Modifier.weight(1f).heightIn(min = 56.dp).semantics { contentDescription = playLabel },
shape = RoundedCornerShape(16.dp),
colors = quiet,
) {
Icon(Icons.Rounded.SmartToy, null, tint = MaterialTheme.colorScheme.primary)
Spacer(Modifier.size(8.dp))
Text(stringResource(R.string.play_with_maia))
Text(stringResource(R.string.play_button))
}
FilledTonalButton(onClick = onNewGame, modifier = Modifier.weight(1f).heightIn(min = 56.dp), shape = RoundedCornerShape(16.dp), colors = quiet) {
Icon(Icons.Rounded.Add, null, tint = MaterialTheme.colorScheme.primary)

View file

@ -113,6 +113,7 @@ import io.github.vrubelroman.chesspenguin.data.Written
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.EngineSession
import io.github.vrubelroman.chesspenguin.data.NetState
import io.github.vrubelroman.chesspenguin.data.Opponent
import io.github.vrubelroman.chesspenguin.data.REVIEW_NODES
import io.github.vrubelroman.chesspenguin.data.ReviewSession
import io.github.vrubelroman.chesspenguin.data.enginePosition
@ -451,7 +452,7 @@ fun GameScreen(
edit?.undo()?.let { apply(it) }
}
// ----- a game against Maia (§31) -----
// ----- a game against the computer (§31, android-rodent.md) -----
val runOver = run?.over?.value
val runOffer = run?.offer?.value == true
val runThinking = run?.thinking?.value == true
@ -465,6 +466,7 @@ fun GameScreen(
val r = run ?: return
val e = edit ?: return
r.generation++
r.rodent?.forget()
r.thinking.value = false
r.offer.value = false
e.setData(listOf(uniffi.mobile_api.Tag("Termination", "Normal")), over.result)
@ -505,7 +507,8 @@ fun GameScreen(
persist()
edit?.ending(e.cursor)?.let { finishGame(overBy(it, r.meta.userWhite)) }
}
// Maia's move when it is her turn: computed in the background, shown after her pause.
// The opponent's move when it is its turn: computed in the background, shown after its
// pause. Maia computes at once and waits; Rodent thinks for the pause (android-rodent.md §6.1).
LaunchedEffect(run, g, runOver, runOffer, runFailure) {
val r = run ?: return@LaunchedEffect
val gg = g ?: return@LaunchedEffect
@ -516,22 +519,53 @@ fun GameScreen(
val gen = ++r.generation
r.thinking.value = true
try {
val player = r.player ?: withContext(Dispatchers.IO) { runCatching { uniffi.mobile_api.MaiaPlayer.load(app.maiaFiles.download.file.path) } }
.getOrElse { ex ->
r.failure.value = ex.message ?: ""
return@LaunchedEffect
}.also { r.player = it }
// Her resignation is judged by Stockfish, when it is there.
val started = System.currentTimeMillis()
val only = e.legalMoves(end.toUInt()).size == 1
val pause = uniffi.mobile_api.movePauseMs(depth(gg, end).toUInt(), only)
val rodentFiles = app.rodentFiles
val think: suspend () -> String? = if (r.meta.rival == Opponent.Rodent) {
// Rodent is in the APK: its personalities copied out, its books if the pack is
// whole (a game goes on without them, §1.7).
val rodent = r.rodent ?: (
if (rodentFiles.prepare()) {
uniffi.mobile_api.RodentPlayer.start(rodentFiles.executable, rodentFiles.home.path, r.meta.style, r.meta.strength.toUInt(), rodentFiles.books.installed())
} else {
r.failure.value = PlayFailure("no space for the personalities")
return@LaunchedEffect
}
).also { r.rodent = it }
suspend {
// None: passed over by a newer request (a take-back), or Rodent failed.
withContext(Dispatchers.IO) { rodent.choose(e, end.toUInt(), pause) }.also { m ->
if (m == null) {
rodent.failure()?.let { f ->
r.failure.value = when (f) {
is uniffi.mobile_api.RodentFailure.DidNotStart -> PlayFailure(f.detail)
uniffi.mobile_api.RodentFailure.Stopped -> PlayFailure("", stopped = true)
}
}
}
}
}
} else {
val player = r.player ?: withContext(Dispatchers.IO) { runCatching { uniffi.mobile_api.MaiaPlayer.load(app.maiaFiles.download.file.path) } }
.getOrElse { ex ->
r.failure.value = PlayFailure(ex.message ?: "")
return@LaunchedEffect
}.also { r.player = it }
suspend {
withContext(Dispatchers.Default) {
player.choose(e, end.toUInt(), r.meta.strength.toUInt(), null, kotlin.random.Random.nextFloat())
}
}
}
// Its resignation is judged by Stockfish, when it is there.
if (r.judge == null && files.state.value == NetState.Ready) {
r.judge = runCatching { uniffi.mobile_api.ResignJudge.start(files.executable, files.net.path) }.getOrNull()
}
r.judge?.ask(e, end.toUInt())
val started = System.currentTimeMillis()
val only = e.legalMoves(end.toUInt()).size == 1
val uci = withContext(Dispatchers.Default) {
player.choose(e, end.toUInt(), r.meta.strength.toUInt(), null, kotlin.random.Random.nextFloat())
} ?: return@LaunchedEffect
val wait = uniffi.mobile_api.maiaPauseMs(depth(gg, end).toUInt(), only).toLong() - (System.currentTimeMillis() - started)
val uci = think() ?: return@LaunchedEffect
val wait = pause.toLong() - (System.currentTimeMillis() - started)
if (wait > 0) delay(wait)
if (gen != r.generation) return@LaunchedEffect
// The judge's answer, given up to two seconds more (a slow phone, an engine
@ -562,10 +596,10 @@ fun GameScreen(
}
}
var resigning by remember { mutableStateOf(false) }
val drawDeclined = stringResource(R.string.play_draw_declined)
val drawLater = stringResource(R.string.play_draw_later)
val drawNoEngine = stringResource(R.string.play_draw_no_engine)
// A draw offered (§31.3): Maia answers by her judge's scores of her last turns.
val drawDeclined = stringResource(run?.meta?.said(R.string.play_draw_declined, R.string.rodent_draw_declined) ?: R.string.play_draw_declined)
val drawLater = stringResource(run?.meta?.said(R.string.play_draw_later, R.string.rodent_draw_later) ?: R.string.play_draw_later)
val drawNoEngine = stringResource(run?.meta?.said(R.string.play_draw_no_engine, R.string.rodent_draw_no_engine) ?: R.string.play_draw_no_engine)
// A draw offered (§31.3): the opponent answers by its judge's scores of its last turns.
fun offerDraw() {
val r = run ?: return
val j = r.judge
@ -584,6 +618,7 @@ fun GameScreen(
LaunchedEffect(g) {
if (runOver != null && atEnd != null && g != null && lineEnd(g) != atEnd) resultClosed = true
}
// Maia's file fetched again after she failed: she starts anew once it is there.
var maiaRetry by remember { mutableStateOf(false) }
val maiaState by app.maiaFiles.download.state.collectAsState()
LaunchedEffect(maiaState, maiaRetry) {
@ -595,13 +630,21 @@ fun GameScreen(
}
}
val eventText = stringResource(R.string.play_event)
val noteText = stringResource(R.string.play_note_from, (run?.meta?.strength ?: 0).toString())
// The same strength again, colours swapped; from a position: the same one and colour.
val runStyle = run?.meta?.styleShown()
// A new game asked for when a rematch cannot start at once (Rodent's books removed
// meanwhile, android-rodent.md §1.6): the sheet, as for a new game.
var newGameSheet by remember { mutableStateOf(false) }
// The same opponent and strength again, colours swapped; from a position: the same one
// and colour.
fun rematch() {
val r = run ?: return
val e = edit ?: return
val gg = g ?: return
val m = r.meta
if (m.rival == Opponent.Rodent && m.floor == 0 && !app.rodentFiles.books.installed()) {
newGameSheet = true
return
}
val base = if (m.floor > 0) {
var n = 0
repeat(m.floor) { n = gg.nodes[n].children.firstOrNull()?.toInt() ?: n }
@ -609,7 +652,8 @@ fun GameScreen(
} else {
GameSession.newGame("")
}
beginMaiaGame(app, base, m.strength, if (m.floor > 0) m.userWhite else !m.userWhite, m.name, m.floor, eventText, noteText)
val next = m.copy(userWhite = if (m.floor > 0) m.userWhite else !m.userWhite, over = false)
beginComputerGame(app, base, next, eventText, playNote(resources, next, runStyle))
base.close()
// The report of the game before is not this one's.
review.close()
@ -622,12 +666,13 @@ fun GameScreen(
val gg = g ?: return
val e = edit ?: return
val end = lineEnd(gg)
// While Maia thinks or offers to resign, the last move is the user's; else hers, and
// the user's before.
// While the opponent thinks or offers to resign, the last move is the user's; else
// its, and the user's before.
val userLast = r.thinking.value || r.offer.value
val from = if (userLast) end else gg.nodes[end].parent?.toInt() ?: return
if (depth(gg, from) <= r.meta.floor) return
r.generation++
r.rodent?.forget()
r.thinking.value = false
r.offer.value = false
r.judge?.forget()
@ -952,18 +997,28 @@ fun GameScreen(
if (run != null) {
when {
runOffer -> OfferCard(
onAccept = { finishGame(PlayOver(if (run.meta.userWhite) "1-0" else "0-1", R.string.play_won, R.string.end_maia_resigned)) },
run.meta,
onAccept = { finishGame(PlayOver(if (run.meta.userWhite) "1-0" else "0-1", R.string.play_won, run.meta.said(R.string.end_maia_resigned, R.string.end_rodent_resigned))) },
onPlayOn = {
run.playOn = true
run.offer.value = false
},
)
runFailure != null -> FailureCard(
run.meta,
runFailure,
onRetry = {
// A missing or damaged file is fetched again, then she starts.
app.maiaFiles.download.delete()
app.maiaFiles.download.download()
maiaRetry = true
if (run.meta.rival == Opponent.Rodent) {
// Rodent is in the APK: it is started again.
run.rodent?.close()
run.rodent = null
run.failure.value = null
} else {
// A missing or damaged file is fetched again, then she starts.
app.maiaFiles.download.delete()
app.maiaFiles.download.download()
maiaRetry = true
}
},
onAbort = {
app.playerGames.keepUnfinished(app.maiaGames, prefs.recordGames, app.scope)
@ -1035,8 +1090,9 @@ fun GameScreen(
// The event and year (else the site); the game's place and round. A tap
// shows the game's details.
// No event and no site: the database's name.
// «Game against Rodent IV 1800» (android-rodent.md §6.1): a name, not a command.
val event = if (playGame && run != null) {
stringResource(R.string.play_with_maia) + " " + run.meta.strength
stringResource(R.string.play_adjourned_title, run.meta.label())
} else if (newGame && held.savedTo == null) {
stringResource(R.string.new_game)
} else {
@ -1048,7 +1104,10 @@ fun GameScreen(
val yearInLine = if (joinKnown(tag("Event")).isEmpty()) year(tag("Date")) else ""
val round = tag("Round").trim().takeIf { it.isNotEmpty() && it != "?" && it != "-" }
val placeLine = if (playGame && run != null) {
stringResource(R.string.play_adjourned_sub, stringResource(if (run.meta.userWhite) R.string.play_as_white else R.string.play_as_black), stringResource(R.string.play_untimed))
listOfNotNull(
runStyle,
stringResource(R.string.play_adjourned_sub, stringResource(if (run.meta.userWhite) R.string.play_as_white else R.string.play_as_black), stringResource(R.string.play_untimed)),
).joinToString(" · ")
} else joinKnown(
if (total > 0 && held.savedTo == null) stringResource(R.string.game_of, place + 1, total) else "",
yearInLine,
@ -1175,19 +1234,26 @@ fun GameScreen(
// a title for White and no Black keeps both bars, so the board does not jump.
val study = whiteName != null && blackName == null
val result = g?.result ?: ""
// In a game: «thinking…» on Maia's bar while she computes (§31.3).
// In a game: «thinking…» on the opponent's bar while it computes (§31.3).
val thinkingText = stringResource(R.string.play_thinking)
val maiaThinks = { white: Boolean -> if (gameOn && runThinking && run?.meta?.userWhite != white) thinkingText else null }
// In a game against Maia: the user without a name is «You»; Maia's rating is in her name.
// In a game against the computer: the user without a name is «You»; the opponent is
// named with its strength and Rodent's character («Rodent IV 1800 · Tal»: the end
// goes first when it does not fit, never the strength, android-rodent.md §6.1).
val youText = stringResource(R.string.play_you)
val rivalText = run?.meta?.let { m -> listOfNotNull(m.label(), runStyle).joinToString(" · ") }
val playName = { white: Boolean ->
if (playGame && run?.meta?.userWhite == white && (if (white) whiteName else blackName) == null) youText else null
when {
!playGame || run == null -> null
run.meta.userWhite == white -> if ((if (white) whiteName else blackName) == null) youText else null
else -> rivalText
}
}
val whiteBar: @Composable () -> Unit = {
PlayerBar(playName(true) ?: whiteName ?: whiteLabel, if (playGame) "" else elo(tag("WhiteElo")), true, sideResult(result, true), known = whiteName != null || playGame, abbreviate = !study, status = maiaThinks(true))
PlayerBar(playName(true) ?: whiteName ?: whiteLabel, if (playGame) "" else elo(tag("WhiteElo")), true, sideResult(result, true), known = whiteName != null || playGame, abbreviate = !study && !playGame, status = maiaThinks(true))
}
val blackBar: @Composable () -> Unit = {
PlayerBar(playName(false) ?: blackName ?: blackLabel, if (playGame) "" else elo(tag("BlackElo")), false, sideResult(result, false), known = blackName != null || playGame, status = maiaThinks(false))
PlayerBar(playName(false) ?: blackName ?: blackLabel, if (playGame) "" else elo(tag("BlackElo")), false, sideResult(result, false), known = blackName != null || playGame, abbreviate = !playGame, status = maiaThinks(false))
}
val topBar = if (flipped) whiteBar else blackBar
val bottomBar = if (flipped) blackBar else whiteBar
@ -1321,12 +1387,14 @@ fun GameScreen(
} else {
val moveLabel = (if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san).text
val origin = listOfNotNull(whiteName, blackName).joinToString(" — ").takeIf { it.isNotEmpty() }
val styles = RODENT_TEXTS.mapValues { stringResource(it.value.first) }
PlaySheet(
PlayFrom(n.fen, listOfNotNull(stringResource(R.string.play_from_label, moveLabel), origin).joinToString("\n"), whiteToMove(n.fen)),
onPlay = { strength, white, name ->
onPlay = { choice ->
playFrom = null
val s = runCatching { edit?.playFrom(fromMove.toUInt()) }.getOrNull() ?: return@PlaySheet
beginMaiaGame(app, s, strength, white, name, depth(g, fromMove), eventText, resources.getString(R.string.play_note_from, strength.toString()))
val meta = choice.meta(depth(g, fromMove))
beginComputerGame(app, s, meta, eventText, playNote(resources, meta, styles[meta.style]))
s.close()
// On the play screen itself the game in hand is read anew.
held.key = null
@ -1336,6 +1404,19 @@ fun GameScreen(
)
}
}
if (newGameSheet) {
PlaySheet(null, onPlay = { choice ->
newGameSheet = false
val s = GameSession.newGame("")
beginComputerGame(app, s, choice.meta(0), eventText, null)
s.close()
// The report of the game before is not this one's.
review.close()
reviewHidden = true
held.key = null
held.reloads.intValue++
}, onDismiss = { newGameSheet = false })
}
val askAt = askFrom
val adjournedMeta = app.maiaGames.current.collectAsState().value
if (askAt != null && adjournedMeta != null) {
@ -1687,7 +1768,7 @@ private fun MoveSheet(
if (inVariation) SheetAction(Icons.Rounded.VerticalAlignTop, stringResource(R.string.make_main), onClick = onMakeMain)
SheetAction(Icons.Rounded.Close, stringResource(R.string.delete_move), onClick = onDelete)
HorizontalDivider(Modifier.padding(vertical = 4.dp), color = MaterialTheme.colorScheme.outlineVariant)
SheetAction(Icons.Rounded.SmartToy, stringResource(R.string.play_from_maia), enabled = canPlay, onClick = onPlay)
SheetAction(Icons.Rounded.SmartToy, stringResource(R.string.play_from_here), enabled = canPlay, onClick = onPlay)
SheetAction(
Icons.Rounded.School,
stringResource(R.string.train_learn),

View file

@ -40,38 +40,72 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.Opponent
import io.github.vrubelroman.chesspenguin.data.PlayMeta
import uniffi.mobile_api.GameData
import uniffi.mobile_api.GameEnding
import uniffi.mobile_api.MaiaPlayer
import uniffi.mobile_api.ResignJudge
import uniffi.mobile_api.Rival
import uniffi.mobile_api.RodentPlayer
/// The key of the game against Maia in hand (a game screen without a database).
/// The key of the game against the computer in hand (a game screen without a database).
const val PLAY_GAME = "play"
/// How a game against Maia ended: the result and what the strip says.
/// How a game against the computer ended: the result and what the strip says.
data class PlayOver(val result: String, val heading: Int, val detail: Int?)
/// A game against Maia being played (android-play.md §31), kept while the phone turns.
/// The opponent of a game for the core.
fun PlayMeta.rivalOf(): Rival = when (rival) {
Opponent.Maia -> Rival.Maia
Opponent.Rodent -> Rival.Rodent(style)
}
/// «Maia 1500», «Rodent IV 1800» (android-rodent.md §6.1): the title, the card, the question.
fun PlayMeta.label(): String = uniffi.mobile_api.rivalLabel(rivalOf(), strength.toUInt())
/// A character's name in the app's language (the English one, should the app not know it).
@Composable
fun styleTitle(id: String): String =
RODENT_TEXTS[id]?.let { stringResource(it.first) }
?: uniffi.mobile_api.rodentStyles().firstOrNull { it.id == id }?.title ?: id
/// Rodent's character after its name (none for Maia): «Таль».
@Composable
fun PlayMeta.styleShown(): String? = if (rival == Opponent.Rodent) styleTitle(style) else null
/// A text of either opponent: Maia's, or Rodent's (their own sentences: in Russian and
/// other languages the words agree with her or him, rodent-opponent.md §7).
fun PlayMeta.said(maia: Int, rodent: Int): Int = if (rival == Opponent.Rodent) rodent else maia
/// Why the opponent does not play: it did not start (`detail`: the words of the error),
/// or it stopped during the game (Rodent's process gone, android-rodent.md §6.6).
data class PlayFailure(val detail: String, val stopped: Boolean = false)
/// A game against the computer being played (android-play.md §31), kept while the phone
/// turns: Maia (her network) or Rodent IV (its process).
class PlayRun(val meta: PlayMeta) {
var player: MaiaPlayer? = null
var rodent: RodentPlayer? = null
var judge: ResignJudge? = null
val thinking = mutableStateOf(false)
/// Maia offers to resign (her position hopeless two turns in a row).
/// The opponent offers to resign (its position hopeless two turns in a row).
val offer = mutableStateOf(false)
val over = mutableStateOf<PlayOver?>(null)
/// Maia failed to start: why.
val failure = mutableStateOf<String?>(null)
/// The opponent does not play: why.
val failure = mutableStateOf<PlayFailure?>(null)
/// «Play to the end»: no more offers in this game.
var playOn = false
var hopeless = 0u
/// Bumped by a take-back: Maia's answer for the old position is dropped.
/// Bumped by a take-back: the answer for the old position is dropped.
var generation = 0
fun close() {
player?.close()
rodent?.close()
judge?.close()
player = null
rodent = null
judge = null
}
}
@ -156,12 +190,12 @@ private fun LabeledButton(icon: androidx.compose.ui.graphics.vector.ImageVector,
}
}
/// Maia offers to resign (§31.3): accept the win, or play on.
/// The opponent offers to resign (§31.3): accept the win, or play on.
@Composable
fun OfferCard(onAccept: () -> Unit, onPlayOn: () -> Unit) {
fun OfferCard(meta: PlayMeta, onAccept: () -> Unit, onPlayOn: () -> Unit) {
Card {
Text(stringResource(R.string.play_maia_resigns), style = MaterialTheme.typography.titleMedium)
Text(stringResource(R.string.play_her_position_lost), style = MaterialTheme.typography.bodyMedium)
Text(stringResource(meta.said(R.string.play_maia_resigns, R.string.rodent_resigns)), style = MaterialTheme.typography.titleMedium)
Text(stringResource(meta.said(R.string.play_her_position_lost, R.string.rodent_position_lost)), style = MaterialTheme.typography.bodyMedium)
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = onAccept, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_accept_win)) }
OutlinedButton(onClick = onPlayOn, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_on_short)) }
@ -234,40 +268,56 @@ private fun Card(content: @Composable () -> Unit) {
) { content() }
}
/// Puts a new game against Maia in hand (android-play.md §31): `session` holds its moves
/// so far (none, or those of the game it goes on from: `floor` half-moves); its tags
/// are set, and after the moves of another game a note says where it comes from.
fun beginMaiaGame(
/// Puts a new game against the computer in hand (android-play.md §31): `session` holds
/// its moves so far (none, or those of the game it goes on from: `meta.floor`
/// half-moves); its tags are set, and after the moves of another game a note says where
/// it comes from.
fun beginComputerGame(
app: io.github.vrubelroman.chesspenguin.ChessPenguinApp,
session: uniffi.mobile_api.GameSession,
strength: Int,
userWhite: Boolean,
name: String,
floor: Int,
meta: PlayMeta,
event: String,
note: String?,
) {
val date = java.text.SimpleDateFormat("yyyy.MM.dd", java.util.Locale.ROOT).format(java.util.Date())
val tags = uniffi.mobile_api.maiaGameTags(event, userWhite, name, strength.toUInt()) + uniffi.mobile_api.Tag("Date", date)
val tags = uniffi.mobile_api.computerGameTags(event, meta.userWhite, meta.name, meta.rivalOf(), meta.strength.toUInt()) +
uniffi.mobile_api.Tag("Date", date)
session.setData(tags, "*")
if (floor > 0 && note != null) {
if (meta.floor > 0 && note != null) {
val data = session.data()
runCatching { session.addComment(lineEnd(data).toUInt(), note) }
}
session.markSaved()
// The game it replaces, if left unfinished, is kept in its player's database.
app.playerGames.keepUnfinished(app.maiaGames, app.settings.prefs.value.recordGames, app.scope)
app.playerGames.remember(name)
app.maiaGames.begin(session.pgn(), PlayMeta(strength, userWhite, name, floor))
app.playerGames.remember(meta.name)
app.maiaGames.begin(session.pgn(), meta)
}
/// Maia did not start (§31.3): her file again, or leave the game.
/// The note in a game played on from another one: «From here on, a game against Maia
/// 1500.», «… Rodent IV 1800 · Tal.» (in the app's language).
fun playNote(resources: android.content.res.Resources, meta: PlayMeta, style: String?): String =
if (meta.rival == Opponent.Rodent && style != null) {
resources.getString(R.string.play_note_from_rodent, meta.strength.toString(), style)
} else {
resources.getString(R.string.play_note_from, meta.strength.toString())
}
/// The opponent did not start (§31.3, android-rodent.md §6.6): Maia's file again, or
/// Rodent started again (it is in the APK: nothing to download); or leave the game.
@Composable
fun FailureCard(onRetry: () -> Unit, onAbort: () -> Unit) {
fun FailureCard(meta: PlayMeta, failure: PlayFailure, onRetry: () -> Unit, onAbort: () -> Unit) {
val text = when {
meta.rival != Opponent.Rodent -> R.string.play_maia_stopped
failure.stopped -> R.string.rodent_stopped_playing
else -> R.string.rodent_stopped
}
Card {
Text(stringResource(R.string.play_maia_stopped), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.error)
Text(stringResource(text), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.error)
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = onRetry, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_maia_reload), maxLines = 1, overflow = TextOverflow.Ellipsis) }
Button(onClick = onRetry, modifier = Modifier.weight(1f)) {
Text(stringResource(meta.said(R.string.play_maia_reload, R.string.rodent_restart)), maxLines = 1, overflow = TextOverflow.Ellipsis)
}
OutlinedButton(onClick = onAbort, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_abort), maxLines = 1) }
}
}
@ -282,7 +332,7 @@ fun AdjournedQuestion(meta: PlayMeta, onContinue: () -> Unit, onNew: () -> Unit,
val kept = remember { app.playerGames.wouldKeep(app.maiaGames, app.settings.prefs.value.recordGames) }
androidx.compose.material3.AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.play_adjourned_q, meta.strength.toString())) },
title = { Text(stringResource(R.string.play_adjourned_q, meta.label())) },
text = { Text(stringResource(if (kept) R.string.play_adjourned_new_text else R.string.play_adjourned_replaced)) },
confirmButton = { androidx.compose.material3.TextButton(onClick = onContinue) { Text(stringResource(R.string.play_continue_it)) } },
dismissButton = { androidx.compose.material3.TextButton(onClick = onNew) { Text(stringResource(R.string.play_start_new)) } },

View file

@ -1,35 +1,66 @@
package io.github.vrubelroman.chesspenguin.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Person
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.ScaffoldDefaults
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.ui.draw.clip
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@ -42,40 +73,90 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.NetProblem
import io.github.vrubelroman.chesspenguin.data.NetState
import io.github.vrubelroman.chesspenguin.data.Opponent
import io.github.vrubelroman.chesspenguin.data.PlayMeta
import io.github.vrubelroman.chesspenguin.theme.Tabular
import uniffi.mobile_api.RodentStyle
import uniffi.mobile_api.maiaRange
import uniffi.mobile_api.rodentRange
import uniffi.mobile_api.rodentStyles
/// The position a game against Maia starts from (android-play.md §31.6): drawn small,
/// with where it comes from; the side to move plays by default.
/// The position a game against the computer starts from (android-play.md §31.6): drawn
/// small, with where it comes from; the side to move plays by default.
data class PlayFrom(val fen: String, val label: String, val whiteToMove: Boolean)
/// «Play against the computer» (android-play.md §31.1): Maia's strength, the colour,
/// the name; Maia downloaded here the first time (21 MB). `onPlay`: strength, the user
/// plays White, name.
/// What the sheet starts: the opponent (Rodent in `style`), its strength, the user's
/// colour and name.
data class PlayChoice(val rival: Opponent, val strength: Int, val style: String, val userWhite: Boolean, val name: String) {
/// The game's description; `floor`: the half-moves it goes on from.
fun meta(floor: Int) = PlayMeta(strength, userWhite, name, floor, rival = rival, style = if (rival == Opponent.Rodent) style else "")
}
/// «Play against the computer» (android-play.md §31.1, android-rodent.md §2): the
/// opponent — Maia or Rodent IV with its character — its strength on its own scale, the
/// colour, the name. What the opponent needs is downloaded here the first time (Maia's
/// file; Rodent's opening books, or «Without book»). The state line and the button stay
/// at the bottom; the rest scrolls.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlaySheet(from: PlayFrom?, onPlay: (Int, Boolean, String) -> Unit, onDismiss: () -> Unit) {
fun PlaySheet(from: PlayFrom?, onPlay: (PlayChoice) -> Unit, onDismiss: () -> Unit) {
val app = app()
val prefs by app.settings.prefs.collectAsState()
val files = app.maiaFiles.download
val state by files.state.collectAsState()
val range = remember { maiaRange() }
val lo = range[0].toInt()
val hi = range[1].toInt()
var strength by remember { mutableFloatStateOf(prefs.maiaStrength.coerceIn(lo, hi).toFloat()) }
val maiaFiles = app.maiaFiles.download
val maiaState by maiaFiles.state.collectAsState()
val books = app.rodentFiles.books
val booksState by books.state.collectAsState()
val styles = remember { rodentStyles() }
var rival by remember { mutableStateOf(prefs.opponent) }
val rodent = rival == Opponent.Rodent
// Each opponent's strength on its own scale, remembered apart (§4).
val maiaRange = remember { maiaRange().map { it.toInt() } }
val rodentRange = remember { rodentRange().map { it.toInt() } }
var maiaLevel by remember { mutableFloatStateOf(prefs.maiaStrength.coerceIn(maiaRange[0], maiaRange[1]).toFloat()) }
var rodentLevel by remember { mutableFloatStateOf(prefs.rodentStrength.coerceIn(rodentRange[0], rodentRange[1]).toFloat()) }
// The character: kept at once when chosen (§7.1); an unknown one is Tal.
val style = prefs.rodentPersonality.takeIf { id -> styles.any { it.id == id } } ?: DEFAULT_RODENT_STYLE
var picking by remember { mutableStateOf(false) }
// From a position: the side to move by default, not remembered (play-from-position.md §2).
var color by remember { mutableIntStateOf(if (from != null) (if (from.whiteToMove) 1 else -1) else prefs.maiaColor) }
var color by remember { mutableIntStateOf(if (from != null) (if (from.whiteToMove) 1 else -1) else prefs.playColor) }
var name by remember { mutableStateOf(prefs.yourName) }
// «Download and play»: the game starts once the file is checked.
// «Download and play»: the game starts once the files are checked, if this opponent
// is still the one chosen.
var playAfter by remember { mutableStateOf(false) }
val range = if (rodent) rodentRange else maiaRange
val strength = if (rodent) rodentLevel else maiaLevel
val level = (strength / 50f).toInt() * 50
// From a position Rodent needs no book (§1.5); Maia always needs her file.
val state = if (rodent) booksState else maiaState
// From a position Rodent plays at once, whatever its books (§1.5, question 4).
val noBookNeeded = rodent && from != null
val ready = state == NetState.Ready || noBookNeeded
fun play() {
val white = when (color) {
1 -> true
@ -83,152 +164,432 @@ fun PlaySheet(from: PlayFrom?, onPlay: (Int, Boolean, String) -> Unit, onDismiss
else -> kotlin.random.Random.nextBoolean()
}
app.settings.update { p ->
p.copy(maiaStrength = level, yourName = name.trim(), maiaColor = if (from != null) p.maiaColor else color)
val q = p.copy(opponent = rival, yourName = name.trim(), playColor = if (from != null) p.playColor else color)
if (rodent) q.copy(rodentStrength = level) else q.copy(maiaStrength = level)
}
onPlay(level, white, name.trim())
onPlay(PlayChoice(rival, level, style, white, name.trim()))
}
LaunchedEffect(state) {
// A failure of an earlier attempt is not this sheet's: the download is offered anew.
LaunchedEffect(Unit) { books.forgetFailure() }
LaunchedEffect(state, rival) {
if (playAfter && state == NetState.Ready) {
playAfter = false
play()
}
}
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(start = 24.dp, end = 24.dp, bottom = 24.dp)) {
Text(stringResource(R.string.play_title), style = MaterialTheme.typography.titleLarge)
if (from != null) {
Row(Modifier.padding(top = 12.dp), verticalAlignment = Alignment.CenterVertically) {
MiniBoard(from.fen, flipped = color == -1, size = 96.dp)
Text(from.label, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 4, overflow = TextOverflow.Ellipsis)
}
}
Spacer(Modifier.height(16.dp))
Text(stringResource(R.string.play_opponent, level.toString()), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)
Row(verticalAlignment = Alignment.CenterVertically) {
Text("$lo", style = MaterialTheme.typography.bodySmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
Slider(
value = strength,
onValueChange = { strength = it },
valueRange = lo.toFloat()..hi.toFloat(),
modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
)
Text("$hi", style = MaterialTheme.typography.bodySmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text(stringResource(R.string.play_measured), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(16.dp))
Text(stringResource(R.string.play_colour), style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(8.dp))
val options = listOf(1 to R.string.color_white, 0 to R.string.color_random, -1 to R.string.color_black)
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {
options.forEachIndexed { i, (v, label) ->
SegmentedButton(selected = color == v, onClick = { color = v }, shape = SegmentedButtonDefaults.itemShape(i, options.size)) {
Text(stringResource(label))
val scroll = rememberScrollState()
Column(Modifier.fillMaxWidth()) {
Column(Modifier.weight(1f, fill = false).verticalScroll(scroll).padding(horizontal = 24.dp)) {
Text(stringResource(R.string.play_title), style = MaterialTheme.typography.titleLarge)
if (from != null) {
Row(Modifier.padding(top = 12.dp), verticalAlignment = Alignment.CenterVertically) {
MiniBoard(from.fen, flipped = color == -1, size = 96.dp)
Text(from.label, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 4, overflow = TextOverflow.Ellipsis)
}
}
}
Spacer(Modifier.height(12.dp))
// The name, with the players of this phone to pick from; under it, where the
// games go (player-games.md §6).
val players = remember { app.playerGames.players() }
var picking by remember { mutableStateOf(false) }
val line = if (!prefs.recordGames) {
stringResource(R.string.player_line_off)
} else {
val db = app.playerGames.database(name)
when {
app.playerGames.tidy(name).isEmpty() -> stringResource(R.string.player_line_noname, db?.name ?: app.playerGames.dbName(""))
db != null -> stringResource(R.string.player_line_existing, db.name) + " · " +
androidx.compose.ui.res.pluralStringResource(R.plurals.games_count, db.games ?: 0, groupDigits(db.games ?: 0))
else -> stringResource(R.string.player_line_new, app.playerGames.dbName(name))
Spacer(Modifier.height(16.dp))
// Who first, then how strong: the scale is the opponent's (§2.1).
Row(Modifier.fillMaxWidth().selectableGroup(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OpponentCard("Maia", stringResource(R.string.opp_maia_sub), !rodent, Modifier.weight(1f)) {
if (rodent) playAfter = false
rival = Opponent.Maia
}
OpponentCard("Rodent IV", stringResource(R.string.opp_rodent_sub), rodent, Modifier.weight(1f)) {
if (!rodent) playAfter = false
rival = Opponent.Rodent
// The first time, the list opens by itself with Tal suggested (§3.4).
if (prefs.rodentPersonality.isEmpty()) picking = true
}
}
Spacer(Modifier.height(8.dp))
CharacterRow(if (rodent) styles.firstOrNull { it.id == style } else null) { picking = true }
Spacer(Modifier.height(8.dp))
Text(
stringResource(R.string.strength_n, level.toString()),
style = MaterialTheme.typography.titleMedium.merge(Tabular),
fontWeight = FontWeight.Medium,
)
val strengthLabel = stringResource(R.string.strength)
val strengthState = stringResource(R.string.strength_range, level.toString(), range[0].toString(), range[1].toString())
Row(verticalAlignment = Alignment.CenterVertically) {
Text("${range[0]}", style = MaterialTheme.typography.bodySmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
Slider(
value = strength,
onValueChange = { if (rodent) rodentLevel = it else maiaLevel = it },
valueRange = range[0].toFloat()..range[1].toFloat(),
modifier = Modifier.weight(1f).padding(horizontal = 8.dp).semantics {
contentDescription = strengthLabel
stateDescription = strengthState
},
)
Text("${range[1]}", style = MaterialTheme.typography.bodySmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
// Always two lines: the sheet does not jump when the opponent changes. It
// changes only with the opponent: TalkBack says it then, not at each step of
// the slider.
Text(
stringResource(if (rodent) R.string.rodent_measured else R.string.play_measured),
Modifier.semantics { liveRegion = LiveRegionMode.Polite },
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
minLines = 2,
)
Spacer(Modifier.height(16.dp))
Text(stringResource(R.string.play_colour), style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(8.dp))
val options = listOf(1 to R.string.color_white, 0 to R.string.color_random, -1 to R.string.color_black)
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {
options.forEachIndexed { i, (v, label) ->
SegmentedButton(selected = color == v, onClick = { color = v }, shape = SegmentedButtonDefaults.itemShape(i, options.size)) {
Text(stringResource(label))
}
}
}
Spacer(Modifier.height(12.dp))
NameField(name, prefs.recordGames) { name = it }
Spacer(Modifier.height(12.dp))
}
// The players whose names begin with what is typed (none once it is one of them).
val typed = app.playerGames.tidy(name).lowercase()
val matching = players.filter { it.lowercase().startsWith(typed) && it.lowercase() != typed }
// Opened by typing or by its arrow, not by a tap in the field (it would cover «Play»).
ExposedDropdownMenuBox(expanded = picking && matching.isNotEmpty(), onExpandedChange = { if (!it) picking = false }) {
OutlinedTextField(
name,
{
name = it
picking = it.isNotBlank()
},
Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
label = { Text(stringResource(R.string.play_your_name)) },
supportingText = { Text(line) },
trailingIcon = {
if (matching.isNotEmpty()) {
IconButton(onClick = { picking = !picking }) { ExposedDropdownMenuDefaults.TrailingIcon(expanded = picking) }
// The footer: what the chosen opponent needs, and the button (§2.4). A line
// over it while the content goes on under it.
HorizontalDivider(color = if (scroll.canScrollForward) MaterialTheme.colorScheme.outlineVariant else Color.Transparent)
Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 8.dp, bottom = 24.dp)) {
// At least 40 dp (it grows with a large font). Only the lines that change with
// the kind of state are read out, not every step of the progress.
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) {
val noBookText = stringResource(R.string.books_without_cd)
val noBook = @Composable {
TextButton(onClick = {
playAfter = false
play()
}, modifier = Modifier.heightIn(min = 48.dp).semantics { contentDescription = noBookText }) {
Text(stringResource(R.string.books_without), maxLines = 1)
}
}
// What is left to download (the books checked so far stay).
val booksLeft = remember(booksState) { books.remaining() }
val left = if (rodent) booksLeft else maiaFiles.size
when (val s = state) {
NetState.Ready -> StateText(stringResource(if (rodent) R.string.books_ready else R.string.play_maia_ready))
NetState.Missing -> if (noBookNeeded) {
StateText(stringResource(R.string.books_not_needed))
} else if (rodent) {
StateText(stringResource(R.string.books_offer, megabytes(left)), Modifier.weight(1f))
noBook()
} else {
StateText(stringResource(R.string.play_download_note, megabytes(left)))
}
is NetState.Loading -> {
val what = stringResource(R.string.online_downloading, if (rodent) stringResource(R.string.books_notification) else "Maia")
Column(
Modifier.weight(1f).clearAndSetSemantics {
contentDescription = what
progressBarRangeInfo = ProgressBarRangeInfo(s.done.toFloat() / s.total.coerceAtLeast(1), 0f..1f)
},
) {
LinearProgressIndicator(progress = { s.done.toFloat() / s.total.coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth())
Text(stringResource(R.string.downloaded_of, megabytes(s.done), megabytes(s.total)), style = MaterialTheme.typography.bodySmall.merge(Tabular))
}
IconButton(onClick = {
playAfter = false
if (rodent) books.cancel() else maiaFiles.cancel()
}) { Icon(Icons.Rounded.Close, stringResource(R.string.cancel_download)) }
}
// From a position a failed download does not matter to Rodent.
is NetState.Failed -> if (noBookNeeded) {
StateText(stringResource(R.string.books_not_needed))
} else {
Text(
when (s.problem) {
NetProblem.NoInternet -> stringResource(R.string.no_internet)
NetProblem.Interrupted -> stringResource(R.string.interrupted)
NetProblem.NoSpace -> stringResource(R.string.no_space, megabytes(left))
NetProblem.Corrupt -> stringResource(R.string.corrupt)
},
Modifier.weight(1f).semantics { liveRegion = LiveRegionMode.Polite },
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
// Rodent plays without its books (§5.5); from a position it needs none.
if (rodent) noBook()
}
}
}
Spacer(Modifier.height(8.dp))
val loading = state is NetState.Loading
Button(
onClick = {
if (ready) {
play()
} else {
playAfter = true
if (rodent) books.download() else maiaFiles.download()
}
},
singleLine = true,
)
ExposedDropdownMenu(expanded = picking && matching.isNotEmpty(), onDismissRequest = { picking = false }) {
matching.forEach { p ->
DropdownMenuItem(text = { Text(p) }, onClick = {
name = p
picking = false
})
}
enabled = !loading || noBookNeeded,
modifier = Modifier.fillMaxWidth().height(56.dp),
) {
Text(
stringResource(
when {
ready || loading -> R.string.play_play
state is NetState.Failed -> R.string.play_retry
else -> R.string.play_download_and_play
},
),
)
}
}
Spacer(Modifier.height(12.dp))
// The state of Maia's file: always one line, so that nothing jumps.
Row(Modifier.fillMaxWidth().height(40.dp), verticalAlignment = Alignment.CenterVertically) {
when (val s = state) {
NetState.Ready -> Text(stringResource(R.string.play_maia_ready), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
NetState.Missing -> Text(
stringResource(R.string.play_download_note, megabytes(files.size)),
style = MaterialTheme.typography.bodySmall,
}
}
if (picking) {
// Closed without a choice the first time: Tal stays, and the list does not open
// by itself again (§3.4).
StylePicker(styles, style, onPick = { id ->
picking = false
app.settings.update { it.copy(rodentPersonality = id) }
}, onDismiss = {
picking = false
if (prefs.rodentPersonality.isEmpty()) app.settings.update { it.copy(rodentPersonality = style) }
})
}
}
@Composable
private fun StateText(text: String, modifier: Modifier = Modifier) {
// Not cut: with a large font the footer grows (§8.2).
Text(text, modifier.semantics { liveRegion = LiveRegionMode.Polite }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
/// One of the two opponents (§2.2): chosen, it is filled and ticked (not by colour alone).
@Composable
private fun OpponentCard(title: String, sub: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) {
OutlinedCard(
modifier = modifier.heightIn(min = 64.dp).selectable(selected = selected, role = Role.RadioButton, onClick = onClick),
shape = RoundedCornerShape(12.dp),
colors = CardDefaults.outlinedCardColors(
containerColor = if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surface,
),
border = BorderStroke(if (selected) 2.dp else 1.dp, if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant),
) {
Column(Modifier.padding(12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (selected) {
Icon(Icons.Rounded.Check, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.primary)
Spacer(Modifier.width(4.dp))
}
Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium, maxLines = 1)
}
Text(sub, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
}
/// The character's line (§2.3): Rodent's character, a tap opens the list; for Maia the
/// same line, inactive («Like a human»), so that the sheet keeps its height.
@Composable
private fun CharacterRow(style: RodentStyle?, onClick: () -> Unit) {
val title = style?.let { styleTitle(it.id) } ?: stringResource(R.string.like_human)
val about = style?.let { s -> RODENT_TEXTS[s.id]?.let { stringResource(it.second) } ?: s.about } ?: stringResource(R.string.maia_no_style)
val active = style != null
val described = if (active) stringResource(R.string.character_cd, title) + ". " + about else "$title. $about"
val change = stringResource(R.string.pick_change)
Row(
Modifier
.fillMaxWidth()
.heightIn(min = 80.dp)
.background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(12.dp))
.then(if (active) Modifier.clickable(onClickLabel = change, role = Role.Button, onClick = onClick) else Modifier)
.clearAndSetSemantics { contentDescription = described }
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
val dim = if (active) 1f else 0.38f
if (style != null) {
Initial(title, style.player)
} else {
Box(Modifier.size(40.dp).background(MaterialTheme.colorScheme.surfaceContainerHighest, CircleShape), contentAlignment = Alignment.Center) {
Icon(Icons.Rounded.Person, null, Modifier.size(24.dp), tint = MaterialTheme.colorScheme.onSurface.copy(alpha = dim))
}
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface.copy(alpha = dim), maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(about, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = dim), minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (active) Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
/// A character's initial in a circle (§3.2): the players in one colour, the characters
/// in another. Decoration: not read out.
@Composable
private fun Initial(title: String, player: Boolean) {
val (back, fore) = if (player) {
MaterialTheme.colorScheme.tertiaryContainer to MaterialTheme.colorScheme.onTertiaryContainer
} else {
MaterialTheme.colorScheme.secondaryContainer to MaterialTheme.colorScheme.onSecondaryContainer
}
Box(Modifier.size(40.dp).background(back, CircleShape), contentAlignment = Alignment.Center) {
Text(title.take(1), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium, color = fore)
}
}
/// «Who to play» (§3): Rodent IV's characters in two groups, each in the alphabet of the
/// app's language; a tap chooses and closes. Full screen on a phone, a dialog on a tablet.
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
private fun StylePicker(styles: List<RodentStyle>, selected: String, onPick: (String) -> Unit, onDismiss: () -> Unit) {
val wide = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.width.toDp() } >= 600.dp
val locale = LocalConfiguration.current.locales[0]
val titled = styles.map { it to styleTitle(it.id) }
val collator = remember(locale) { java.text.Collator.getInstance(locale) }
val groups = listOf(R.string.pick_players to true, R.string.pick_characters to false).map { (heading, player) ->
heading to titled.filter { it.first.player == player }.sortedWith { a, b -> collator.compare(a.second, b.second) }
}
// Opened with the chosen one in sight: the row above it just under the group's heading
// (which stays on top of the list), so that neither is cut.
val index = run {
var i = 0
for ((_, rows) in groups) {
i++ // the group's heading
val at = rows.indexOfFirst { it.first.id == selected }
if (at >= 0) return@run i + at
i += rows.size
}
0
}
val list = rememberLazyListState()
val headerPx = with(LocalDensity.current) { 48.dp.roundToPx() }
LaunchedEffect(Unit) {
// A negative offset: the row above starts below the sticky heading.
if (index >= 2) list.scrollToItem(index - 1, -headerPx)
}
// Full screen: edge to edge, the bars' insets inside. A dialog: in the window between
// the system bars, clipped to its corners, no insets of its own.
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = wide)) {
val frame = if (wide) {
Modifier.widthIn(max = 560.dp).fillMaxWidth().fillMaxHeight(0.9f).clip(RoundedCornerShape(28.dp))
} else {
Modifier.fillMaxSize()
}
val insets = if (wide) WindowInsets(0) else ScaffoldDefaults.contentWindowInsets
Scaffold(
modifier = frame,
containerColor = MaterialTheme.colorScheme.surface,
contentWindowInsets = insets,
topBar = {
Column {
TopAppBar(
windowInsets = if (wide) WindowInsets(0) else TopAppBarDefaults.windowInsets,
navigationIcon = { IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } },
title = { Text(stringResource(R.string.pick_title)) },
)
// Fixed under the bar: what the list is for, wherever it is scrolled.
Text(
stringResource(R.string.pick_intro),
Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
)
is NetState.Loading -> {
Column(Modifier.weight(1f)) {
LinearProgressIndicator(progress = { s.done.toFloat() / s.total.coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth())
Text(stringResource(R.string.downloaded_of, megabytes(s.done), megabytes(s.total)), style = MaterialTheme.typography.bodySmall.merge(Tabular))
}
IconButton(onClick = {
playAfter = false
files.cancel()
}) { Icon(Icons.Rounded.Close, stringResource(R.string.cancel_download)) }
}
is NetState.Failed -> Text(
when (s.problem) {
NetProblem.NoInternet -> stringResource(R.string.no_internet)
NetProblem.Interrupted -> stringResource(R.string.interrupted)
NetProblem.NoSpace -> stringResource(R.string.no_space, megabytes(files.size))
NetProblem.Corrupt -> stringResource(R.string.corrupt)
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
Spacer(Modifier.height(8.dp))
val loading = state is NetState.Loading
Button(
onClick = {
if (state == NetState.Ready) {
play()
} else {
playAfter = true
files.download()
},
) { padding ->
LazyColumn(Modifier.fillMaxSize().padding(padding), state = list) {
groups.forEach { (heading, rows) ->
stickyHeader(key = heading) {
Surface(color = MaterialTheme.colorScheme.surface) {
Text(
stringResource(heading),
Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 14.dp).semantics { heading() },
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
},
enabled = !loading,
modifier = Modifier.fillMaxWidth().height(56.dp),
) {
Text(
stringResource(
when (state) {
NetState.Ready, is NetState.Loading -> R.string.play_play
is NetState.Failed -> R.string.play_retry
NetState.Missing -> R.string.play_download_and_play
},
),
)
items(rows, key = { it.first.id }) { (st, title) ->
val on = st.id == selected
val about = RODENT_TEXTS[st.id]?.let { stringResource(it.second) } ?: st.about
val described = stringResource(if (st.player) R.string.pick_player_cd else R.string.pick_character_cd, title) + ". " + about
Row(
Modifier
.fillMaxWidth()
.heightIn(min = 72.dp)
.background(if (on) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent)
.selectable(selected = on, role = Role.RadioButton) { onPick(st.id) }
// One reading: the name, the group, what it does; not the texts again.
.clearAndSetSemantics {
contentDescription = described
this.selected = on
role = Role.RadioButton
onClick { onPick(st.id); true }
}
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Initial(title, st.player)
Spacer(Modifier.width(16.dp))
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.bodyLarge)
Text(about, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
if (on) Icon(Icons.Rounded.Check, null, Modifier.padding(start = 8.dp), tint = MaterialTheme.colorScheme.primary)
}
}
}
}
}
}
}
/// The name, with the players of this phone to pick from; under it, where the games go
/// (player-games.md §6).
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun NameField(name: String, record: Boolean, onName: (String) -> Unit) {
val app = app()
val players = remember { app.playerGames.players() }
var picking by remember { mutableStateOf(false) }
val line = if (!record) {
stringResource(R.string.player_line_off)
} else {
val db = app.playerGames.database(name)
when {
app.playerGames.tidy(name).isEmpty() -> stringResource(R.string.player_line_noname, db?.name ?: app.playerGames.dbName(""))
db != null -> stringResource(R.string.player_line_existing, db.name) + " · " +
androidx.compose.ui.res.pluralStringResource(R.plurals.games_count, db.games ?: 0, groupDigits(db.games ?: 0))
else -> stringResource(R.string.player_line_new, app.playerGames.dbName(name))
}
}
// The players whose names begin with what is typed (none once it is one of them).
val typed = app.playerGames.tidy(name).lowercase()
val matching = players.filter { it.lowercase().startsWith(typed) && it.lowercase() != typed }
// Opened by typing or by its arrow, not by a tap in the field (it would cover «Play»).
ExposedDropdownMenuBox(expanded = picking && matching.isNotEmpty(), onExpandedChange = { if (!it) picking = false }) {
OutlinedTextField(
name,
{
onName(it)
picking = it.isNotBlank()
},
Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
label = { Text(stringResource(R.string.play_your_name)) },
supportingText = { Text(line) },
trailingIcon = {
if (matching.isNotEmpty()) {
IconButton(onClick = { picking = !picking }) { ExposedDropdownMenuDefaults.TrailingIcon(expanded = picking) }
}
},
singleLine = true,
)
ExposedDropdownMenu(expanded = picking && matching.isNotEmpty(), onDismissRequest = { picking = false }) {
matching.forEach { p ->
DropdownMenuItem(text = { Text(p) }, onClick = {
onName(p)
picking = false
})
}
}
}

View file

@ -0,0 +1,48 @@
package io.github.vrubelroman.chesspenguin.ui
import io.github.vrubelroman.chesspenguin.R
/// Rodent IV's characters in the app's language (android-rodent.md §3.3): their names and
/// what they do, as the desktop app says them (apps/desktop/src/i18n.rs), by the ids of
/// the shared list (`play::rodent::STYLES`, given by `rodentStyles()`).
val RODENT_TEXTS: Map<String, Pair<Int, Int>> = mapOf(
"iv_amanda" to (R.string.rodent_iv_amanda to R.string.rodent_iv_amanda_about),
"iv_cloe" to (R.string.rodent_iv_cloe to R.string.rodent_iv_cloe_about),
"iv_deborah" to (R.string.rodent_iv_deborah to R.string.rodent_iv_deborah_about),
"iv_defender" to (R.string.rodent_iv_defender to R.string.rodent_iv_defender_about),
"iv_dynamic" to (R.string.rodent_iv_dynamic to R.string.rodent_iv_dynamic_about),
"iv_grumpy" to (R.string.rodent_iv_grumpy to R.string.rodent_iv_grumpy_about),
"iv_partisan" to (R.string.rodent_iv_partisan to R.string.rodent_iv_partisan_about),
"iv_pawnsacker" to (R.string.rodent_iv_pawnsacker to R.string.rodent_iv_pawnsacker_about),
"iv_pedrita" to (R.string.rodent_iv_pedrita to R.string.rodent_iv_pedrita_about),
"iv_preston" to (R.string.rodent_iv_preston to R.string.rodent_iv_preston_about),
"iv_simple" to (R.string.rodent_iv_simple to R.string.rodent_iv_simple_about),
"iv_spitfire" to (R.string.rodent_iv_spitfire to R.string.rodent_iv_spitfire_about),
"iv_strangler" to (R.string.rodent_iv_strangler to R.string.rodent_iv_strangler_about),
"iv_alekhine" to (R.string.rodent_iv_alekhine to R.string.rodent_iv_alekhine_about),
"iv_anand" to (R.string.rodent_iv_anand to R.string.rodent_iv_anand_about),
"iv_anderssen" to (R.string.rodent_iv_anderssen to R.string.rodent_iv_anderssen_about),
"iv_bosboom" to (R.string.rodent_iv_bosboom to R.string.rodent_iv_bosboom_about),
"iv_botvinnik" to (R.string.rodent_iv_botvinnik to R.string.rodent_iv_botvinnik_about),
"iv_fischer" to (R.string.rodent_iv_fischer to R.string.rodent_iv_fischer_about),
"iv_karpov" to (R.string.rodent_iv_karpov to R.string.rodent_iv_karpov_about),
"iv_kasparov" to (R.string.rodent_iv_kasparov to R.string.rodent_iv_kasparov_about),
"iv_kortchnoi" to (R.string.rodent_iv_kortchnoi to R.string.rodent_iv_kortchnoi_about),
"iv_larsen" to (R.string.rodent_iv_larsen to R.string.rodent_iv_larsen_about),
"iv_lasker" to (R.string.rodent_iv_lasker to R.string.rodent_iv_lasker_about),
"iv_marshall" to (R.string.rodent_iv_marshall to R.string.rodent_iv_marshall_about),
"iv_morphy" to (R.string.rodent_iv_morphy to R.string.rodent_iv_morphy_about),
"iv_nimzowitsch" to (R.string.rodent_iv_nimzowitsch to R.string.rodent_iv_nimzowitsch_about),
"iv_petrosian" to (R.string.rodent_iv_petrosian to R.string.rodent_iv_petrosian_about),
"iv_reti" to (R.string.rodent_iv_reti to R.string.rodent_iv_reti_about),
"iv_rubinstein" to (R.string.rodent_iv_rubinstein to R.string.rodent_iv_rubinstein_about),
"iv_spassky" to (R.string.rodent_iv_spassky to R.string.rodent_iv_spassky_about),
"iv_steinitz" to (R.string.rodent_iv_steinitz to R.string.rodent_iv_steinitz_about),
"iv_tal" to (R.string.rodent_iv_tal to R.string.rodent_iv_tal_about),
"iv_tarrasch" to (R.string.rodent_iv_tarrasch to R.string.rodent_iv_tarrasch_about),
"iv_topalov" to (R.string.rodent_iv_topalov to R.string.rodent_iv_topalov_about),
)
/// The character suggested first (android-rodent.md §3.4), and the one an unknown id
/// (of a later version) falls back to.
const val DEFAULT_RODENT_STYLE = "iv_tal"

View file

@ -5,6 +5,9 @@ import androidx.compose.material.icons.rounded.SdCard
import androidx.compose.material.icons.rounded.DeveloperBoard
import androidx.compose.material.icons.rounded.Timer
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.automirrored.rounded.MenuBook
import kotlinx.coroutines.launch
import androidx.compose.material.icons.rounded.Memory
import androidx.compose.material.icons.rounded.Translate
import androidx.compose.material.icons.rounded.Palette
@ -63,11 +66,14 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import java.util.Locale
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.BuildConfig
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.LANGUAGES
import io.github.vrubelroman.chesspenguin.data.Language
import io.github.vrubelroman.chesspenguin.data.NetProblem
import io.github.vrubelroman.chesspenguin.data.NetState
import io.github.vrubelroman.chesspenguin.data.Notation
import io.github.vrubelroman.chesspenguin.data.Theme
@ -178,6 +184,8 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () ->
// The same sheet as in a game: the size, mobile data, cancel (§9).
else -> Item(stringResource(R.string.engine_missing, size), null, icon = Icons.Rounded.Memory) { sheet = true }
}
// Rodent IV's opening books (android-rodent.md §7.2): the engine itself is in the app.
RodentBooks(snackbar)
Item(stringResource(R.string.lines), "${prefs.engineLines}", icon = Icons.AutoMirrored.Rounded.FormatListBulleted) {
choice = Choice(R.string.lines, listOf("1", "2", "3"), prefs.engineLines - 1) { i -> set { it.copy(engineLines = i + 1) } }
}
@ -267,6 +275,84 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () ->
}
}
/// «Rodent IV — opening books»: downloaded or not, with what is left to download;
/// download, or delete (not while a game against Rodent goes on); the progress and ✕
/// while downloading; why it failed, and «Try again».
@Composable
private fun RodentBooks(snackbar: androidx.compose.material3.SnackbarHostState) {
val app = app()
val books = app.rodentFiles.books
val state by books.state.collectAsState()
val game by app.maiaGames.current.collectAsState()
val playing = game?.let { !it.over && it.rival == io.github.vrubelroman.chesspenguin.data.Opponent.Rodent } == true
val scope = androidx.compose.runtime.rememberCoroutineScope()
val deletedText = stringResource(R.string.books_deleted)
val deleteText = stringResource(R.string.books_delete_cd)
fun mb(bytes: Long) = ((bytes + 999_999) / 1_000_000).toInt()
// The books checked so far stay: what is left is offered.
val left = remember(state) { books.remaining() }
Row(
Modifier.card().heightIn(min = 56.dp).padding(start = 16.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
ItemIcon(Icons.AutoMirrored.Rounded.MenuBook)
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.books_settings), style = MaterialTheme.typography.bodyLarge)
when (val s = state) {
is NetState.Loading -> {
androidx.compose.material3.LinearProgressIndicator(
progress = { s.done.toFloat() / s.total.coerceAtLeast(1) },
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
)
Text(
stringResource(R.string.downloaded_of, mb(s.done), mb(s.total)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
is NetState.Failed -> Text(
when (s.problem) {
NetProblem.NoInternet -> stringResource(R.string.no_internet)
NetProblem.Interrupted -> stringResource(R.string.interrupted)
NetProblem.NoSpace -> stringResource(R.string.no_space, mb(left))
NetProblem.Corrupt -> stringResource(R.string.corrupt)
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
)
NetState.Ready -> Text(
stringResource(R.string.books_downloaded_mb, mb(books.size)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
NetState.Missing -> Text(
stringResource(R.string.books_missing_mb, mb(left)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
when (state) {
is NetState.Loading -> IconButton(onClick = { books.cancel() }) {
Icon(Icons.Rounded.Close, stringResource(R.string.cancel_download))
}
NetState.Ready -> TextButton(
enabled = !playing,
modifier = Modifier.semantics { contentDescription = deleteText },
onClick = {
books.delete()
scope.launch {
snackbar.currentSnackbarData?.dismiss()
snackbar.showSnackbar(deletedText)
}
},
) { Text(stringResource(R.string.delete)) }
is NetState.Failed -> TextButton(onClick = { books.download() }) { Text(stringResource(R.string.play_retry)) }
NetState.Missing -> TextButton(onClick = { books.download() }) { Text(stringResource(R.string.download)) }
}
}
}
private class Choice(val title: Int, val options: List<String>, val selected: Int, val hint: Int? = null, val pick: (Int) -> Unit)
@Composable

View file

@ -396,7 +396,7 @@
<string name="new_game">Neue Partie</string>
<string name="own_databases">Meine Datenbanken</string>
<string name="own_new">+ Neue Datenbank</string>
<string name="own_empty">Hier stehen die Partien, die Sie eingeben oder gegen Maia spielen</string>
<string name="own_empty">Hier stehen die Partien, die Sie eingeben oder gegen den Computer spielen</string>
<string name="files">Dateien</string>
<string name="own_default_name">Meine Partien</string>
<string name="own_new_title">Neue Datenbank</string>
@ -479,7 +479,6 @@
<string name="color_white">Weiß</string>
<string name="color_black">Schwarz</string>
<string name="color_random">Zufällig</string>
<string name="play_opponent">Gegner — Maia %1$s</string>
<string name="play_measured">Die eigene Wertung von Maia: sie entspricht nicht der Elo eines Menschen.</string>
<string name="play_download_note">Maia wird einmalig heruntergeladen (%1$s MB, von huggingface.co, die Datei der Autoren selbst).</string>
<string name="play_download_and_play">Herunterladen und spielen</string>
@ -496,7 +495,6 @@
<string name="play_maia_resigns">Maia gibt auf</string>
<string name="play_note_from">Ab hier eine Partie gegen Maia %1$s.</string>
<string name="play_abort">Abbrechen</string>
<string name="play_with_maia">Gegen Maia spielen</string>
<string name="play_your_name">Ihr Name</string>
<string name="play_maia_ready">Maia ist heruntergeladen</string>
<string name="play_retry">Erneut versuchen</string>
@ -511,7 +509,6 @@
<string name="play_saved">✓ Gespeichert</string>
<string name="play_save">Speichern…</string>
<string name="play_adjourned_sub">Sie spielen %1$s · %2$s</string>
<string name="play_from_maia">Von hier gegen Maia weiterspielen…</string>
<string name="play_from_label">Nach %1$s</string>
<string name="sound">Ton</string>
<string name="undo_menu">Rückgängig</string>
@ -523,7 +520,7 @@
<string name="start_position">die Ausgangsstellung</string>
<string name="play_maia_stopped">Maia ist nicht gestartet.</string>
<string name="play_maia_reload">Maia neu herunterladen</string>
<string name="play_adjourned_q">Eine Partie gegen Maia %1$s ist zurückgestellt</string>
<string name="play_adjourned_q">Eine Partie gegen %1$s ist zurückgestellt</string>
<string name="play_continue_it">Fortsetzen</string>
<string name="play_start_new">Neue beginnen</string>
<string name="play_adjourned_new_text">Eine neue Partie ersetzt sie; das Gespielte kommt unvollendet in die Datenbank des Spielers.</string>
@ -537,7 +534,7 @@
<string name="player_written">✓ In „%1$s“, Nr. %2$s ›</string>
<string name="player_kept_unfinished">Partie unvollendet in „%1$s“ gespeichert</string>
<string name="player_db_row">werden selbst gespeichert</string>
<string name="record_games">Partien gegen Maia in die Datenbank des Spielers schreiben</string>
<string name="record_games">Partien gegen den Computer in die Datenbank des Spielers schreiben</string>
<string name="player_line_existing">Partien werden in „%1$s“ gespeichert</string>
<string name="player_line_new">Die Partien werden in eine neue Datenbank „%1$s“ gespeichert.</string>
<string name="player_line_noname">Ohne Namen gehen die Partien in „%1$s“. Geben Sie einen Namen ein, um eine eigene Datenbank zu bekommen.</string>
@ -546,6 +543,116 @@
<string name="player_write_failed">Konnte nicht in „%1$s“ schreiben: %2$s</string>
<string name="play_adjourned_replaced">Eine neue Partie ersetzt sie.</string>
<string name="last_opened">Zuletzt geöffnet</string>
<string name="play_adjourned_title">Partie gegen Maia %1$s</string>
<string name="play_adjourned_title">Partie gegen %1$s</string>
<string name="play_move_n">Zug %1$d</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Greift zuerst an, spielt dann auf aktive Figuren.</string>
<string name="rodent_iv_cloe">Cloe</string>
<string name="rodent_iv_cloe_about">Mag geschlossene Stellungen.</string>
<string name="rodent_iv_deborah">Deborah</string>
<string name="rodent_iv_deborah_about">Verteidigt gut und mag ihre Läufer.</string>
<string name="rodent_iv_defender">Verteidiger</string>
<string name="rodent_iv_defender_about">Solide und vorsichtig; mit Remis zufrieden.</string>
<string name="rodent_iv_dynamic">Dynamiker</string>
<string name="rodent_iv_dynamic_about">Greift an, mag Läufer, opfert ab und zu.</string>
<string name="rodent_iv_grumpy">Brummbär</string>
<string name="rodent_iv_grumpy_about">Angriff und Einengung; mag blockierte Stellungen, meidet Remis.</string>
<string name="rodent_iv_partisan">Partisan</string>
<string name="rodent_iv_partisan_about">Greift nach ruhigen, unauffälligen Eröffnungen an.</string>
<string name="rodent_iv_pawnsacker">Bauernopferer</string>
<string name="rodent_iv_pawnsacker_about">Ausgewogen, gibt aber eher Bauern her.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Bauern, Verteidigung und Einengung.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">Ein materialistischer, maßvoller Angreifer.</string>
<string name="rodent_iv_simple">Schlicht</string>
<string name="rodent_iv_simple_about">Am computerhaftesten: schlichtes, solides Schach.</string>
<string name="rodent_iv_spitfire">Hitzkopf</string>
<string name="rodent_iv_spitfire_about">Scharf und aggressiv.</string>
<string name="rodent_iv_strangler">Würger</string>
<string name="rodent_iv_strangler_about">Eine Würgeschlange: würgt langsam, sehr menschlich.</string>
<string name="rodent_iv_alekhine">Aljechin</string>
<string name="rodent_iv_alekhine_about">Dynamische Angriffe und tiefe Kombinationen.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Schnelles, universelles Spiel mit scharfen Eröffnungen.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">Ein romantischer Angreifer des 19. Jahrhunderts: Opfer.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Ausgefallene Eröffnungen und kreatives Blitzspiel.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Wissenschaftliches, strategisches Spiel aus tiefer Vorbereitung.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Klar, klassisch und präzise.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Positioneller Druck, Prophylaxe und Technik.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Initiative und kraftvoller Angriff.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">Ein zäher Verteidiger und Konterspieler.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">Originell und riskant, mit ausgefallenen Eröffnungen.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">Ein praktischer, psychologischer Kämpfer.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">Ein verwegener Angreifer mit Gambits.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Schnelle Entwicklung und offene Linien.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Einengung, Blockade und Überdeckung.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Prophylaxe und Sicherheit zuerst.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Hypermodern: kontrolliert das Zentrum aus der Ferne.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Klassisches Positionsspiel, stark im Endspiel.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">Ein Universalspieler, in jeder Stellung zu Hause.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">Der Begründer des Positionsspiels, ein hartnäckiger Verteidiger.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">Der Zauberer aus Riga: Opfer und Angriff.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Klassische Regeln: Raum, Entwicklung, aktive Figuren.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Aggressiv und dynamisch, opfert die Qualität.</string>
<string name="opp_maia_sub">spielt wie ein Mensch</string>
<string name="opp_rodent_sub">stark, mit Stil</string>
<string name="like_human">Wie ein Mensch</string>
<string name="maia_no_style">Maia wählt keinen Stil: Sie spielt wie Menschen ihrer Wertung.</string>
<string name="rodent_measured">Die eigene Wertung von Rodent (UCI_Elo): sie entspricht nicht der Elo eines Menschen.</string>
<string name="rodent_resigns">Rodent gibt auf</string>
<string name="end_rodent_resigned">Rodent hat aufgegeben</string>
<string name="rodent_draw_declined">Rodent lehnt das Remis ab</string>
<string name="rodent_draw_later">Rodent hat abgelehnt; nach zwei seiner Züge wieder anbieten</string>
<string name="rodent_position_lost">Seine Stellung ist verloren. Sieg annehmen oder zu Ende spielen?</string>
<string name="play_button">Spielen</string>
<string name="play_button_cd">Gegen den Computer spielen</string>
<string name="strength_n">Spielstärke: %1$s</string>
<string name="pick_title">Gegen wen spielen</string>
<string name="pick_intro">Ein Charakter ist ein Stil mit seinen Eröffnungen; die Spielstärke stellt der Schieberegler ein.</string>
<string name="pick_players">Große Spieler</string>
<string name="pick_characters">Charaktere</string>
<string name="pick_change">Ändern</string>
<string name="pick_player_cd">%1$s, großer Spieler</string>
<string name="pick_character_cd">%1$s, Charakter</string>
<string name="character_cd">Charakter: %1$s</string>
<string name="books_ready">Rodent IV und seine Eröffnungsbücher sind auf dem Telefon</string>
<string name="books_offer">Eröffnungsbücher von Rodent IV: %1$s MB, einmalig von github.com</string>
<string name="books_not_needed">Aus einer Stellung heraus ist kein Eröffnungsbuch nötig: Rodent IV spielt sofort</string>
<string name="books_without">Ohne Buch</string>
<string name="books_without_cd">Ohne Buch: ohne Eröffnungsbuch spielen</string>
<string name="books_notification">Eröffnungsbücher von Rodent IV</string>
<string name="books_settings">Rodent IV — Eröffnungsbücher</string>
<string name="books_downloaded_mb">heruntergeladen · %1$s MB</string>
<string name="books_missing_mb">nicht heruntergeladen · %1$s MB</string>
<string name="books_deleted">Eröffnungsbücher gelöscht</string>
<string name="rodent_draw_no_engine">Rodent beantwortet Remis mit Stockfish: über „Engine“ herunterladen</string>
<string name="rodent_stopped">Rodent ist nicht gestartet.</string>
<string name="rodent_restart">Neu starten</string>
<string name="play_note_from_rodent">Ab hier eine Partie gegen Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">Rodent hat während der Partie aufgehört.</string>
<string name="strength_range">%1$s, von %2$s bis %3$s</string>
<string name="strength">Spielstärke</string>
<string name="books_delete_cd">Eröffnungsbücher löschen</string>
</resources>

View file

@ -402,7 +402,7 @@
<string name="new_game">Nueva partida</string>
<string name="own_databases">Mis bases</string>
<string name="own_new">+ Nueva base</string>
<string name="own_empty">Aquí estarán las partidas que introduzcas o juegues contra Maia</string>
<string name="own_empty">Aquí estarán las partidas que introduzcas o juegues contra el ordenador</string>
<string name="files">Archivos</string>
<string name="own_default_name">Mis partidas</string>
<string name="own_new_title">Nueva base</string>
@ -487,7 +487,6 @@
<string name="color_white">Blancas</string>
<string name="color_black">Negras</string>
<string name="color_random">Al azar</string>
<string name="play_opponent">Rival — Maia %1$s</string>
<string name="play_measured">El rating propio de Maia: no equivale al Elo de una persona.</string>
<string name="play_download_note">Maia se descarga una sola vez (%1$s MB, desde huggingface.co, el archivo de los propios autores).</string>
<string name="play_download_and_play">Descargar y jugar</string>
@ -504,7 +503,6 @@
<string name="play_maia_resigns">Maia se rinde</string>
<string name="play_note_from">A partir de aquí, una partida contra Maia %1$s.</string>
<string name="play_abort">Abortar</string>
<string name="play_with_maia">Jugar con Maia</string>
<string name="play_your_name">Tu nombre</string>
<string name="play_maia_ready">Maia está descargada</string>
<string name="play_retry">Reintentar</string>
@ -519,7 +517,6 @@
<string name="play_saved">✓ Guardada</string>
<string name="play_save">Guardar…</string>
<string name="play_adjourned_sub">juegas con %1$s · %2$s</string>
<string name="play_from_maia">Seguir desde aquí contra Maia…</string>
<string name="play_from_label">Tras %1$s</string>
<string name="sound">Sonido</string>
<string name="undo_menu">Deshacer</string>
@ -531,7 +528,7 @@
<string name="start_position">la posición inicial</string>
<string name="play_maia_stopped">Maia no se inició.</string>
<string name="play_maia_reload">Volver a descargar Maia</string>
<string name="play_adjourned_q">Hay una partida aplazada contra Maia %1$s</string>
<string name="play_adjourned_q">Hay una partida aplazada contra %1$s</string>
<string name="play_continue_it">Continuarla</string>
<string name="play_start_new">Empezar una nueva</string>
<string name="play_adjourned_new_text">Una partida nueva la sustituye; lo jugado va sin terminar a la base del jugador.</string>
@ -545,7 +542,7 @@
<string name="player_written">✓ En «%1$s», n.º %2$s ›</string>
<string name="player_kept_unfinished">Partida guardada sin terminar en «%1$s»</string>
<string name="player_db_row">se guardan solas</string>
<string name="record_games">Guardar las partidas contra Maia en la base del jugador</string>
<string name="record_games">Guardar las partidas contra el ordenador en la base del jugador</string>
<string name="player_line_existing">Las partidas se guardan en «%1$s»</string>
<string name="player_line_new">Las partidas se guardarán en una base nueva «%1$s».</string>
<string name="player_line_noname">Sin nombre, las partidas van a «%1$s». Escribe un nombre para tener tu propia base.</string>
@ -554,6 +551,116 @@
<string name="player_write_failed">No se pudo escribir en «%1$s»: %2$s</string>
<string name="play_adjourned_replaced">Una partida nueva la sustituye.</string>
<string name="last_opened">Abierta por última vez</string>
<string name="play_adjourned_title">Partida contra Maia %1$s</string>
<string name="play_adjourned_title">Partida contra %1$s</string>
<string name="play_move_n">jugada %1$d</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Primero ataca, luego busca piezas activas.</string>
<string name="rodent_iv_cloe">Cloe</string>
<string name="rodent_iv_cloe_about">Le gustan las posiciones cerradas.</string>
<string name="rodent_iv_deborah">Débora</string>
<string name="rodent_iv_deborah_about">Defiende bien y le gustan sus alfiles.</string>
<string name="rodent_iv_defender">Defensor</string>
<string name="rodent_iv_defender_about">Sólido y prudente; se conforma con tablas.</string>
<string name="rodent_iv_dynamic">Dinámico</string>
<string name="rodent_iv_dynamic_about">Ataca, le gustan los alfiles, sacrifica de vez en cuando.</string>
<string name="rodent_iv_grumpy">Gruñón</string>
<string name="rodent_iv_grumpy_about">Ataque y restricción; le gustan las posiciones bloqueadas, evita las tablas.</string>
<string name="rodent_iv_partisan">Partisano</string>
<string name="rodent_iv_partisan_about">Ataca tras aperturas tranquilas y discretas.</string>
<string name="rodent_iv_pawnsacker">Gambitero</string>
<string name="rodent_iv_pawnsacker_about">Equilibrado, pero entrega peones con más facilidad.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Peones, defensa y restricción.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">Un atacante materialista y moderado.</string>
<string name="rodent_iv_simple">Sencillo</string>
<string name="rodent_iv_simple_about">El más «computadora»: ajedrez sencillo y sólido.</string>
<string name="rodent_iv_spitfire">Fogoso</string>
<string name="rodent_iv_spitfire_about">Agudo y agresivo.</string>
<string name="rodent_iv_strangler">Estrangulador</string>
<string name="rodent_iv_strangler_about">Una boa: asfixia despacio, muy humano.</string>
<string name="rodent_iv_alekhine">Alekhine</string>
<string name="rodent_iv_alekhine_about">Ataques dinámicos y combinaciones profundas.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Juego rápido y universal con aperturas agudas.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">Un atacante romántico del siglo XIX: sacrificios.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Aperturas poco habituales y blitz creativo.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Juego estratégico y científico, preparación profunda.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Claro, clásico y preciso.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Presión posicional, profilaxis y técnica.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Iniciativa y ataque poderoso.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">Un defensor tenaz y contraatacante.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">Original y arriesgado, con aperturas inusuales.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">Un luchador práctico y psicológico.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">Un atacante audaz, amigo de los gambitos.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Desarrollo rápido y líneas abiertas.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Restricción, bloqueo y sobreprotección.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Profilaxis y seguridad ante todo.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Hipermoderno: controla el centro a distancia.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Juego posicional clásico, gran finalista.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">Un jugador universal, cómodo en cualquier posición.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">El fundador del juego posicional, un defensor obstinado.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">El mago de Riga: sacrificios y ataque.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Reglas clásicas: espacio, desarrollo, piezas activas.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Agresivo y dinámico, sacrifica la calidad.</string>
<string name="opp_maia_sub">juega como una persona</string>
<string name="opp_rodent_sub">fuerte, con estilo</string>
<string name="like_human">Como una persona</string>
<string name="maia_no_style">Maia no elige estilo: juega como la gente de su nivel.</string>
<string name="rodent_measured">El rating propio de Rodent (UCI_Elo): no equivale al Elo de una persona.</string>
<string name="rodent_resigns">Rodent se rinde</string>
<string name="end_rodent_resigned">Rodent se rindió</string>
<string name="rodent_draw_declined">Rodent rechaza las tablas</string>
<string name="rodent_draw_later">Rodent lo rechazó; ofrece de nuevo tras dos de sus jugadas</string>
<string name="rodent_position_lost">Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final?</string>
<string name="play_button">Jugar</string>
<string name="play_button_cd">Jugar contra el ordenador</string>
<string name="strength_n">Fuerza: %1$s</string>
<string name="pick_title">Contra quién jugar</string>
<string name="pick_intro">Un carácter es un estilo y unas aperturas; la fuerza la marca el control deslizante.</string>
<string name="pick_players">Grandes jugadores</string>
<string name="pick_characters">Caracteres</string>
<string name="pick_change">Cambiar</string>
<string name="pick_player_cd">%1$s, gran jugador</string>
<string name="pick_character_cd">%1$s, carácter</string>
<string name="character_cd">Carácter: %1$s</string>
<string name="books_ready">Rodent IV y sus libros de aperturas están en el teléfono</string>
<string name="books_offer">Libros de aperturas de Rodent IV: %1$s MB, una sola vez de github.com</string>
<string name="books_not_needed">Desde una posición no hace falta libro de aperturas: Rodent IV juega enseguida</string>
<string name="books_without">Sin libro</string>
<string name="books_without_cd">Sin libro: jugar sin libro de aperturas</string>
<string name="books_notification">Libros de aperturas de Rodent IV</string>
<string name="books_settings">Rodent IV — libros de aperturas</string>
<string name="books_downloaded_mb">descargados · %1$s MB</string>
<string name="books_missing_mb">no descargados · %1$s MB</string>
<string name="books_deleted">Libros de aperturas eliminados</string>
<string name="rodent_draw_no_engine">Rodent responde a las tablas con Stockfish: descárgalo con «Motor»</string>
<string name="rodent_stopped">Rodent no se inició.</string>
<string name="rodent_restart">Reiniciar</string>
<string name="play_note_from_rodent">A partir de aquí, una partida contra Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">Rodent se detuvo durante la partida.</string>
<string name="strength_range">%1$s, de %2$s a %3$s</string>
<string name="strength">Fuerza</string>
<string name="books_delete_cd">Eliminar los libros de aperturas</string>
</resources>

View file

@ -402,7 +402,7 @@
<string name="new_game">Nouvelle partie</string>
<string name="own_databases">Mes bases</string>
<string name="own_new">+ Nouvelle base</string>
<string name="own_empty">Ici seront les parties que vous saisirez ou jouerez contre Maia</string>
<string name="own_empty">Ici seront les parties que vous saisirez ou jouerez contre l’ordinateur</string>
<string name="files">Fichiers</string>
<string name="own_default_name">Mes parties</string>
<string name="own_new_title">Nouvelle base</string>
@ -487,7 +487,6 @@
<string name="color_white">Blancs</string>
<string name="color_black">Noirs</string>
<string name="color_random">Au hasard</string>
<string name="play_opponent">Adversaire — Maia %1$s</string>
<string name="play_measured">Le classement propre de Maia : il ne correspond pas à l’Elo d’une personne.</string>
<string name="play_download_note">Maia est téléchargée une seule fois (%1$s Mo, depuis huggingface.co, le fichier des auteurs eux-mêmes).</string>
<string name="play_download_and_play">Télécharger et jouer</string>
@ -504,7 +503,6 @@
<string name="play_maia_resigns">Maia abandonne</string>
<string name="play_note_from">À partir d’ici, une partie contre Maia %1$s.</string>
<string name="play_abort">Abandonner</string>
<string name="play_with_maia">Jouer contre Maia</string>
<string name="play_your_name">Votre nom</string>
<string name="play_maia_ready">Maia est téléchargée</string>
<string name="play_retry">Réessayer</string>
@ -519,7 +517,6 @@
<string name="play_saved">✓ Enregistrée</string>
<string name="play_save">Enregistrer…</string>
<string name="play_adjourned_sub">vous jouez %1$s · %2$s</string>
<string name="play_from_maia">Continuer d’ici contre Maia…</string>
<string name="play_from_label">Après %1$s</string>
<string name="sound">Son</string>
<string name="undo_menu">Annuler</string>
@ -531,7 +528,7 @@
<string name="start_position">la position initiale</string>
<string name="play_maia_stopped">Maia n’a pas démarré.</string>
<string name="play_maia_reload">Retélécharger Maia</string>
<string name="play_adjourned_q">Une partie contre Maia %1$s est en attente</string>
<string name="play_adjourned_q">Une partie contre %1$s est en attente</string>
<string name="play_continue_it">La continuer</string>
<string name="play_start_new">En commencer une nouvelle</string>
<string name="play_adjourned_new_text">Une nouvelle partie la remplace ; ce qui a été joué va, inachevé, dans la base du joueur.</string>
@ -545,7 +542,7 @@
<string name="player_written">✓ Dans « %1$s », n° %2$s ›</string>
<string name="player_kept_unfinished">Partie enregistrée inachevée dans « %1$s »</string>
<string name="player_db_row">enregistrées d’elles-mêmes</string>
<string name="record_games">Enregistrer les parties contre Maia dans la base du joueur</string>
<string name="record_games">Enregistrer les parties contre l’ordinateur dans la base du joueur</string>
<string name="player_line_existing">Les parties sont enregistrées dans « %1$s »</string>
<string name="player_line_new">Les parties seront enregistrées dans une nouvelle base « %1$s ».</string>
<string name="player_line_noname">Sans nom, les parties vont dans « %1$s ». Saisissez un nom pour avoir votre propre base.</string>
@ -554,6 +551,116 @@
<string name="player_write_failed">Impossible d’écrire dans « %1$s » : %2$s</string>
<string name="play_adjourned_replaced">Une nouvelle partie la remplace.</string>
<string name="last_opened">Ouverte en dernier</string>
<string name="play_adjourned_title">Partie contre Maia %1$s</string>
<string name="play_adjourned_title">Partie contre %1$s</string>
<string name="play_move_n">coup %1$d</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Attaque d’abord, puis joue pour l’activité des pièces.</string>
<string name="rodent_iv_cloe">Cloé</string>
<string name="rodent_iv_cloe_about">Aime les positions fermées.</string>
<string name="rodent_iv_deborah">Déborah</string>
<string name="rodent_iv_deborah_about">Défend bien et aime ses fous.</string>
<string name="rodent_iv_defender">Défenseur</string>
<string name="rodent_iv_defender_about">Solide et prudent ; se contente de la nulle.</string>
<string name="rodent_iv_dynamic">Dynamique</string>
<string name="rodent_iv_dynamic_about">Attaque, aime les fous, sacrifie de temps en temps.</string>
<string name="rodent_iv_grumpy">Grincheux</string>
<string name="rodent_iv_grumpy_about">Attaque et restriction ; aime les positions bloquées, évite la nulle.</string>
<string name="rodent_iv_partisan">Partisan</string>
<string name="rodent_iv_partisan_about">Attaque après des ouvertures calmes et discrètes.</string>
<string name="rodent_iv_pawnsacker">Gambiteur</string>
<string name="rodent_iv_pawnsacker_about">Équilibré, mais cède plus volontiers des pions.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Pions, défense et restriction.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">Un attaquant matérialiste et modéré.</string>
<string name="rodent_iv_simple">Simplet</string>
<string name="rodent_iv_simple_about">Le plus « ordinateur » : un jeu simple et sain.</string>
<string name="rodent_iv_spitfire">Boutefeu</string>
<string name="rodent_iv_spitfire_about">Tranchant et agressif.</string>
<string name="rodent_iv_strangler">Étrangleur</string>
<string name="rodent_iv_strangler_about">Un boa : étouffe lentement, très humain.</string>
<string name="rodent_iv_alekhine">Alekhine</string>
<string name="rodent_iv_alekhine_about">Attaques dynamiques et combinaisons profondes.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Jeu rapide et universel, ouvertures tranchantes.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">Un attaquant romantique du XIXe siècle : sacrifices.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Ouvertures originales et blitz créatif.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Jeu stratégique et scientifique, préparation profonde.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Clair, classique et précis.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Étau positionnel, prophylaxie et technique.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Initiative et attaque puissante.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">Un défenseur tenace et contre-attaquant.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">Original et risqué, aux ouvertures insolites.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">Un combattant pratique et psychologue.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">Un attaquant fougueux, amateur de gambits.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Développement rapide et lignes ouvertes.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Restriction, blocus et surprotection.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Prophylaxie et sécurité avant tout.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Hypermoderne : contrôle le centre à distance.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Jeu positionnel classique, excellent en finale.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">Un joueur universel, à l’aise partout.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">Le fondateur du jeu positionnel, défenseur obstiné.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">Le magicien de Riga : sacrifices et attaque.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Règles classiques : espace, développement, pièces actives.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Agressif et dynamique, sacrifie la qualité.</string>
<string name="opp_maia_sub">joue comme un humain</string>
<string name="opp_rodent_sub">fort, avec un style</string>
<string name="like_human">Comme un humain</string>
<string name="maia_no_style">Maia ne choisit pas de style : elle joue comme les gens de son niveau.</string>
<string name="rodent_measured">Le classement propre de Rodent (UCI_Elo) : il ne correspond pas à l’Elo d’une personne.</string>
<string name="rodent_resigns">Rodent abandonne</string>
<string name="end_rodent_resigned">Rodent a abandonné</string>
<string name="rodent_draw_declined">Rodent refuse la nulle</string>
<string name="rodent_draw_later">Rodent a refusé ; reproposez après deux de ses coups</string>
<string name="rodent_position_lost">Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ?</string>
<string name="play_button">Jouer</string>
<string name="play_button_cd">Jouer contre l’ordinateur</string>
<string name="strength_n">Force : %1$s</string>
<string name="pick_title">Contre qui jouer</string>
<string name="pick_intro">Un caractère, c’est un style et des ouvertures ; le curseur règle la force.</string>
<string name="pick_players">Grands joueurs</string>
<string name="pick_characters">Caractères</string>
<string name="pick_change">Changer</string>
<string name="pick_player_cd">%1$s, grand joueur</string>
<string name="pick_character_cd">%1$s, caractère</string>
<string name="character_cd">Caractère : %1$s</string>
<string name="books_ready">Rodent IV et ses livres d’ouvertures sont sur le téléphone</string>
<string name="books_offer">Livres d’ouvertures de Rodent IV : %1$s Mo, une seule fois depuis github.com</string>
<string name="books_not_needed">Depuis une position, pas besoin de livre d’ouvertures : Rodent IV joue tout de suite</string>
<string name="books_without">Sans livre</string>
<string name="books_without_cd">Sans livre : jouer sans livre d’ouvertures</string>
<string name="books_notification">Livres d’ouvertures de Rodent IV</string>
<string name="books_settings">Rodent IV — livres d’ouvertures</string>
<string name="books_downloaded_mb">téléchargés · %1$s Mo</string>
<string name="books_missing_mb">non téléchargés · %1$s Mo</string>
<string name="books_deleted">Livres d’ouvertures supprimés</string>
<string name="rodent_draw_no_engine">Rodent répond à la nulle avec Stockfish : téléchargez-le avec « Moteur »</string>
<string name="rodent_stopped">Rodent n’a pas démarré.</string>
<string name="rodent_restart">Redémarrer</string>
<string name="play_note_from_rodent">À partir d’ici, une partie contre Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">Rodent s’est arrêté pendant la partie.</string>
<string name="strength_range">%1$s, de %2$s à %3$s</string>
<string name="strength">Force</string>
<string name="books_delete_cd">Supprimer les livres d’ouvertures</string>
</resources>

View file

@ -402,7 +402,7 @@
<string name="new_game">Nuova partita</string>
<string name="own_databases">I miei database</string>
<string name="own_new">+ Nuovo database</string>
<string name="own_empty">Qui ci saranno le partite che inserisci o giochi contro Maia</string>
<string name="own_empty">Qui ci saranno le partite che inserisci o giochi contro il computer</string>
<string name="files">File</string>
<string name="own_default_name">Le mie partite</string>
<string name="own_new_title">Nuovo database</string>
@ -487,7 +487,6 @@
<string name="color_white">Bianco</string>
<string name="color_black">Nero</string>
<string name="color_random">Casuale</string>
<string name="play_opponent">Avversario — Maia %1$s</string>
<string name="play_measured">Il rating proprio di Maia: non corrisponde all’Elo di una persona.</string>
<string name="play_download_note">Maia si scarica una sola volta (%1$s MB, da huggingface.co, il file degli autori stessi).</string>
<string name="play_download_and_play">Scarica e gioca</string>
@ -504,7 +503,6 @@
<string name="play_maia_resigns">Maia abbandona</string>
<string name="play_note_from">Da qui, una partita contro Maia %1$s.</string>
<string name="play_abort">Annulla</string>
<string name="play_with_maia">Gioca con Maia</string>
<string name="play_your_name">Il tuo nome</string>
<string name="play_maia_ready">Maia è scaricata</string>
<string name="play_retry">Riprova</string>
@ -519,7 +517,6 @@
<string name="play_saved">✓ Salvata</string>
<string name="play_save">Salva…</string>
<string name="play_adjourned_sub">giochi con %1$s · %2$s</string>
<string name="play_from_maia">Continua da qui contro Maia…</string>
<string name="play_from_label">Dopo %1$s</string>
<string name="sound">Suono</string>
<string name="undo_menu">Annulla</string>
@ -531,7 +528,7 @@
<string name="start_position">la posizione iniziale</string>
<string name="play_maia_stopped">Maia non si è avviata.</string>
<string name="play_maia_reload">Riscarica Maia</string>
<string name="play_adjourned_q">C’è una partita sospesa contro Maia %1$s</string>
<string name="play_adjourned_q">C’è una partita sospesa contro %1$s</string>
<string name="play_continue_it">Continuala</string>
<string name="play_start_new">Iniziarne una nuova</string>
<string name="play_adjourned_new_text">Una nuova partita la sostituisce; quanto giocato va, non finito, nel database del giocatore.</string>
@ -545,7 +542,7 @@
<string name="player_written">✓ In «%1$s», n. %2$s ›</string>
<string name="player_kept_unfinished">Partita salvata non finita in «%1$s»</string>
<string name="player_db_row">salvate da sole</string>
<string name="record_games">Salvare le partite contro Maia nel database del giocatore</string>
<string name="record_games">Salvare le partite contro il computer nel database del giocatore</string>
<string name="player_line_existing">Le partite vengono salvate in «%1$s»</string>
<string name="player_line_new">Le partite saranno salvate in un nuovo database «%1$s».</string>
<string name="player_line_noname">Senza nome le partite vanno in «%1$s». Inserisci un nome per avere un database tuo.</string>
@ -554,6 +551,116 @@
<string name="player_write_failed">Impossibile scrivere in «%1$s»: %2$s</string>
<string name="play_adjourned_replaced">Una nuova partita la sostituisce.</string>
<string name="last_opened">Aperta per ultima</string>
<string name="play_adjourned_title">Partita contro Maia %1$s</string>
<string name="play_adjourned_title">Partita contro %1$s</string>
<string name="play_move_n">mossa %1$d</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Prima attacca, poi gioca per l’attività dei pezzi.</string>
<string name="rodent_iv_cloe">Cloe</string>
<string name="rodent_iv_cloe_about">Ama le posizioni chiuse.</string>
<string name="rodent_iv_deborah">Debora</string>
<string name="rodent_iv_deborah_about">Difende bene e ama i suoi alfieri.</string>
<string name="rodent_iv_defender">Difensore</string>
<string name="rodent_iv_defender_about">Solido e prudente; si accontenta della patta.</string>
<string name="rodent_iv_dynamic">Dinamico</string>
<string name="rodent_iv_dynamic_about">Attacca, ama gli alfieri, sacrifica di tanto in tanto.</string>
<string name="rodent_iv_grumpy">Brontolo</string>
<string name="rodent_iv_grumpy_about">Attacco e restrizione; ama le posizioni bloccate, evita la patta.</string>
<string name="rodent_iv_partisan">Partigiano</string>
<string name="rodent_iv_partisan_about">Attacca dopo aperture tranquille e discrete.</string>
<string name="rodent_iv_pawnsacker">Gambettista</string>
<string name="rodent_iv_pawnsacker_about">Equilibrato, ma cede pedoni più volentieri.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Pedoni, difesa e restrizione.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">Un attaccante materialista e moderato.</string>
<string name="rodent_iv_simple">Semplice</string>
<string name="rodent_iv_simple_about">Il più «computer»: scacchi semplici e solidi.</string>
<string name="rodent_iv_spitfire">Testa calda</string>
<string name="rodent_iv_spitfire_about">Tagliente e aggressivo.</string>
<string name="rodent_iv_strangler">Strangolatore</string>
<string name="rodent_iv_strangler_about">Un boa: stringe lentamente, molto umano.</string>
<string name="rodent_iv_alekhine">Aljechin</string>
<string name="rodent_iv_alekhine_about">Attacchi dinamici e combinazioni profonde.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Gioco rapido e universale con aperture taglienti.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">Un attaccante romantico dell’Ottocento: sacrifici.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Aperture insolite e blitz creativo.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Gioco strategico e scientifico, preparazione profonda.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Chiaro, classico e preciso.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Morsa posizionale, profilassi e tecnica.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Iniziativa e attacco potente.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">Un difensore tenace e contrattaccante.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">Originale e rischioso, con aperture insolite.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">Un combattente pratico e psicologico.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">Un attaccante spavaldo con i gambetti.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Sviluppo rapido e linee aperte.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Restrizione, blocco e sovraprotezione.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Profilassi e sicurezza prima di tutto.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Ipermoderno: controlla il centro da lontano.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Gioco posizionale classico, ottimo nei finali.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">Un giocatore universale, a suo agio ovunque.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">Il fondatore del gioco posizionale, difensore ostinato.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">Il mago di Riga: sacrifici e attacco.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Regole classiche: spazio, sviluppo, pezzi attivi.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Aggressivo e dinamico, sacrifica la qualità.</string>
<string name="opp_maia_sub">gioca come un umano</string>
<string name="opp_rodent_sub">forte, con uno stile</string>
<string name="like_human">Come un umano</string>
<string name="maia_no_style">Maia non sceglie uno stile: gioca come le persone del suo livello.</string>
<string name="rodent_measured">Il rating proprio di Rodent (UCI_Elo): non corrisponde all’Elo di una persona.</string>
<string name="rodent_resigns">Rodent abbandona</string>
<string name="end_rodent_resigned">Rodent ha abbandonato</string>
<string name="rodent_draw_declined">Rodent rifiuta la patta</string>
<string name="rodent_draw_later">Rodent ha rifiutato; riproponi dopo due sue mosse</string>
<string name="rodent_position_lost">La sua posizione è persa. Accettare la vittoria o giocare fino in fondo?</string>
<string name="play_button">Gioca</string>
<string name="play_button_cd">Gioca contro il computer</string>
<string name="strength_n">Forza: %1$s</string>
<string name="pick_title">Contro chi giocare</string>
<string name="pick_intro">Un carattere è uno stile con le sue aperture; la forza la regola il cursore.</string>
<string name="pick_players">Grandi giocatori</string>
<string name="pick_characters">Caratteri</string>
<string name="pick_change">Cambia</string>
<string name="pick_player_cd">%1$s, grande giocatore</string>
<string name="pick_character_cd">%1$s, carattere</string>
<string name="character_cd">Carattere: %1$s</string>
<string name="books_ready">Rodent IV e i suoi libri di aperture sono sul telefono</string>
<string name="books_offer">Libri di aperture di Rodent IV: %1$s MB, una sola volta da github.com</string>
<string name="books_not_needed">Da una posizione non serve il libro di aperture: Rodent IV gioca subito</string>
<string name="books_without">Senza libro</string>
<string name="books_without_cd">Senza libro: gioca senza libro di aperture</string>
<string name="books_notification">Libri di aperture di Rodent IV</string>
<string name="books_settings">Rodent IV — libri di aperture</string>
<string name="books_downloaded_mb">scaricati · %1$s MB</string>
<string name="books_missing_mb">non scaricati · %1$s MB</string>
<string name="books_deleted">Libri di aperture eliminati</string>
<string name="rodent_draw_no_engine">Rodent risponde alla patta con Stockfish: scaricalo con «Motore»</string>
<string name="rodent_stopped">Rodent non si è avviato.</string>
<string name="rodent_restart">Riavvia</string>
<string name="play_note_from_rodent">Da qui, una partita contro Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">Rodent si è fermato durante la partita.</string>
<string name="strength_range">%1$s, da %2$s a %3$s</string>
<string name="strength">Forza</string>
<string name="books_delete_cd">Elimina i libri di aperture</string>
</resources>

View file

@ -397,7 +397,7 @@
<string name="new_game">Жаңа ойын</string>
<string name="own_databases">Менің базаларым</string>
<string name="own_new">+ Жаңа база</string>
<string name="own_empty">Мұнда сіз енгізген немесе Maia-мен ойнаған ойындар болады</string>
<string name="own_empty">Мұнда сіз енгізген немесе компьютермен ойнаған ойындар болады</string>
<string name="files">Файлдар</string>
<string name="own_default_name">Менің ойындарым</string>
<string name="own_new_title">Жаңа база</string>
@ -480,7 +480,6 @@
<string name="color_white">Ақтар</string>
<string name="color_black">Қаралар</string>
<string name="color_random">Кездейсоқ</string>
<string name="play_opponent">Қарсылас — Maia %1$s</string>
<string name="play_measured">Maia-ның өз рейтингі: ол адамның Эло рейтингіне сәйкес келмейді.</string>
<string name="play_download_note">Maia бір рет жүктеледі (%1$s МБ, huggingface.co сайтынан — авторлардың өз файлы).</string>
<string name="play_download_and_play">Жүктеп алып ойнау</string>
@ -497,7 +496,6 @@
<string name="play_maia_resigns">Maia беріледі</string>
<string name="play_note_from">Бұдан әрі — Maia %1$s-мен ойын.</string>
<string name="play_abort">Тоқтату</string>
<string name="play_with_maia">Maia-мен ойнау</string>
<string name="play_your_name">Атыңыз</string>
<string name="play_maia_ready">Maia жүктелді</string>
<string name="play_retry">Қайталау</string>
@ -512,7 +510,6 @@
<string name="play_saved">✓ Сақталды</string>
<string name="play_save">Сақтау…</string>
<string name="play_adjourned_sub">сіз %1$s · %2$s</string>
<string name="play_from_maia">Осы жерден Maia-мен жалғастыру…</string>
<string name="play_from_label">%1$s кейін</string>
<string name="sound">Дыбыс</string>
<string name="undo_menu">Болдырмау</string>
@ -524,7 +521,7 @@
<string name="start_position">бастапқы позиция</string>
<string name="play_maia_stopped">Maia іске қосылмады.</string>
<string name="play_maia_reload">Maia-ны қайта жүктеу</string>
<string name="play_adjourned_q">Maia %1$s-мен кейінге қалдырылған ойын бар</string>
<string name="play_adjourned_q">%1$s-мен кейінге қалдырылған ойын бар</string>
<string name="play_continue_it">Жалғастыру</string>
<string name="play_start_new">Жаңасын бастау</string>
<string name="play_adjourned_new_text">Жаңа ойын оның орнын басады; ойналғаны аяқталмаған күйде ойыншы базасына жазылады.</string>
@ -538,7 +535,7 @@
<string name="player_written">✓ «%1$s» базасында, № %2$s ›</string>
<string name="player_kept_unfinished">Ойын аяқталмаған күйде «%1$s» базасына жазылды</string>
<string name="player_db_row">өзі жазылады</string>
<string name="record_games">Maia-мен ойындарды ойыншы базасына жазу</string>
<string name="record_games">Компьютермен ойындарды ойыншы базасына жазу</string>
<string name="player_line_existing">Ойындар «%1$s» базасына жазылады</string>
<string name="player_line_new">Ойындар жаңа «%1$s» базасына жазылады.</string>
<string name="player_line_noname">Атсыз ойындар «%1$s» базасына түседі. Өз базаңыз болуы үшін атыңызды жазыңыз.</string>
@ -547,6 +544,116 @@
<string name="player_write_failed">«%1$s» базасына жазу мүмкін болмады: %2$s</string>
<string name="play_adjourned_replaced">Жаңа ойын оның орнын басады.</string>
<string name="last_opened">Соңғы ашылған</string>
<string name="play_adjourned_title">Maia %1$s-мен ойын</string>
<string name="play_adjourned_title">%1$s-мен ойын</string>
<string name="play_move_n">%1$d-жүріс</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Аманда</string>
<string name="rodent_iv_amanda_about">Алдымен шабуылдайды, кейін фигуралар белсенділігіне ойнайды.</string>
<string name="rodent_iv_cloe">Клои</string>
<string name="rodent_iv_cloe_about">Жабық позицияларды ұнатады.</string>
<string name="rodent_iv_deborah">Дебора</string>
<string name="rodent_iv_deborah_about">Жақсы қорғанады және пілдерін ұнатады.</string>
<string name="rodent_iv_defender">Қорғаушы</string>
<string name="rodent_iv_defender_about">Сенімді әрі сақ; тең ойынға келіседі.</string>
<string name="rodent_iv_dynamic">Динамик</string>
<string name="rodent_iv_dynamic_about">Шабуылдайды, пілдерді ұнатады, анда-санда құрбан етеді.</string>
<string name="rodent_iv_grumpy">Күңкілдек</string>
<string name="rodent_iv_grumpy_about">Шабуыл мен қысу; бітелген позицияларды ұнатады, тең ойыннан қашады.</string>
<string name="rodent_iv_partisan">Партизан</string>
<string name="rodent_iv_partisan_about">Тыныш, байқалмайтын дебюттерден кейін шабуылдайды.</string>
<string name="rodent_iv_pawnsacker">Гамбитші</string>
<string name="rodent_iv_pawnsacker_about">Теңгерімді, бірақ пешкаларды оңай береді.</string>
<string name="rodent_iv_pedrita">Педрита</string>
<string name="rodent_iv_pedrita_about">Пешкалар, қорғаныс және қысу.</string>
<string name="rodent_iv_preston">Престон</string>
<string name="rodent_iv_preston_about">Материалист, қалыпты шабуылшы.</string>
<string name="rodent_iv_simple">Қарапайым</string>
<string name="rodent_iv_simple_about">Ең «компьютерлік»: қарапайым, дұрыс шахмат.</string>
<string name="rodent_iv_spitfire">Қызба</string>
<string name="rodent_iv_spitfire_about">Өткір және агрессивті.</string>
<string name="rodent_iv_strangler">Тұншықтырушы</string>
<string name="rodent_iv_strangler_about">Айдаһар-жылан: баяу қысады, өте адамға ұқсас.</string>
<string name="rodent_iv_alekhine">Алехин</string>
<string name="rodent_iv_alekhine_about">Серпінді шабуылдар мен терең комбинациялар.</string>
<string name="rodent_iv_anand">Ананд</string>
<string name="rodent_iv_anand_about">Жылдам, әмбебап ойын, өткір дебюттермен.</string>
<string name="rodent_iv_anderssen">Андерсен</string>
<string name="rodent_iv_anderssen_about">XIX ғасырдың романтик шабуылшысы: құрбандар.</string>
<string name="rodent_iv_bosboom">Босбум</string>
<string name="rodent_iv_bosboom_about">Әдеттен тыс дебюттер және шығармашыл блиц.</string>
<string name="rodent_iv_botvinnik">Ботвинник</string>
<string name="rodent_iv_botvinnik_about">Терең дайындыққа негізделген ғылыми, стратегиялық ойын.</string>
<string name="rodent_iv_fischer">Фишер</string>
<string name="rodent_iv_fischer_about">Анық, классикалық және дәл.</string>
<string name="rodent_iv_karpov">Карпов</string>
<string name="rodent_iv_karpov_about">Позициялық қысым, профилактика және техника.</string>
<string name="rodent_iv_kasparov">Каспаров</string>
<string name="rodent_iv_kasparov_about">Бастама және қуатты шабуыл.</string>
<string name="rodent_iv_kortchnoi">Корчной</string>
<string name="rodent_iv_kortchnoi_about">Табанды қорғаушы және қарсы шабуылшы.</string>
<string name="rodent_iv_larsen">Ларсен</string>
<string name="rodent_iv_larsen_about">Өзгеше және тәуекелшіл, әдеттен тыс дебюттермен.</string>
<string name="rodent_iv_lasker">Ласкер</string>
<string name="rodent_iv_lasker_about">Практикалық, психолог күрескер.</string>
<string name="rodent_iv_marshall">Маршалл</string>
<string name="rodent_iv_marshall_about">Гамбиттері бар батыл шабуылшы.</string>
<string name="rodent_iv_morphy">Морфи</string>
<string name="rodent_iv_morphy_about">Жылдам дамыту және ашық сызықтар.</string>
<string name="rodent_iv_nimzowitsch">Нимцович</string>
<string name="rodent_iv_nimzowitsch_about">Қысу, блокада және артық қорғау.</string>
<string name="rodent_iv_petrosian">Петросян</string>
<string name="rodent_iv_petrosian_about">Профилактика және қауіпсіздік бірінші.</string>
<string name="rodent_iv_reti">Рети</string>
<string name="rodent_iv_reti_about">Гиперзаманауи: орталықты алыстан бақылайды.</string>
<string name="rodent_iv_rubinstein">Рубинштейн</string>
<string name="rodent_iv_rubinstein_about">Классикалық позициялық ойын, эндшпильде мықты.</string>
<string name="rodent_iv_spassky">Спасский</string>
<string name="rodent_iv_spassky_about">Әмбебап ойыншы, кез келген позицияда өзін үйдегідей сезінеді.</string>
<string name="rodent_iv_steinitz">Стейниц</string>
<string name="rodent_iv_steinitz_about">Позициялық ойынның негізін салушы, қыңыр қорғаушы.</string>
<string name="rodent_iv_tal">Таль</string>
<string name="rodent_iv_tal_about">Ригалық сиқыршы: құрбандар мен шабуыл.</string>
<string name="rodent_iv_tarrasch">Тарраш</string>
<string name="rodent_iv_tarrasch_about">Классикалық ережелер: кеңістік, дамыту, белсенді фигуралар.</string>
<string name="rodent_iv_topalov">Топалов</string>
<string name="rodent_iv_topalov_about">Агрессивті және серпінді, сапаны құрбан етеді.</string>
<string name="opp_maia_sub">адам сияқты ойнайды</string>
<string name="opp_rodent_sub">күшті, стилімен</string>
<string name="like_human">Адам сияқты</string>
<string name="maia_no_style">Maia стиль таңдамайды: ол өз рейтингіндегі адамдар сияқты ойнайды.</string>
<string name="rodent_measured">Rodent-тің өз рейтингі (UCI_Elo): ол адамның Эло рейтингіне сәйкес келмейді.</string>
<string name="rodent_resigns">Rodent беріледі</string>
<string name="end_rodent_resigned">Rodent берілді</string>
<string name="rodent_draw_declined">Rodent тең ойыннан бас тартады</string>
<string name="rodent_draw_later">Rodent бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз</string>
<string name="rodent_position_lost">Оның позициясы ұтылды. Жеңісті қабылдайсыз ба, әлде соңына дейін ойнайсыз ба?</string>
<string name="play_button">Ойнау</string>
<string name="play_button_cd">Компьютермен ойнау</string>
<string name="strength_n">Күші: %1$s</string>
<string name="pick_title">Кіммен ойнау</string>
<string name="pick_intro">Мінез — бұл стиль мен дебюттер, күшті жүгірткі белгілейді.</string>
<string name="pick_players">Ұлы шахматшылар</string>
<string name="pick_characters">Мінездер</string>
<string name="pick_change">Өзгерту</string>
<string name="pick_player_cd">%1$s, ұлы шахматшы</string>
<string name="pick_character_cd">%1$s, мінез</string>
<string name="character_cd">Мінез: %1$s</string>
<string name="books_ready">Rodent IV және оның дебют кітаптары телефонда</string>
<string name="books_offer">Rodent IV дебют кітаптары: %1$s МБ, github.com сайтынан бір рет</string>
<string name="books_not_needed">Позициядан ойнағанда дебют кітабы керек емес — Rodent IV бірден ойнайды</string>
<string name="books_without">Кітапсыз</string>
<string name="books_without_cd">Кітапсыз: дебют кітабысыз ойнау</string>
<string name="books_notification">Rodent IV дебют кітаптары</string>
<string name="books_settings">Rodent IV — дебют кітаптары</string>
<string name="books_downloaded_mb">жүктелген · %1$s МБ</string>
<string name="books_missing_mb">жүктелмеген · %1$s МБ</string>
<string name="books_deleted">Дебют кітаптары жойылды</string>
<string name="rodent_draw_no_engine">Rodent тең ойынға Stockfish арқылы жауап береді: оны «Қозғалтқыш» батырмасымен жүктеңіз</string>
<string name="rodent_stopped">Rodent іске қосылмады.</string>
<string name="rodent_restart">Қайта іске қосу</string>
<string name="play_note_from_rodent">Бұдан әрі — Rodent IV %1$s-мен ойын (%2$s).</string>
<string name="rodent_stopped_playing">Rodent ойын кезінде тоқтады.</string>
<string name="strength_range">%1$s, %2$s-ден %3$s-ге дейін</string>
<string name="strength">Күші</string>
<string name="books_delete_cd">Дебют кітаптарын жою</string>
</resources>

View file

@ -403,7 +403,7 @@
<string name="new_game">Nova partida</string>
<string name="own_databases">Minhas bases</string>
<string name="own_new">+ Nova base</string>
<string name="own_empty">Aqui ficarão as partidas que você inserir ou jogar contra a Maia</string>
<string name="own_empty">Aqui ficarão as partidas que você inserir ou jogar contra o computador</string>
<string name="files">Arquivos</string>
<string name="own_default_name">Minhas partidas</string>
<string name="own_new_title">Nova base</string>
@ -488,7 +488,6 @@
<string name="color_white">Brancas</string>
<string name="color_black">Pretas</string>
<string name="color_random">Aleatório</string>
<string name="play_opponent">Adversário — Maia %1$s</string>
<string name="play_measured">O rating próprio da Maia: não corresponde ao Elo de uma pessoa.</string>
<string name="play_download_note">A Maia é baixada uma única vez (%1$s MB, de huggingface.co, o arquivo dos próprios autores).</string>
<string name="play_download_and_play">Baixar e jogar</string>
@ -505,7 +504,6 @@
<string name="play_maia_resigns">Maia desiste</string>
<string name="play_note_from">A partir daqui, uma partida contra Maia %1$s.</string>
<string name="play_abort">Abortar</string>
<string name="play_with_maia">Jogar com a Maia</string>
<string name="play_your_name">O seu nome</string>
<string name="play_maia_ready">A Maia foi baixada</string>
<string name="play_retry">Tentar de novo</string>
@ -520,7 +518,6 @@
<string name="play_saved">✓ Salva</string>
<string name="play_save">Salvar…</string>
<string name="play_adjourned_sub">você joga de %1$s · %2$s</string>
<string name="play_from_maia">Continuar daqui contra a Maia…</string>
<string name="play_from_label">Depois de %1$s</string>
<string name="sound">Som</string>
<string name="undo_menu">Desfazer</string>
@ -532,7 +529,7 @@
<string name="start_position">a posição inicial</string>
<string name="play_maia_stopped">A Maia não iniciou.</string>
<string name="play_maia_reload">Baixar a Maia de novo</string>
<string name="play_adjourned_q">Há uma partida adiada contra a Maia %1$s</string>
<string name="play_adjourned_q">Há uma partida adiada contra %1$s</string>
<string name="play_continue_it">Continuá-la</string>
<string name="play_start_new">Começar uma nova</string>
<string name="play_adjourned_new_text">Uma nova partida a substitui; o que foi jogado vai, inacabado, para a base do jogador.</string>
@ -546,7 +543,7 @@
<string name="player_written">✓ Em «%1$s», n.º %2$s ›</string>
<string name="player_kept_unfinished">Partida gravada inacabada em «%1$s»</string>
<string name="player_db_row">gravadas sozinhas</string>
<string name="record_games">Gravar as partidas contra a Maia na base do jogador</string>
<string name="record_games">Gravar as partidas contra o computador na base do jogador</string>
<string name="player_line_existing">As partidas são gravadas em «%1$s»</string>
<string name="player_line_new">As partidas serão gravadas numa nova base «%1$s».</string>
<string name="player_line_noname">Sem nome, as partidas vão para «%1$s». Escreva um nome para ter a sua própria base.</string>
@ -555,6 +552,116 @@
<string name="player_write_failed">Não foi possível gravar em «%1$s»: %2$s</string>
<string name="play_adjourned_replaced">Uma nova partida a substitui.</string>
<string name="last_opened">Aberta por último</string>
<string name="play_adjourned_title">Partida contra a Maia %1$s</string>
<string name="play_adjourned_title">Partida contra %1$s</string>
<string name="play_move_n">lance %1$d</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Primeiro ataca, depois joga pela atividade das peças.</string>
<string name="rodent_iv_cloe">Cloe</string>
<string name="rodent_iv_cloe_about">Gosta de posições fechadas.</string>
<string name="rodent_iv_deborah">Débora</string>
<string name="rodent_iv_deborah_about">Defende bem e gosta dos seus bispos.</string>
<string name="rodent_iv_defender">Defensor</string>
<string name="rodent_iv_defender_about">Sólido e cuidadoso; contenta-se com o empate.</string>
<string name="rodent_iv_dynamic">Dinâmico</string>
<string name="rodent_iv_dynamic_about">Ataca, gosta de bispos, sacrifica de vez em quando.</string>
<string name="rodent_iv_grumpy">Rabugento</string>
<string name="rodent_iv_grumpy_about">Ataque e restrição; gosta de posições bloqueadas, evita empates.</string>
<string name="rodent_iv_partisan">Partisano</string>
<string name="rodent_iv_partisan_about">Ataca depois de aberturas calmas e discretas.</string>
<string name="rodent_iv_pawnsacker">Gambiteiro</string>
<string name="rodent_iv_pawnsacker_about">Equilibrado, mas entrega peões com mais facilidade.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Peões, defesa e restrição.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">Um atacante materialista e moderado.</string>
<string name="rodent_iv_simple">Simples</string>
<string name="rodent_iv_simple_about">O mais «computador»: xadrez simples e sólido.</string>
<string name="rodent_iv_spitfire">Esquentado</string>
<string name="rodent_iv_spitfire_about">Agudo e agressivo.</string>
<string name="rodent_iv_strangler">Estrangulador</string>
<string name="rodent_iv_strangler_about">Uma jiboia: aperta devagar, muito humano.</string>
<string name="rodent_iv_alekhine">Alekhine</string>
<string name="rodent_iv_alekhine_about">Ataques dinâmicos e combinações profundas.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Jogo rápido e universal com aberturas agudas.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">Um atacante romântico do século XIX: sacrifícios.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Aberturas incomuns e blitz criativo.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Jogo estratégico e científico, preparação profunda.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Claro, clássico e preciso.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Pressão posicional, profilaxia e técnica.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Iniciativa e ataque poderoso.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">Um defensor tenaz e contra-atacante.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">Original e arriscado, com aberturas incomuns.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">Um lutador prático e psicológico.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">Um atacante ousado com gambitos.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Desenvolvimento rápido e linhas abertas.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Restrição, bloqueio e superproteção.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Profilaxia e segurança acima de tudo.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Hipermoderno: controla o centro à distância.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Jogo posicional clássico, ótimo em finais.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">Um jogador universal, à vontade em qualquer posição.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">O fundador do jogo posicional, um defensor obstinado.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">O mágico de Riga: sacrifícios e ataque.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Regras clássicas: espaço, desenvolvimento, peças ativas.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Agressivo e dinâmico, sacrifica a qualidade.</string>
<string name="opp_maia_sub">joga como um humano</string>
<string name="opp_rodent_sub">forte, com estilo</string>
<string name="like_human">Como um humano</string>
<string name="maia_no_style">A Maia não escolhe estilo: joga como as pessoas do nível dela.</string>
<string name="rodent_measured">O rating próprio do Rodent (UCI_Elo): não corresponde ao Elo de uma pessoa.</string>
<string name="rodent_resigns">O Rodent desiste</string>
<string name="end_rodent_resigned">O Rodent desistiu</string>
<string name="rodent_draw_declined">O Rodent recusa o empate</string>
<string name="rodent_draw_later">O Rodent recusou; ofereça de novo após dois lances dele</string>
<string name="rodent_position_lost">A posição dele está perdida. Aceitar a vitória ou jogar até o fim?</string>
<string name="play_button">Jogar</string>
<string name="play_button_cd">Jogar contra o computador</string>
<string name="strength_n">Força: %1$s</string>
<string name="pick_title">Contra quem jogar</string>
<string name="pick_intro">Um caráter é um estilo e suas aberturas; a força é definida pelo controle deslizante.</string>
<string name="pick_players">Grandes jogadores</string>
<string name="pick_characters">Caracteres</string>
<string name="pick_change">Alterar</string>
<string name="pick_player_cd">%1$s, grande jogador</string>
<string name="pick_character_cd">%1$s, caráter</string>
<string name="character_cd">Caráter: %1$s</string>
<string name="books_ready">O Rodent IV e seus livros de aberturas estão no telefone</string>
<string name="books_offer">Livros de aberturas do Rodent IV: %1$s MB, baixados uma vez de github.com</string>
<string name="books_not_needed">A partir de uma posição não é preciso livro de aberturas: o Rodent IV joga na hora</string>
<string name="books_without">Sem livro</string>
<string name="books_without_cd">Sem livro: jogar sem livro de aberturas</string>
<string name="books_notification">Livros de aberturas do Rodent IV</string>
<string name="books_settings">Rodent IV — livros de aberturas</string>
<string name="books_downloaded_mb">baixados · %1$s MB</string>
<string name="books_missing_mb">não baixados · %1$s MB</string>
<string name="books_deleted">Livros de aberturas excluídos</string>
<string name="rodent_draw_no_engine">O Rodent responde ao empate com o Stockfish: baixe-o com «Motor»</string>
<string name="rodent_stopped">O Rodent não iniciou.</string>
<string name="rodent_restart">Reiniciar</string>
<string name="play_note_from_rodent">A partir daqui, uma partida contra Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">O Rodent parou durante a partida.</string>
<string name="strength_range">%1$s, de %2$s a %3$s</string>
<string name="strength">Força</string>
<string name="books_delete_cd">Excluir os livros de aberturas</string>
</resources>

View file

@ -408,7 +408,7 @@
<string name="new_game">Новая партия</string>
<string name="own_databases">Мои базы</string>
<string name="own_new">+ Новая база</string>
<string name="own_empty">Здесь будут партии, которые вы введёте или сыграете с Maia</string>
<string name="own_empty">Здесь будут партии, которые вы введёте или сыграете с компьютером</string>
<string name="files">Файлы</string>
<string name="own_default_name">Мои партии</string>
<string name="own_new_title">Новая база</string>
@ -495,7 +495,6 @@
<string name="color_white">Белые</string>
<string name="color_black">Чёрные</string>
<string name="color_random">Случайно</string>
<string name="play_opponent">Соперник — Maia %1$s</string>
<string name="play_measured">Собственный рейтинг Maia: он не равен Эло человека.</string>
<string name="play_download_note">Maia скачивается один раз (%1$s МБ, с huggingface.co — файл самих авторов).</string>
<string name="play_download_and_play">Скачать и играть</string>
@ -512,7 +511,6 @@
<string name="play_maia_resigns">Maia сдаётся</string>
<string name="play_note_from">Дальше — игра с Maia %1$s.</string>
<string name="play_abort">Прервать</string>
<string name="play_with_maia">Играть с Maia</string>
<string name="play_your_name">Ваше имя</string>
<string name="play_maia_ready">Maia скачана</string>
<string name="play_retry">Повторить</string>
@ -527,7 +525,6 @@
<string name="play_saved">✓ Сохранено</string>
<string name="play_save">Сохранить…</string>
<string name="play_adjourned_sub">вы %1$s · %2$s</string>
<string name="play_from_maia">Играть отсюда с Maia…</string>
<string name="play_from_label">После %1$s</string>
<string name="sound">Звук</string>
<string name="undo_menu">Отменить</string>
@ -539,7 +536,7 @@
<string name="start_position">начальная позиция</string>
<string name="play_maia_stopped">Maia не запустилась.</string>
<string name="play_maia_reload">Скачать Maia заново</string>
<string name="play_adjourned_q">Есть отложенная партия с Maia %1$s</string>
<string name="play_adjourned_q">Есть отложенная партия с %1$s</string>
<string name="play_continue_it">Продолжить её</string>
<string name="play_start_new">Начать новую</string>
<string name="play_adjourned_new_text">Новая партия заменит её; сыгранное запишется в базу игрока неоконченным.</string>
@ -553,7 +550,7 @@
<string name="player_written">✓ В «%1$s», № %2$s ›</string>
<string name="player_kept_unfinished">Партия записана в «%1$s» неоконченной</string>
<string name="player_db_row">пишутся сами</string>
<string name="record_games">Записывать партии с Maia в базу игрока</string>
<string name="record_games">Записывать партии с компьютером в базу игрока</string>
<string name="player_line_existing">Партии записываются в «%1$s»</string>
<string name="player_line_new">Партии будут записываться в новую базу «%1$s».</string>
<string name="player_line_noname">Без имени партии идут в «%1$s». Впишите имя — заведём вашу базу.</string>
@ -562,6 +559,116 @@
<string name="player_write_failed">Не удалось записать в «%1$s»: %2$s</string>
<string name="play_adjourned_replaced">Новая партия заменит её.</string>
<string name="last_opened">Открыта последней</string>
<string name="play_adjourned_title">Партия с Maia %1$s</string>
<string name="play_adjourned_title">Партия с %1$s</string>
<string name="play_move_n">%1$d-й ход</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Аманда</string>
<string name="rodent_iv_amanda_about">Сначала атакует, потом играет на активность фигур.</string>
<string name="rodent_iv_cloe">Клои</string>
<string name="rodent_iv_cloe_about">Любит закрытые позиции.</string>
<string name="rodent_iv_deborah">Дебора</string>
<string name="rodent_iv_deborah_about">Хорошо защищается и любит слонов.</string>
<string name="rodent_iv_defender">Защитник</string>
<string name="rodent_iv_defender_about">Надёжный и осторожный, согласен на ничью.</string>
<string name="rodent_iv_dynamic">Динамик</string>
<string name="rodent_iv_dynamic_about">Атакует, любит слонов, время от времени жертвует.</string>
<string name="rodent_iv_grumpy">Ворчун</string>
<string name="rodent_iv_grumpy_about">Атака и сковывание; любит запертые позиции, избегает ничьих.</string>
<string name="rodent_iv_partisan">Партизан</string>
<string name="rodent_iv_partisan_about">Атакует после тихих, неприметных дебютов.</string>
<string name="rodent_iv_pawnsacker">Гамбитист</string>
<string name="rodent_iv_pawnsacker_about">Сбалансированный, но охотнее отдаёт пешки.</string>
<string name="rodent_iv_pedrita">Педрита</string>
<string name="rodent_iv_pedrita_about">Пешки, защита и сковывание.</string>
<string name="rodent_iv_preston">Престон</string>
<string name="rodent_iv_preston_about">Материалист, атакует умеренно.</string>
<string name="rodent_iv_simple">Простак</string>
<string name="rodent_iv_simple_about">Самый «компьютерный»: простые, правильные шахматы.</string>
<string name="rodent_iv_spitfire">Задира</string>
<string name="rodent_iv_spitfire_about">Острый и агрессивный.</string>
<string name="rodent_iv_strangler">Удав</string>
<string name="rodent_iv_strangler_about">Удав: медленно душит, очень по-человечески.</string>
<string name="rodent_iv_alekhine">Алехин</string>
<string name="rodent_iv_alekhine_about">Динамичные атаки и глубокие комбинации.</string>
<string name="rodent_iv_anand">Ананд</string>
<string name="rodent_iv_anand_about">Быстрая, универсальная игра с острыми дебютами.</string>
<string name="rodent_iv_anderssen">Андерсен</string>
<string name="rodent_iv_anderssen_about">Романтик-атакёр XIX века: жертвы.</string>
<string name="rodent_iv_bosboom">Босбум</string>
<string name="rodent_iv_bosboom_about">Необычные дебюты и творческая блиц-игра.</string>
<string name="rodent_iv_botvinnik">Ботвинник</string>
<string name="rodent_iv_botvinnik_about">Научная стратегическая игра на глубокой подготовке.</string>
<string name="rodent_iv_fischer">Фишер</string>
<string name="rodent_iv_fischer_about">Ясная, классическая и точная игра.</string>
<string name="rodent_iv_karpov">Карпов</string>
<string name="rodent_iv_karpov_about">Позиционное давление, профилактика и техника.</string>
<string name="rodent_iv_kasparov">Каспаров</string>
<string name="rodent_iv_kasparov_about">Инициатива и мощная атака.</string>
<string name="rodent_iv_kortchnoi">Корчной</string>
<string name="rodent_iv_kortchnoi_about">Упорный защитник и мастер контратаки.</string>
<string name="rodent_iv_larsen">Ларсен</string>
<string name="rodent_iv_larsen_about">Оригинальный и рискованный, с необычными дебютами.</string>
<string name="rodent_iv_lasker">Ласкер</string>
<string name="rodent_iv_lasker_about">Практичный боец-психолог.</string>
<string name="rodent_iv_marshall">Маршалл</string>
<string name="rodent_iv_marshall_about">Лихой атакёр с гамбитами.</string>
<string name="rodent_iv_morphy">Морфи</string>
<string name="rodent_iv_morphy_about">Быстрое развитие и открытые линии.</string>
<string name="rodent_iv_nimzowitsch">Нимцович</string>
<string name="rodent_iv_nimzowitsch_about">Сковывание, блокада и сверхзащита.</string>
<string name="rodent_iv_petrosian">Петросян</string>
<string name="rodent_iv_petrosian_about">Профилактика и безопасность прежде всего.</string>
<string name="rodent_iv_reti">Рети</string>
<string name="rodent_iv_reti_about">Гиперсовременный: контролирует центр издалека.</string>
<string name="rodent_iv_rubinstein">Рубинштейн</string>
<string name="rodent_iv_rubinstein_about">Классическая позиционная игра, силён в эндшпиле.</string>
<string name="rodent_iv_spassky">Спасский</string>
<string name="rodent_iv_spassky_about">Универсал, в любой позиции как дома.</string>
<string name="rodent_iv_steinitz">Стейниц</string>
<string name="rodent_iv_steinitz_about">Основатель позиционной игры, упрямый защитник.</string>
<string name="rodent_iv_tal">Таль</string>
<string name="rodent_iv_tal_about">Рижский волшебник: жертвы и атака.</string>
<string name="rodent_iv_tarrasch">Тарраш</string>
<string name="rodent_iv_tarrasch_about">Классические правила: пространство, развитие, активные фигуры.</string>
<string name="rodent_iv_topalov">Топалов</string>
<string name="rodent_iv_topalov_about">Агрессивный и динамичный, жертвует качество.</string>
<string name="opp_maia_sub">играет как человек</string>
<string name="opp_rodent_sub">сильный, со стилем</string>
<string name="like_human">Как человек</string>
<string name="maia_no_style">Maia не выбирает стиль: она играет, как люди её рейтинга.</string>
<string name="rodent_measured">Собственный рейтинг Rodent (UCI_Elo): он не равен Эло человека.</string>
<string name="rodent_resigns">Rodent сдаётся</string>
<string name="end_rodent_resigned">Rodent сдался</string>
<string name="rodent_draw_declined">Rodent отказывается от ничьей</string>
<string name="rodent_draw_later">Rodent отказался; снова можно предложить через два его хода</string>
<string name="rodent_position_lost">Его позиция проиграна. Принять победу или доиграть?</string>
<string name="play_button">Играть</string>
<string name="play_button_cd">Играть с компьютером</string>
<string name="strength_n">Сила: %1$s</string>
<string name="pick_title">С кем играть</string>
<string name="pick_intro">Характер — это стиль и дебюты, силу задаёт ползунок.</string>
<string name="pick_players">Великие шахматисты</string>
<string name="pick_characters">Характеры</string>
<string name="pick_change">Изменить</string>
<string name="pick_player_cd">%1$s, великий шахматист</string>
<string name="pick_character_cd">%1$s, характер</string>
<string name="character_cd">Характер: %1$s</string>
<string name="books_ready">Rodent IV и его дебютные книги на телефоне</string>
<string name="books_offer">Дебютные книги Rodent IV: %1$s МБ, скачиваются один раз с github.com</string>
<string name="books_not_needed">С позиции дебютная книга не нужна — Rodent IV играет сразу</string>
<string name="books_without">Без книги</string>
<string name="books_without_cd">Без книги: играть без дебютной книги</string>
<string name="books_notification">Дебютные книги Rodent IV</string>
<string name="books_settings">Rodent IV — дебютные книги</string>
<string name="books_downloaded_mb">скачаны · %1$s МБ</string>
<string name="books_missing_mb">не скачаны · %1$s МБ</string>
<string name="books_deleted">Дебютные книги удалены</string>
<string name="rodent_draw_no_engine">Rodent отвечает на ничью с помощью Stockfish: скачайте его кнопкой «Движок»</string>
<string name="rodent_stopped">Rodent не запустился.</string>
<string name="rodent_restart">Перезапустить</string>
<string name="play_note_from_rodent">Дальше — игра с Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">Rodent остановился во время игры.</string>
<string name="strength_range">%1$s, от %2$s до %3$s</string>
<string name="strength">Сила</string>
<string name="books_delete_cd">Удалить дебютные книги</string>
</resources>

View file

@ -395,7 +395,7 @@
<string name="new_game">Yangi o‘yin</string>
<string name="own_databases">Mening bazalarim</string>
<string name="own_new">+ Yangi baza</string>
<string name="own_empty">Bu yerda siz kiritgan yoki Maia bilan o‘ynagan o‘yinlar bo‘ladi</string>
<string name="own_empty">Bu yerda siz kiritgan yoki kompyuter bilan o‘ynagan o‘yinlar bo‘ladi</string>
<string name="files">Fayllar</string>
<string name="own_default_name">Mening o‘yinlarim</string>
<string name="own_new_title">Yangi baza</string>
@ -478,7 +478,6 @@
<string name="color_white">Oqlar</string>
<string name="color_black">Qoralar</string>
<string name="color_random">Tasodifiy</string>
<string name="play_opponent">Raqib — Maia %1$s</string>
<string name="play_measured">Maia ning o‘z reytingi: u odamning Elo reytingiga teng emas.</string>
<string name="play_download_note">Maia bir marta yuklab olinadi (%1$s MB, huggingface.co dan — mualliflarning o‘z fayli).</string>
<string name="play_download_and_play">Yuklab olish va o‘ynash</string>
@ -495,7 +494,6 @@
<string name="play_maia_resigns">Maia taslim bo‘lmoqda</string>
<string name="play_note_from">Bundan keyin — Maia %1$s bilan o‘yin.</string>
<string name="play_abort">To‘xtatish</string>
<string name="play_with_maia">Maia bilan o‘ynash</string>
<string name="play_your_name">Ismingiz</string>
<string name="play_maia_ready">Maia yuklab olindi</string>
<string name="play_retry">Qayta urinish</string>
@ -510,7 +508,6 @@
<string name="play_saved">✓ Saqlandi</string>
<string name="play_save">Saqlash…</string>
<string name="play_adjourned_sub">siz %1$s · %2$s</string>
<string name="play_from_maia">Shu yerdan Maia bilan davom ettirish…</string>
<string name="play_from_label">%1$s dan keyin</string>
<string name="sound">Ovoz</string>
<string name="undo_menu">Bekor qilish</string>
@ -522,7 +519,7 @@
<string name="start_position">boshlang‘ich pozitsiya</string>
<string name="play_maia_stopped">Maia ishga tushmadi.</string>
<string name="play_maia_reload">Maia’ni qayta yuklab olish</string>
<string name="play_adjourned_q">Maia %1$s bilan to‘xtatilgan o‘yin bor</string>
<string name="play_adjourned_q">%1$s bilan to‘xtatilgan o‘yin bor</string>
<string name="play_continue_it">Davom ettirish</string>
<string name="play_start_new">Yangisini boshlash</string>
<string name="play_adjourned_new_text">Yangi o‘yin uning o‘rnini oladi; o‘ynalgani tugallanmagan holda o‘yinchi bazasiga yoziladi.</string>
@ -536,7 +533,7 @@
<string name="player_written">✓ «%1$s» da, № %2$s ›</string>
<string name="player_kept_unfinished">O‘yin tugallanmagan holda «%1$s» ga yozildi</string>
<string name="player_db_row">o‘zi yoziladi</string>
<string name="record_games">Maia bilan o‘yinlarni o‘yinchi bazasiga yozish</string>
<string name="record_games">Kompyuter bilan o‘yinlarni o‘yinchi bazasiga yozish</string>
<string name="player_line_existing">O‘yinlar «%1$s» ga yoziladi</string>
<string name="player_line_new">O‘yinlar yangi «%1$s» bazasiga yoziladi.</string>
<string name="player_line_noname">Ismsiz o‘yinlar «%1$s» ga tushadi. O‘z bazangiz bo‘lishi uchun ismingizni yozing.</string>
@ -545,6 +542,116 @@
<string name="player_write_failed">«%1$s» ga yozib bo‘lmadi: %2$s</string>
<string name="play_adjourned_replaced">Yangi o‘yin uning o‘rnini oladi.</string>
<string name="last_opened">Oxirgi ochilgan</string>
<string name="play_adjourned_title">Maia %1$s bilan o‘yin</string>
<string name="play_adjourned_title">%1$s bilan o‘yin</string>
<string name="play_move_n">%1$d-yurish</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Avval hujum qiladi, keyin donalar faolligi uchun o‘ynaydi.</string>
<string name="rodent_iv_cloe">Kloe</string>
<string name="rodent_iv_cloe_about">Yopiq pozitsiyalarni yaxshi ko‘radi.</string>
<string name="rodent_iv_deborah">Debora</string>
<string name="rodent_iv_deborah_about">Yaxshi himoyalanadi va filllarini yaxshi ko‘radi.</string>
<string name="rodent_iv_defender">Himoyachi</string>
<string name="rodent_iv_defender_about">Mustahkam va ehtiyotkor; duranga rozi.</string>
<string name="rodent_iv_dynamic">Dinamik</string>
<string name="rodent_iv_dynamic_about">Hujum qiladi, fillarni yaxshi ko‘radi, ba’zan qurbon qiladi.</string>
<string name="rodent_iv_grumpy">G‘udranuvchi</string>
<string name="rodent_iv_grumpy_about">Hujum va siqish; yopiq pozitsiyalarni yoqtiradi, durangdan qochadi.</string>
<string name="rodent_iv_partisan">Partizan</string>
<string name="rodent_iv_partisan_about">Sokin, sezilmas debyutlardan keyin hujum qiladi.</string>
<string name="rodent_iv_pawnsacker">Gambitchi</string>
<string name="rodent_iv_pawnsacker_about">Muvozanatli, lekin piyodalarni osonroq beradi.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Piyodalar, himoya va siqish.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">Materialist, o‘rtacha hujumchi.</string>
<string name="rodent_iv_simple">Oddiy</string>
<string name="rodent_iv_simple_about">Eng «kompyuterona»: oddiy, to‘g‘ri shaxmat.</string>
<string name="rodent_iv_spitfire">Jo‘shqin</string>
<string name="rodent_iv_spitfire_about">O‘tkir va tajovuzkor.</string>
<string name="rodent_iv_strangler">Bo‘g‘uvchi</string>
<string name="rodent_iv_strangler_about">Bo‘g‘ma ilon: sekin siqadi, juda insoniy.</string>
<string name="rodent_iv_alekhine">Alyoxin</string>
<string name="rodent_iv_alekhine_about">Dinamik hujumlar va chuqur kombinatsiyalar.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Tez, universal o‘yin, o‘tkir debyutlar bilan.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">XIX asrning romantik hujumchisi: qurbonlar.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Noodatiy debyutlar va ijodiy blits.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Chuqur tayyorgarlikka asoslangan ilmiy, strategik o‘yin.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Aniq, klassik va puxta.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Pozitsion bosim, profilaktika va texnika.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Tashabbus va kuchli hujum.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">Qat’iyatli himoyachi va qarshi hujumchi.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">O‘ziga xos va tavakkalchi, noodatiy debyutlar bilan.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">Amaliy, psixolog kurashchi.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">Gambitlar bilan dadil hujumchi.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Tez rivojlanish va ochiq chiziqlar.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Siqish, blokada va ortiqcha himoya.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Profilaktika va xavfsizlik birinchi.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Gipermodern: markazni uzoqdan nazorat qiladi.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Klassik pozitsion o‘yin, endshpilda kuchli.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">Universal o‘yinchi, har qanday pozitsiyada o‘zini uydagidek his qiladi.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">Pozitsion o‘yin asoschisi, qaysar himoyachi.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">Rigalik sehrgar: qurbonlar va hujum.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Klassik qoidalar: makon, rivojlanish, faol donalar.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Tajovuzkor va dinamik, sifatni qurbon qiladi.</string>
<string name="opp_maia_sub">odamdek o‘ynaydi</string>
<string name="opp_rodent_sub">kuchli, uslubli</string>
<string name="like_human">Odamdek</string>
<string name="maia_no_style">Maia uslub tanlamaydi: u o‘z reytingidagi odamlardek o‘ynaydi.</string>
<string name="rodent_measured">Rodent ning o‘z reytingi (UCI_Elo): u odamning Elo reytingiga teng emas.</string>
<string name="rodent_resigns">Rodent taslim bo‘lmoqda</string>
<string name="end_rodent_resigned">Rodent taslim bo‘ldi</string>
<string name="rodent_draw_declined">Rodent durangdan bosh tortadi</string>
<string name="rodent_draw_later">Rodent rad etdi; uning ikki yurishidan keyin yana taklif qiling</string>
<string name="rodent_position_lost">Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi?</string>
<string name="play_button">O‘ynash</string>
<string name="play_button_cd">Kompyuter bilan o‘ynash</string>
<string name="strength_n">Kuch: %1$s</string>
<string name="pick_title">Kim bilan o‘ynash</string>
<string name="pick_intro">Xarakter — bu uslub va debyutlar, kuchni esa slayder belgilaydi.</string>
<string name="pick_players">Buyuk shaxmatchilar</string>
<string name="pick_characters">Xarakterlar</string>
<string name="pick_change">O‘zgartirish</string>
<string name="pick_player_cd">%1$s, buyuk shaxmatchi</string>
<string name="pick_character_cd">%1$s, xarakter</string>
<string name="character_cd">Xarakter: %1$s</string>
<string name="books_ready">Rodent IV va uning debyut kitoblari telefonda</string>
<string name="books_offer">Rodent IV debyut kitoblari: %1$s MB, github.com dan bir marta</string>
<string name="books_not_needed">Pozitsiyadan o‘ynashda debyut kitobi kerak emas — Rodent IV darhol o‘ynaydi</string>
<string name="books_without">Kitobsiz</string>
<string name="books_without_cd">Kitobsiz: debyut kitobisiz o‘ynash</string>
<string name="books_notification">Rodent IV debyut kitoblari</string>
<string name="books_settings">Rodent IV — debyut kitoblari</string>
<string name="books_downloaded_mb">yuklab olingan · %1$s MB</string>
<string name="books_missing_mb">yuklab olinmagan · %1$s MB</string>
<string name="books_deleted">Debyut kitoblari o‘chirildi</string>
<string name="rodent_draw_no_engine">Rodent durangga Stockfish bilan javob beradi: uni «Dvigatel» tugmasi bilan yuklab oling</string>
<string name="rodent_stopped">Rodent ishga tushmadi.</string>
<string name="rodent_restart">Qayta ishga tushirish</string>
<string name="play_note_from_rodent">Bundan keyin — Rodent IV %1$s · %2$s bilan o‘yin.</string>
<string name="rodent_stopped_playing">Rodent o‘yin paytida to‘xtadi.</string>
<string name="strength_range">%1$s, %2$s dan %3$s gacha</string>
<string name="strength">Kuch</string>
<string name="books_delete_cd">Debyut kitoblarini o‘chirish</string>
</resources>

View file

@ -400,7 +400,7 @@
<string name="new_game">New game</string>
<string name="own_databases">My databases</string>
<string name="own_new">+ New database</string>
<string name="own_empty">Games you enter or play against Maia will be here</string>
<string name="own_empty">Games you enter or play against the computer will be here</string>
<string name="files">Files</string>
<string name="own_default_name">My games</string>
<string name="own_new_title">New database</string>
@ -483,7 +483,6 @@
<string name="color_white">White</string>
<string name="color_black">Black</string>
<string name="color_random">Random</string>
<string name="play_opponent">Opponent — Maia %1$s</string>
<string name="play_measured">Maia’s own rating: it does not match a person’s Elo.</string>
<string name="play_download_note">Maia is downloaded once (%1$s MB, from huggingface.co, the authors\' own file).</string>
<string name="play_download_and_play">Download and play</string>
@ -500,7 +499,6 @@
<string name="play_maia_resigns">Maia resigns</string>
<string name="play_note_from">From here on, a game against Maia %1$s.</string>
<string name="play_abort">Abort</string>
<string name="play_with_maia">Play with Maia</string>
<string name="play_your_name">Your name</string>
<string name="play_maia_ready">Maia is downloaded</string>
<string name="play_retry">Try again</string>
@ -515,7 +513,6 @@
<string name="play_saved">✓ Saved</string>
<string name="play_save">Save…</string>
<string name="play_adjourned_sub">you play %1$s · %2$s</string>
<string name="play_from_maia">Play on from here with Maia…</string>
<string name="play_from_label">After %1$s</string>
<string name="sound">Sound</string>
<string name="undo_menu">Undo</string>
@ -527,7 +524,7 @@
<string name="start_position">the starting position</string>
<string name="play_maia_stopped">Maia did not start.</string>
<string name="play_maia_reload">Download Maia again</string>
<string name="play_adjourned_q">There is a game put aside against Maia %1$s</string>
<string name="play_adjourned_q">There is a game put aside against %1$s</string>
<string name="play_continue_it">Continue it</string>
<string name="play_start_new">Start a new one</string>
<string name="play_adjourned_new_text">A new game replaces it; what was played goes into the player’s database, unfinished.</string>
@ -535,13 +532,13 @@
<string name="end_agreement">by agreement</string>
<string name="play_draw_declined">Maia declines the draw</string>
<string name="play_draw_later">Maia declined; offer again after two of her moves</string>
<string name="play_draw_no_engine">Maia answers a draw offer with Stockfish: download it in the game screen («Engine»)</string>
<string name="play_draw_no_engine">Maia answers a draw offer with Stockfish: download it in the game screen (“Engine”)</string>
<string name="player_db_name">%1$s — games against the computer</string>
<string name="player_db_shared">Games against the computer</string>
<string name="player_written">✓ In “%1$s”, No. %2$s ›</string>
<string name="player_kept_unfinished">Game written to “%1$s” unfinished</string>
<string name="player_db_row">recorded automatically</string>
<string name="record_games">Write games against Maia to the player’s database</string>
<string name="record_games">Write games against the computer to the player’s database</string>
<string name="player_line_existing">Games are written to “%1$s”</string>
<string name="player_line_new">Games will be written to a new database “%1$s”.</string>
<string name="player_line_noname">Without a name games go to “%1$s”. Enter a name to have a database of your own.</string>
@ -550,6 +547,116 @@
<string name="player_write_failed">Could not write to “%1$s”: %2$s</string>
<string name="play_adjourned_replaced">A new game replaces it.</string>
<string name="last_opened">Last opened</string>
<string name="play_adjourned_title">Game against Maia %1$s</string>
<string name="play_adjourned_title">Game against %1$s</string>
<string name="play_move_n">move %1$d</string>
<!-- Rodent IV on the phone (android-rodent.md §9); the characters and the desktop's sentences come from apps/desktop/src/i18n.rs. -->
<string name="rodent_iv_amanda">Amanda</string>
<string name="rodent_iv_amanda_about">Attacks first, then plays for active pieces.</string>
<string name="rodent_iv_cloe">Cloe</string>
<string name="rodent_iv_cloe_about">Likes closed positions.</string>
<string name="rodent_iv_deborah">Deborah</string>
<string name="rodent_iv_deborah_about">Defends well and likes her bishops.</string>
<string name="rodent_iv_defender">Defender</string>
<string name="rodent_iv_defender_about">Solid and careful; content with a draw.</string>
<string name="rodent_iv_dynamic">Dynamic</string>
<string name="rodent_iv_dynamic_about">Attacks, likes bishops, sacrifices now and then.</string>
<string name="rodent_iv_grumpy">Grumpy</string>
<string name="rodent_iv_grumpy_about">Attack and restraint; likes blocked positions, avoids draws.</string>
<string name="rodent_iv_partisan">Partisan</string>
<string name="rodent_iv_partisan_about">Attacks after quiet, stealthy openings.</string>
<string name="rodent_iv_pawnsacker">Pawnsacker</string>
<string name="rodent_iv_pawnsacker_about">Balanced, but gives up pawns more readily.</string>
<string name="rodent_iv_pedrita">Pedrita</string>
<string name="rodent_iv_pedrita_about">Pawns, defence and restraint.</string>
<string name="rodent_iv_preston">Preston</string>
<string name="rodent_iv_preston_about">A materialistic, moderate attacker.</string>
<string name="rodent_iv_simple">Simple</string>
<string name="rodent_iv_simple_about">The most computer-like: plain, sound chess.</string>
<string name="rodent_iv_spitfire">Spitfire</string>
<string name="rodent_iv_spitfire_about">Sharp and aggressive.</string>
<string name="rodent_iv_strangler">Strangler</string>
<string name="rodent_iv_strangler_about">A boa constrictor: squeezes slowly, very human-like.</string>
<string name="rodent_iv_alekhine">Alekhine</string>
<string name="rodent_iv_alekhine_about">Dynamic attacks and deep combinations.</string>
<string name="rodent_iv_anand">Anand</string>
<string name="rodent_iv_anand_about">Quick, universal play with sharp openings.</string>
<string name="rodent_iv_anderssen">Anderssen</string>
<string name="rodent_iv_anderssen_about">A romantic attacker of the 19th century: sacrifices.</string>
<string name="rodent_iv_bosboom">Bosboom</string>
<string name="rodent_iv_bosboom_about">Offbeat openings and creative blitz play.</string>
<string name="rodent_iv_botvinnik">Botvinnik</string>
<string name="rodent_iv_botvinnik_about">Scientific, strategic play from deep preparation.</string>
<string name="rodent_iv_fischer">Fischer</string>
<string name="rodent_iv_fischer_about">Clear, classical and precise.</string>
<string name="rodent_iv_karpov">Karpov</string>
<string name="rodent_iv_karpov_about">Positional squeeze, prophylaxis and technique.</string>
<string name="rodent_iv_kasparov">Kasparov</string>
<string name="rodent_iv_kasparov_about">Initiative and powerful attack.</string>
<string name="rodent_iv_kortchnoi">Kortchnoi</string>
<string name="rodent_iv_kortchnoi_about">A tenacious defender and counter-attacker.</string>
<string name="rodent_iv_larsen">Larsen</string>
<string name="rodent_iv_larsen_about">Original and risky, with offbeat openings.</string>
<string name="rodent_iv_lasker">Lasker</string>
<string name="rodent_iv_lasker_about">A practical, psychological fighter.</string>
<string name="rodent_iv_marshall">Marshall</string>
<string name="rodent_iv_marshall_about">A swashbuckling attacker with gambits.</string>
<string name="rodent_iv_morphy">Morphy</string>
<string name="rodent_iv_morphy_about">Quick development and open lines.</string>
<string name="rodent_iv_nimzowitsch">Nimzowitsch</string>
<string name="rodent_iv_nimzowitsch_about">Restraint, blockade and overprotection.</string>
<string name="rodent_iv_petrosian">Petrosian</string>
<string name="rodent_iv_petrosian_about">Prophylaxis and safety first.</string>
<string name="rodent_iv_reti">Reti</string>
<string name="rodent_iv_reti_about">Hypermodern: controls the centre from afar.</string>
<string name="rodent_iv_rubinstein">Rubinstein</string>
<string name="rodent_iv_rubinstein_about">Classical positional play, great in endgames.</string>
<string name="rodent_iv_spassky">Spassky</string>
<string name="rodent_iv_spassky_about">A universal player, at home in any position.</string>
<string name="rodent_iv_steinitz">Steinitz</string>
<string name="rodent_iv_steinitz_about">The founder of positional play, a stubborn defender.</string>
<string name="rodent_iv_tal">Tal</string>
<string name="rodent_iv_tal_about">The magician from Riga: sacrifices and attack.</string>
<string name="rodent_iv_tarrasch">Tarrasch</string>
<string name="rodent_iv_tarrasch_about">Classical rules: space, development, active pieces.</string>
<string name="rodent_iv_topalov">Topalov</string>
<string name="rodent_iv_topalov_about">Aggressive and dynamic, sacrifices the exchange.</string>
<string name="opp_maia_sub">plays like a human</string>
<string name="opp_rodent_sub">strong, with a style</string>
<string name="like_human">Like a human</string>
<string name="maia_no_style">Maia does not pick a style: she plays like people of her rating.</string>
<string name="rodent_measured">Rodent’s own rating (UCI_Elo): it does not match a person’s Elo.</string>
<string name="rodent_resigns">Rodent resigns</string>
<string name="end_rodent_resigned">Rodent resigned</string>
<string name="rodent_draw_declined">Rodent declines the draw</string>
<string name="rodent_draw_later">Rodent declined; offer again after two of its moves</string>
<string name="rodent_position_lost">Its position is lost. Accept the win, or play to the end?</string>
<string name="play_button">Play</string>
<string name="play_button_cd">Play the computer</string>
<string name="strength_n">Strength: %1$s</string>
<string name="pick_title">Who to play</string>
<string name="pick_intro">A character is a style and openings; the slider sets the strength.</string>
<string name="pick_players">Great players</string>
<string name="pick_characters">Characters</string>
<string name="pick_change">Change</string>
<string name="pick_player_cd">%1$s, great player</string>
<string name="pick_character_cd">%1$s, character</string>
<string name="character_cd">Character: %1$s</string>
<string name="books_ready">Rodent IV and its opening books are on the phone</string>
<string name="books_offer">Rodent IV opening books: %1$s MB, downloaded once from github.com</string>
<string name="books_not_needed">From a position no opening book is needed: Rodent IV plays at once</string>
<string name="books_without">No book</string>
<string name="books_without_cd">No book: play without the opening book</string>
<string name="books_notification">Rodent IV opening books</string>
<string name="books_settings">Rodent IV — opening books</string>
<string name="books_downloaded_mb">downloaded · %1$s MB</string>
<string name="books_missing_mb">not downloaded · %1$s MB</string>
<string name="books_deleted">Opening books deleted</string>
<string name="rodent_draw_no_engine">Rodent answers a draw offer with Stockfish: download it in the game screen (“Engine”)</string>
<string name="rodent_stopped">Rodent did not start.</string>
<string name="rodent_restart">Restart</string>
<string name="play_note_from_rodent">From here on, a game against Rodent IV %1$s · %2$s.</string>
<string name="rodent_stopped_playing">Rodent stopped during the game.</string>
<string name="strength_range">%1$s, from %2$s to %3$s</string>
<string name="strength">Strength</string>
<string name="books_delete_cd">Delete the opening books</string>
</resources>

77
androidApp/scripts/rodent4.sh Executable file
View file

@ -0,0 +1,77 @@
#!/usr/bin/env bash
# Builds Rodent IV (github.com/nescitus/rodent-iv, GPL-3.0) for Android from the authors'
# sources at the commit the desktop build uses (.github/workflows/rodent-iv.yml), with the
# same fix (packaging/rodent-iv/home-dir.patch), and two more: think-thread.patch (a
# dangling reference that clang builds trip over) and android.patch (bionic has no
# wordexp); takes its personalities.
#
# scripts/rodent4.sh OUT_DIR
# OUT_DIR/jniLibs/arm64-v8a/librodent4.so, OUT_DIR/jniLibs/x86_64/librodent4.so
# OUT_DIR/home/personalities/* (basic.ini and the personality files)
# OUT_DIR/source/LICENSE, README.md, COPYRIGHT, books/<folder>/readme.txt (the books'
# credits, the authors' #readme.txt)
#
# The executable goes into the APK as a "library", the only place Android 10+ lets an
# app execute a file from (docs/research/android-stack.md §5). The engine finds its
# personalities and books in the folder named by RODENT4HOME: NDK clang defines
# __ANDROID__ but not ANDROID, so the authors' /sdcard/Rodent4 branch is not compiled
# (android.patch keys only the missing wordexp on __ANDROID__).
# The books are not here: the app downloads them. libc++ is linked statically.
# The source is cached in ~/.cache/chesspenguin-android and checked against its SHA-256.
# Needs ANDROID_NDK_HOME (NDK r27c or later).
set -euo pipefail
commit="e8d84c8c8c189a1cf4eb27c578fc573af3b916d2"
source_sha256="db372b48a8ccf22d9bfbe3e5454cbbccb81dadca0120cbc0abaee2a81a0cb3fe"
api=31
here="$(cd "$(dirname "$0")" && pwd)"
patches="${here}/../../packaging/rodent-iv"
out="$(realpath -m "${1:?usage: $0 OUT_DIR}")"
ndk="${ANDROID_NDK_HOME:?set ANDROID_NDK_HOME}"
cache="${XDG_CACHE_HOME:-$HOME/.cache}/chesspenguin-android"
mkdir -p "${cache}" "${out}"
file="rodent-iv-${commit}.tar.gz"
if ! { [[ -f "${cache}/${file}" ]] \
&& echo "${source_sha256} ${cache}/${file}" | sha256sum -c --quiet - 2>/dev/null; }; then
curl -fsSL --retry 3 --max-time 900 -o "${cache}/${file}.part" \
"https://github.com/nescitus/rodent-iv/archive/${commit}.tar.gz"
if ! echo "${source_sha256} ${cache}/${file}.part" | sha256sum -c --quiet -; then
rm -f "${cache}/${file}.part"
echo "rodent4.sh: the source does not match its SHA-256" >&2
exit 1
fi
mv "${cache}/${file}.part" "${cache}/${file}"
fi
work="$(mktemp -d)"
trap 'rm -rf "${work}"' EXIT
tar -xzf "${cache}/${file}" -C "${work}"
root="${work}/rodent-iv-${commit}"
patch -s -d "${root}" -p1 < "${patches}/home-dir.patch"
patch -s -d "${root}" -p1 < "${patches}/think-thread.patch"
patch -s -d "${root}" -p1 < "${patches}/android.patch"
bin="${ndk}/toolchains/llvm/prebuilt/linux-x86_64/bin"
build() { # abi target
"${bin}/$2${api}-clang++" -O3 -w -pipe -DNDEBUG -fno-rtti -finline-functions -std=c++14 \
-static-libstdc++ "${root}"/sources/src/*.cpp -o "${work}/rodent4-$1" -lm
mkdir -p "${out}/jniLibs/$1"
"${bin}/llvm-strip" -o "${out}/jniLibs/$1/librodent4.so" "${work}/rodent4-$1"
}
build arm64-v8a aarch64-linux-android
build x86_64 x86_64-linux-android
rm -rf "${out}/home" "${out}/source"
mkdir -p "${out}/home" "${out}/source"
cp -r "${root}/personalities" "${out}/home/personalities"
cp "${root}/LICENSE" "${root}/README.md" "${out}/source/"
# The authors are named in the sources' headers; the repository has no AUTHORS file.
sed -n '/^\/\*/,/^\*\//p' "${root}/sources/src/main.cpp" > "${out}/source/COPYRIGHT"
# The books are downloaded by the app; their credits come with the licence.
for credits in $(cd "${root}" && find books -name '#readme.txt'); do
mkdir -p "${out}/source/$(dirname "${credits}")"
cp "${root}/${credits}" "${out}/source/$(dirname "${credits}")/readme.txt"
done
echo "Rodent IV (${commit:0:8}) for Android -> ${out}"

View file

@ -2601,7 +2601,7 @@ impl GameView {
"Maia did not start: {e}"
}
crate::play::Engine::Rodent(g) => {
g.remove();
crate::play::RodentFiles::remove(g);
"Rodent did not start: {e}"
}
};

View file

@ -28,7 +28,6 @@ mod player_games;
mod reference;
mod review;
mod rodent4_download;
mod rodent4_files;
mod rodent_download;
mod san;
mod settings;

View file

@ -11,7 +11,10 @@ use serde::{Deserialize, Serialize};
use crate::i18n::tr;
use crate::maia_download::Published;
pub use ::play::{Ending, HOPELESS_TURNS, Judge, ending, hopeless, pause, random_unit};
pub use ::play::rodent::{Gen, STYLES, Style, style};
pub use ::play::{
Ending, HOPELESS_TURNS, Judge, MAIA_MAX, MAIA_MIN, ending, hopeless, pause, random_unit,
};
use maia::strength::Model;
// ----- time controls --------------------------------------------------------------------
@ -153,75 +156,46 @@ pub enum Rival {
Rodent,
}
/// Rodent's styles: its personality files, the personality's name (for PGN), what the
/// style is called and does (in the app's language). The players' imitations come last
/// (`player`).
pub struct Style {
pub id: &'static str,
pub name: &'static str,
title: &'static str,
pub about: &'static str,
pub player: bool,
/// 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,
/// Downloading each Rodent (the engines' tables are the shared crate's, `play::rodent`).
pub trait RodentFiles {
fn available(self) -> bool;
fn installed(self) -> Option<std::path::PathBuf>;
fn size_mb(self) -> u64;
fn start(self, ctx: &egui::Context) -> crate::engine_download::Download;
/// A file that does not start goes: the dialog offers the download again.
fn remove(self);
}
/// 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 {
impl RodentFiles for Gen {
fn available(self) -> bool {
match self {
Gen::V => crate::rodent_download::available(),
Gen::IV => crate::rodent4_download::available(),
}
}
pub fn installed(self) -> Option<std::path::PathBuf> {
fn installed(self) -> Option<std::path::PathBuf> {
match self {
Gen::V => crate::rodent_download::installed(),
Gen::IV => crate::rodent4_download::installed(),
}
}
pub fn size_mb(self) -> u64 {
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 {
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) {
fn remove(self) {
let _ = match self {
Gen::V => crate::rodent_download::remove(),
Gen::IV => crate::rodent4_download::remove(),
@ -229,412 +203,18 @@ impl Gen {
}
}
impl Style {
/// The style's name to translate («Attacking»).
pub fn title(&self) -> &'static str {
self.title
}
}
pub const STYLES: &[Style] = &[
Style {
id: "rodent",
name: "Rodent",
title: "Balanced",
about: "Even, all-round play with no bias.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "ampere",
name: "Ampere",
title: "Attacking",
about: "Active pieces and attack, sound pawn structure.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "chaotic",
name: "Chaotic",
title: "Chaotic",
about: "Aggressive, tricky openings, careless with pawns.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "nimzoid",
name: "Nimzoid",
title: "Restricting",
about: "Closed positions, cramping the opponent, old openings.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "hector",
name: "Hector",
title: "Classical",
about: "Hand-written evaluation, no neural network.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "tal_hybrid",
name: "Tal",
title: "Tal",
about: "Attacking style tuned on Tal's games.",
player: true,
rodent: Gen::V,
personality: "",
},
Style {
id: "tal_nnue",
name: "Tal NNUE",
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, and so
// are Rodent IV's characters (their titles are their names, translated).
if st.player || st.id == "rodent" || st.title == st.name {
if st.player || st.id == "rodent" || st.title() == st.name {
title.to_owned()
} else {
format!("{title} — {}", st.name)
}
}
/// The style of this id (the default one for an unknown id).
pub fn style(id: &str) -> &'static Style {
STYLES.iter().find(|s| s.id == id).unwrap_or(&STYLES[0])
}
impl Default for PlayPrefs {
fn default() -> Self {
PlayPrefs {
@ -654,16 +234,7 @@ impl Default for PlayPrefs {
// Each engine on its own scale, as its authors give it (the owner's decision, after the
// measurements of docs/research/maia-strength.md and rodent.md): these are not a
// person's Elo, and the dialog says so.
/// Maia's ratings: what her network was trained on.
pub const MAIA_MIN: u32 = 600;
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;
// person's Elo, and the dialog says so. The scales are the shared crate's (`play`).
/// The strengths `rival` plays (Rodent's by the engine of the style chosen).
pub fn range(rival: Rival, style_id: &str) -> (u32, u32) {
@ -874,9 +445,9 @@ pub fn clk_of(comment: &str) -> Option<Duration> {
Some(Duration::from_secs(secs))
}
// ----- Maia's moves -------------------------------------------------------------------
// ----- the opponent's moves -------------------------------------------------------------
/// A request for a move: the positions up to now, the ratings, the pause.
/// A request for Maia's move: the positions up to now, the ratings, the pause.
struct Request {
generation: u64,
positions: Vec<Chess>,
@ -884,18 +455,26 @@ struct Request {
oppo_elo: u32,
temperature: f32,
pause: Duration,
/// The game for a UCI engine (Rodent): its start and moves.
engine_pos: Option<uci::EnginePosition>,
}
/// The engine in a thread of its own: loads Maia once, answers requests after a pause.
/// An answer for an older generation (after a take-back, a resignation) is dropped.
/// What computes the opponent's moves.
enum Worker {
/// Maia in a thread of her own; her error, if loading failed.
Maia {
tx: Sender<Request>,
rx: Receiver<(u64, Option<Move>, Duration)>,
generation: u64,
error: Arc<Mutex<Option<String>>>,
},
/// Rodent, a UCI engine (the shared crate's player).
Rodent(::play::rodent::RodentPlayer),
}
/// The engine in a thread of its own: loads Maia once (or starts Rodent), answers
/// requests after a pause. An answer for an older request (after a take-back, a
/// resignation) is dropped.
pub struct Opponent {
tx: Sender<Request>,
rx: Receiver<(u64, Option<Move>, Duration)>,
generation: u64,
/// Loading failed: why (shown to the user).
pub error: Arc<Mutex<Option<String>>>,
worker: Worker,
pub thinking: bool,
}
@ -939,10 +518,12 @@ impl Opponent {
}
});
Opponent {
tx,
rx,
generation: 0,
error,
worker: Worker::Maia {
tx,
rx,
generation: 0,
error,
},
thinking: false,
}
}
@ -957,134 +538,59 @@ impl Opponent {
oppo_elo: u32,
pause: Duration,
) {
self.generation += 1;
self.thinking = true;
let _ = self.tx.send(Request {
generation: self.generation,
positions,
self_elo,
oppo_elo,
temperature,
pause,
engine_pos,
});
match &mut self.worker {
Worker::Maia { tx, generation, .. } => {
*generation += 1;
let _ = tx.send(Request {
generation: *generation,
positions,
self_elo,
oppo_elo,
temperature,
pause,
});
}
Worker::Rodent(player) => {
if let (Some(pos), Some(now)) = (engine_pos, positions.last().cloned()) {
player.ask(pos, now, pause);
}
}
}
}
/// Rodent V (`exe` in its folder) playing in `style` at `uci_elo` (none: full
/// strength), with its opening book. It thinks during the pause (a game's own clock
/// is not its business: Maia's pause rule paces it), and answers after it.
/// Rodent (`exe` in its folder) playing in `style` at `uci_elo` (none: full
/// strength), with its opening book.
pub fn start_rodent(
exe: std::path::PathBuf,
style: String,
uci_elo: Option<u32>,
ctx: &egui::Context,
) -> Opponent {
let (tx, req_rx) = channel::<Request>();
let (ans_tx, rx) = channel();
let error = Arc::new(Mutex::new(None));
let err = error.clone();
let config = uci::EngineConfig {
working_dir: exe.parent().map(|d| d.to_path_buf()),
..uci::EngineConfig::new(&exe)
};
let ctx = ctx.clone();
let _ = std::thread::Builder::new()
.name("rodent".into())
.spawn(move || {
let fail = |e: String| {
if let Ok(mut g) = err.lock() {
*g = Some(e);
}
ctx.request_repaint();
};
let config = uci::EngineConfig {
working_dir: exe.parent().map(|d| d.to_path_buf()),
..uci::EngineConfig::new(&exe)
};
let engine = match uci::Engine::spawn_with(config, Box::new(|| {})) {
Ok(e) => e,
Err(e) => return fail(start_failure(&e.to_string())),
};
// 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()));
}
let ready = engine.set_threads(1).and_then(|()| engine.set_hash_mb(64));
if let Err(e) = ready {
return fail(start_failure(&e.to_string()));
}
for (name, value) in &setup {
if let Err(e) = engine.set_option(name, Some(value)) {
return fail(start_failure(&e.to_string()));
}
}
let _ = engine.new_game();
while let Ok(mut r) = req_rx.recv() {
while let Ok(newer) = req_rx.try_recv() {
r = newer;
}
let (Some(pos), Some(now)) =
(r.engine_pos.clone(), r.positions.last().cloned())
else {
continue;
};
let started = Instant::now();
let id = uci::SearchId(r.generation);
// Its own limit (from UCI_Elo) ends the search early; at full strength
// it thinks for the pause.
let think = r.pause.max(Duration::from_millis(300));
if let Err(e) = engine.search(pos, id, uci::SearchLimits::MoveTime(think)) {
return fail(e.to_string());
}
let best = loop {
match engine.recv_timeout(Duration::from_millis(200)) {
Some(uci::EngineEvent::BestMove {
search_id, best: b, ..
}) if search_id == id => {
break b;
}
Some(uci::EngineEvent::Terminated(_)) => {
return fail(tr("it stopped while playing").to_owned());
}
_ if started.elapsed() > think + Duration::from_secs(20) => {
let _ = engine.stop();
}
_ => {}
}
};
let m = best
.and_then(|b| b.parse::<shakmaty::uci::UciMove>().ok())
.and_then(|u| u.to_move(&now).ok());
std::thread::sleep(r.pause.saturating_sub(started.elapsed()));
let spent = r.pause.max(started.elapsed());
if ans_tx.send((r.generation, m, spent)).is_err() {
engine.quit();
return;
}
ctx.request_repaint();
}
engine.quit();
});
let player = ::play::rodent::RodentPlayer::start(
config,
&style,
uci_elo,
true,
Box::new(move || ctx.request_repaint()),
);
Opponent {
tx,
rx,
generation: 0,
error,
worker: Worker::Rodent(player),
thinking: false,
}
}
/// Forgets what was asked (its answer will be dropped).
pub fn forget(&mut self) {
self.generation += 1;
match &mut self.worker {
Worker::Maia { generation, .. } => *generation += 1,
Worker::Rodent(player) => player.forget(),
}
self.thinking = false;
}
@ -1092,17 +598,35 @@ impl Opponent {
/// the computing when longer).
pub fn answer(&mut self) -> Option<(Move, Duration)> {
let mut out = None;
while let Ok((g, m, pause)) = self.rx.try_recv() {
if g == self.generation {
self.thinking = false;
out = m.map(|m| (m, pause));
match &mut self.worker {
Worker::Maia { rx, generation, .. } => {
while let Ok((g, m, pause)) = rx.try_recv() {
if g == *generation {
self.thinking = false;
out = m.map(|m| (m, pause));
}
}
}
Worker::Rodent(player) => {
if let Some((m, pause)) = player.answer() {
self.thinking = false;
out = m.map(|m| (m, pause));
}
}
}
out
}
pub fn failed(&self) -> Option<String> {
self.error.lock().ok().and_then(|g| g.clone())
use ::play::rodent::Failure;
match &self.worker {
Worker::Maia { error, .. } => error.lock().ok().and_then(|g| g.clone()),
Worker::Rodent(player) => player.failure().map(|f| match f {
Failure::Start(e) => start_failure(&e),
Failure::Stopped => tr("it stopped while playing").to_owned(),
Failure::Search(e) => e,
}),
}
}
}
@ -1468,11 +992,9 @@ pub fn debug_rival() -> (Rival, String) {
/// «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!("{} {strength}", st.rodent.name()),
Rival::Rodent => format!("{} {strength} ({})", st.rodent.name(), st.name),
Rival::Rodent => ::play::rodent::name(strength, style_id),
}
}

View file

@ -9,7 +9,7 @@ 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};
use ::play::rodent::{BOOK_NAMES, FILES, file_url};
/// The release of our builds.
const TAG: &str = "rodent-iv-0.33";
@ -97,23 +97,6 @@ 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<PathBuf, Failure> {
let bin = binary().ok_or(Failure::Unsupported)?;
let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?;
@ -154,11 +137,7 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result<PathBuf, Failure>
size,
zip: false,
};
let url = format!(
"https://raw.githubusercontent.com/nescitus/rodent-iv/{COMMIT}/{}",
url_path(path)
);
fetch(&url, &dest, &asset, &step(base), cancel)?;
fetch(&file_url(path), &dest, &asset, &step(base), cancel)?;
base += size;
}
report(Stage::Unpacking);
@ -178,22 +157,3 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result<PathBuf, Failure>
}
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}");
}
}
}

View file

@ -26,7 +26,9 @@ pub use online::{
OnlineProblem, OnlineTarget, Site,
};
pub use play::{
GameEnding, MaiaPlayer, ResignJudge, hopeless_turns, maia_game_tags, maia_pause_ms, maia_range,
GameEnding, MaiaPlayer, ResignJudge, Rival, RodentBook, RodentFailure, RodentPlayer,
RodentStyle, computer_game_tags, hopeless_turns, maia_range, move_pause_ms, rival_label,
rival_name, rodent_book_pack, rodent_range, rodent_styles, rodent_version,
};
pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview};
pub use session::{Edited, GameSession, own_create, own_remove, own_save};

View file

@ -1,6 +1,7 @@
//! A game against Maia on the phone (docs/design/android-play.md §31): the small model
//! (5M) chooses her moves at a strength on the Lichess blitz scale, by the same tables
//! and rule as on the desktop (`maia::strength`). No clocks on the phone.
//! A game against the computer on the phone (docs/design/android-play.md §31,
//! android-rodent.md): Maia's small model (5M) chooses her moves at a strength of her
//! own scale, by the same tables and rule as on the desktop (`maia::strength`); Rodent IV
//! plays in a style, as on the desktop (`play::rodent`). No clocks on the phone.
use std::sync::Arc;
@ -55,20 +56,54 @@ impl GameSession {
}
}
/// How long Maia "thinks" before her move `ply` of an untimed game (milliseconds):
/// as a person would, quicker with one legal move.
/// How long the computer "thinks" before its move `ply` of an untimed game
/// (milliseconds): as a person would, quicker with one legal move.
#[uniffi::export]
pub fn maia_pause_ms(ply: u32, only_move: bool) -> u64 {
pub fn move_pause_ms(ply: u32, only_move: bool) -> u64 {
::play::pause(None, ply as usize, only_move).as_millis() as u64
}
/// The tags of a game against Maia on the phone (no clocks): `event` in the app's
/// language; the user plays White when `user_white`.
/// Who plays against the user.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum Rival {
Maia,
/// Rodent IV in a style of its list (`iv_tal`…).
Rodent {
style_id: String,
},
}
/// The opponent as the game's record names it: «Maia 1500», «Rodent IV 1800 (Tal)».
#[uniffi::export]
pub fn maia_game_tags(
pub fn rival_name(rival: Rival, strength: u32) -> String {
match rival {
Rival::Maia => format!("Maia {strength}"),
Rival::Rodent { style_id } => {
::play::rodent::name(strength, ::play::rodent::iv_style(&style_id).id)
}
}
}
/// The opponent as the app shows it, without the style: «Maia 1500», «Rodent IV 1800».
#[uniffi::export]
pub fn rival_label(rival: Rival, strength: u32) -> String {
match rival {
Rival::Maia => format!("Maia {strength}"),
Rival::Rodent { style_id } => format!(
"{} {strength}",
::play::rodent::iv_style(&style_id).rodent.name()
),
}
}
/// The tags of a game against the computer on the phone (no clocks): `event` in the
/// app's language; the user plays White when `user_white`.
#[uniffi::export]
pub fn computer_game_tags(
event: String,
user_white: bool,
user_name: String,
rival: Rival,
strength: u32,
) -> Vec<crate::Tag> {
let user = if user_white {
@ -81,7 +116,7 @@ pub fn maia_game_tags(
user,
&user_name,
None,
&format!("Maia {strength}"),
&rival_name(rival, strength),
"-",
)
.into_iter()
@ -178,15 +213,10 @@ impl ResignJudge {
}
}
/// Maia's own scale, as on the desktop (decisions «Сила соперника — по шкале самого
/// движка»): the ratings her network was trained on, not a person's Elo.
pub const PHONE_MIN: u32 = 600;
pub const PHONE_MAX: u32 = 2600;
/// The strengths the phone offers: (weakest, strongest).
/// The strengths Maia plays on her own scale, as on the desktop: (weakest, strongest).
#[uniffi::export]
pub fn maia_range() -> Vec<u32> {
vec![PHONE_MIN, PHONE_MAX]
vec![::play::MAIA_MIN, ::play::MAIA_MAX]
}
/// Maia, loaded once for a game.
@ -227,7 +257,7 @@ impl MaiaPlayer {
.collect(),
)
})?;
let strength = strength.clamp(PHONE_MIN, PHONE_MAX);
let strength = strength.clamp(::play::MAIA_MIN, ::play::MAIA_MAX);
let p = self
.maia
.predict(&history, strength, opponent.unwrap_or(strength));
@ -235,6 +265,157 @@ impl MaiaPlayer {
}
}
// ----- Rodent IV ---------------------------------------------------------------------
/// A character of Rodent IV: its id, its English name (for PGN), its title and what it
/// does (English: the app shows its own translations), a great player or not.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct RodentStyle {
pub id: String,
pub name: String,
pub title: String,
pub about: String,
pub player: bool,
}
/// Rodent IV's characters (the desktop's list; Rodent V is not on the phone).
#[uniffi::export]
pub fn rodent_styles() -> Vec<RodentStyle> {
use ::play::rodent::{Gen, STYLES};
STYLES
.iter()
.filter(|s| s.rodent == Gen::IV)
.map(|s| RodentStyle {
id: s.id.to_owned(),
name: s.name.to_owned(),
title: s.title().to_owned(),
about: s.about.to_owned(),
player: s.player,
})
.collect()
}
/// The strengths Rodent IV plays (its UCI_Elo): (weakest, strongest).
#[uniffi::export]
pub fn rodent_range() -> Vec<u32> {
let (lo, hi) = ::play::rodent::Gen::IV.range();
vec![lo, hi]
}
/// The version of Rodent IV's files (the authors' commit): the personalities copied out
/// of the APK are copied again when it changes.
#[uniffi::export]
pub fn rodent_version() -> String {
::play::rodent::COMMIT.to_owned()
}
/// A file of the book pack: where it comes from, where it goes (under the engine's
/// home), its size and SHA-256.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct RodentBook {
pub url: String,
pub local: String,
pub size: u64,
pub sha256: String,
}
/// The opening books Rodent IV's characters open, downloaded as one pack
/// (android-rodent.md §5).
#[uniffi::export]
pub fn rodent_book_pack() -> Vec<RodentBook> {
::play::rodent::book_pack()
.into_iter()
.map(|b| RodentBook {
url: ::play::rodent::file_url(b.file),
local: b.local,
size: b.size,
sha256: b.sha256.to_owned(),
})
.collect()
}
/// Rodent IV playing one game (a UCI child process, the shared crate's player).
#[derive(uniffi::Object)]
pub struct RodentPlayer {
player: ::play::rodent::RodentPlayer,
}
#[uniffi::export]
impl RodentPlayer {
/// The engine at `exe` with its personalities and books in `home`, playing
/// `style_id` at `strength` (its UCI_Elo), with its opening book when `use_book`.
/// It starts in the background: a failure is told by [`RodentPlayer::failure`].
#[uniffi::constructor]
pub fn start(
exe: String,
home: String,
style_id: String,
strength: u32,
use_book: bool,
) -> Arc<RodentPlayer> {
// Below the app (nice 10), as the analysis: the interface comes first. The
// engine finds its files by RODENT4HOME (packaging/rodent-iv/android.patch).
let config = uci::EngineConfig {
working_dir: Some(home.clone().into()),
nice: 10,
env: vec![("RODENT4HOME".into(), home.into())],
..uci::EngineConfig::new(exe)
};
Arc::new(RodentPlayer {
player: ::play::rodent::RodentPlayer::start(
config,
::play::rodent::iv_style(&style_id).id,
Some(strength),
use_book,
Box::new(|| {}),
),
})
}
/// Rodent's move (UCI) in the position at place `at` of the game, given after
/// `pause_ms` (it thinks meanwhile). Blocks: called off the main thread. None when
/// the game is over there, a newer request or `forget` passed it over, or Rodent
/// failed.
pub fn choose(&self, game: Arc<GameSession>, at: u32, pause_ms: u64) -> Option<String> {
let (history, now) = game.read(|g| {
let id = crate::order(g).get(at as usize).copied()?;
Some((g.engine_history(id)?, g.position(id)?.clone()))
})?;
let pos = match history.start_fen {
None => uci::EnginePosition::startpos(history.moves),
Some(fen) => uci::EnginePosition::fen(fen, history.moves),
};
let generation = self
.player
.ask(pos, now, std::time::Duration::from_millis(pause_ms));
let (m, _) = self.player.wait(generation)?;
m.map(|m| m.to_uci(CastlingMode::Standard).to_string())
}
/// Drops the request in flight (its position is gone): its `choose` returns none.
pub fn forget(&self) {
self.player.forget();
}
/// Why Rodent does not play, if it does not.
pub fn failure(&self) -> Option<RodentFailure> {
use ::play::rodent::Failure;
self.player.failure().map(|f| match f {
Failure::Start(detail) => RodentFailure::DidNotStart { detail },
// A search not taken: the process is gone in the middle of the game.
Failure::Stopped | Failure::Search(_) => RodentFailure::Stopped,
})
}
}
/// Why Rodent does not play: it did not start (the engine's words), or it stopped
/// during the game (android-rodent.md §6.6).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum RodentFailure {
DidNotStart { detail: String },
Stopped,
}
#[cfg(test)]
mod tests {
use super::*;
@ -271,4 +452,53 @@ mod tests {
.id;
assert!(m.choose(mated, end, 1500, None, 0.3).is_none());
}
#[test]
fn rodent_is_named_and_listed_as_on_the_desktop() {
let tags = computer_game_tags(
"Game".into(),
true,
"Roman".into(),
Rival::Rodent {
style_id: "iv_tal".into(),
},
1800,
);
let black = tags.iter().find(|t| t.name == "Black").unwrap();
assert_eq!(black.value, "Rodent IV 1800 (Tal)");
assert_eq!(rival_name(Rival::Maia, 1500), "Maia 1500");
let tal = Rival::Rodent {
style_id: "iv_tal".into(),
};
assert_eq!(rival_label(tal, 1800), "Rodent IV 1800");
let styles = rodent_styles();
assert_eq!(styles.len(), 35);
assert_eq!(styles.iter().filter(|s| s.player).count(), 22);
assert_eq!(rodent_range(), vec![800, 2800]);
let pack = rodent_book_pack();
assert!(
pack.iter()
.all(|b| b.url.starts_with("https://raw.githubusercontent.com/")
&& b.local.starts_with("books/")
&& b.sha256.len() == 64)
);
}
/// Needs Rodent IV beside its files: `RODENT4=/path/rodent_iv cargo test -p mobile-api -- --ignored`.
#[test]
#[ignore = "needs Rodent IV (RODENT4)"]
fn rodent_answers_with_a_legal_move() {
let exe = std::env::var("RODENT4").expect("RODENT4");
let home = std::path::Path::new(&exe)
.parent()
.unwrap()
.display()
.to_string();
let r = RodentPlayer::start(exe, home, "iv_karpov".into(), 1600, false);
let s = GameSession::from_pgn("1. e4 *".into()).unwrap();
let e4 = s.data().nodes.iter().find(|n| n.san == "e4").unwrap().id;
let uci = r.choose(s.clone(), e4, 300).expect("a move");
assert!(s.legal_moves(e4).contains(&uci), "{uci}");
assert_eq!(r.failure(), None);
}
}

View file

@ -1,6 +1,6 @@
[package]
name = "play"
description = "A game against Maia in ChessPenguin: how it ends, Maia's pause, her resignation judged by an engine (the desktop and Android apps share it)"
description = "A game against the computer in ChessPenguin: how it ends, the pause, resignation judged by an engine, Rodent and its files (the desktop and Android apps share it)"
version.workspace = true
edition.workspace = true
rust-version.workspace = true

View file

@ -1,6 +1,9 @@
//! A game against Maia (docs/design/play-mode.md, android-play.md §31): how it ends,
//! how long Maia "thinks", and her resignation judged by an engine. Shared by the
//! desktop and the Android apps; nothing here draws.
//! A game against the computer (docs/design/play-mode.md, android-play.md §31): how it
//! ends, how long the opponent "thinks", its resignation judged by an engine, and Rodent
//! (`rodent`). Shared by the desktop and the Android apps; nothing here draws.
pub mod rodent;
mod rodent4_files;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};
@ -8,6 +11,11 @@ use std::time::{Duration, Instant};
use shakmaty::zobrist::Zobrist64;
use shakmaty::{Chess, Color, EnPassantMode, Position};
/// Maia's ratings: what her network was trained on (her own scale, not a person's Elo;
/// decisions «Сила соперника — по шкале самого движка»).
pub const MAIA_MIN: u32 = 600;
pub const MAIA_MAX: u32 = 2600;
// ----- the end of a game ---------------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq)]

857
crates/play/src/rodent.rs Normal file
View file

@ -0,0 +1,857 @@
//! Rodent, the opponent with a style (docs/research/rodent.md, docs/design/rodent-opponent.md,
//! android-rodent.md): its styles and characters, its scales of strength, the files of
//! Rodent IV with the books its characters open, and the engine playing a game in a
//! thread of its own. Shared by the desktop and the Android apps; nothing here draws.
use std::collections::BTreeMap;
use std::sync::mpsc::{Sender, channel};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use shakmaty::{Chess, Move};
pub use crate::rodent4_files::{COMMIT, FILES, PERSONALITY_BOOKS};
// ----- styles and characters -------------------------------------------------------------
/// Rodent's styles: its personality files, the personality's name (for PGN), what the
/// style is called and does (English: the apps translate it). The players' imitations
/// are marked `player`.
pub struct Style {
pub id: &'static str,
pub name: &'static str,
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,
}
impl Style {
/// The style's name to translate («Attacking»).
pub fn title(&self) -> &'static str {
self.title
}
}
/// 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),
}
}
}
// Each engine on its own scale, as its authors give it (decisions «Сила соперника — по
// шкале самого движка»): not a person's Elo.
/// 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;
pub const STYLES: &[Style] = &[
Style {
id: "rodent",
name: "Rodent",
title: "Balanced",
about: "Even, all-round play with no bias.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "ampere",
name: "Ampere",
title: "Attacking",
about: "Active pieces and attack, sound pawn structure.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "chaotic",
name: "Chaotic",
title: "Chaotic",
about: "Aggressive, tricky openings, careless with pawns.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "nimzoid",
name: "Nimzoid",
title: "Restricting",
about: "Closed positions, cramping the opponent, old openings.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "hector",
name: "Hector",
title: "Classical",
about: "Hand-written evaluation, no neural network.",
player: false,
rodent: Gen::V,
personality: "",
},
Style {
id: "tal_hybrid",
name: "Tal",
title: "Tal",
about: "Attacking style tuned on Tal's games.",
player: true,
rodent: Gen::V,
personality: "",
},
Style {
id: "tal_nnue",
name: "Tal NNUE",
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",
},
];
/// The style of this id (the default one for an unknown id).
pub fn style(id: &str) -> &'static Style {
STYLES.iter().find(|s| s.id == id).unwrap_or(&STYLES[0])
}
/// Rodent IV's character of this id (Tal for an unknown one, or one of Rodent V: a
/// phone has Rodent IV only, android-rodent.md §7.1).
pub fn iv_style(id: &str) -> &'static Style {
STYLES
.iter()
.find(|s| s.id == id && s.rodent == Gen::IV)
.unwrap_or_else(|| style("iv_tal"))
}
/// Rodent as a game names it: «Rodent V 2400» (the default style unnamed), «Rodent V 2400
/// (Tal)», «Rodent IV 1800 (Tal)» — the personality's English name: PGN is not translated.
pub fn name(strength: u32, style_id: &str) -> String {
let st = style(style_id);
if st.id == STYLES[0].id {
format!("{} {strength}", st.rodent.name())
} else {
format!("{} {strength} ({})", st.rodent.name(), st.name)
}
}
// ----- Rodent IV's files ---------------------------------------------------------------
/// Books three personalities name by a path not in the authors' files (a case or a dash
/// off): they are read under that name (the engine takes books only from the
/// personality's file). (file in the repository, name it is read by)
pub 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 «#»).
pub fn url_path(path: &str) -> String {
path.replace('#', "%23").replace(' ', "%20")
}
/// Where a file of the authors' repository is downloaded from (at `COMMIT`).
pub fn file_url(path: &str) -> String {
format!(
"https://raw.githubusercontent.com/nescitus/rodent-iv/{COMMIT}/{}",
url_path(path)
)
}
/// An opening book of Rodent IV to download: its file in the authors' repository, where
/// the engine reads it (relative to its home folder), its size and SHA-256.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Book {
pub file: &'static str,
pub local: String,
pub size: u64,
pub sha256: &'static str,
}
/// The books Rodent IV's characters open (the guide and the main book of each), each
/// once, under the name it is read by: the phone's book pack (android-rodent.md §5), not
/// the books nobody uses.
pub fn book_pack() -> Vec<Book> {
let mut books = BTreeMap::new();
for st in STYLES.iter().filter(|s| s.rodent == Gen::IV) {
let Some(&(_, guide, main)) = PERSONALITY_BOOKS.iter().find(|p| p.0 == st.personality)
else {
continue;
};
for book in [guide, main] {
let local = format!("books/{book}");
let file = BOOK_NAMES
.iter()
.find(|(_, name)| *name == local)
.map_or(local.as_str(), |(file, _)| file);
if let Some(&(file, size, sha256)) = FILES.iter().find(|f| f.0 == file) {
books.entry(local.clone()).or_insert(Book {
file,
local,
size,
sha256,
});
}
}
}
books.into_values().collect()
}
// ----- Rodent playing a game -----------------------------------------------------------
/// Why Rodent does not play.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Failure {
/// It did not start, or did not take its options (the engine's words).
Start(String),
/// Its process ended during the game.
Stopped,
/// A search could not be asked for (the engine's words).
Search(String),
}
/// A move asked for: the game for the engine, its position now, the pause.
struct Request {
generation: u64,
pos: uci::EnginePosition,
now: Chess,
pause: Duration,
}
/// Rodent's move, or none (no legal move it gave), and the time it took.
pub type Answer = (Option<Move>, Duration);
#[derive(Default)]
struct State {
/// The request asked last (bumped by `forget`).
generation: u64,
/// The newest request answered or passed over, and the answer of the newest.
answered: u64,
answer: Option<(u64, Answer)>,
failure: Option<Failure>,
}
#[derive(Default)]
struct Shared {
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn fail(&self, f: Failure) {
self.lock().failure = Some(f);
self.changed.notify_all();
}
}
/// Rodent playing one game, in its own thread (a UCI child process): it thinks during
/// the pause a move should take (a game's own clock is not its business: Maia's pause
/// rule paces it) and answers after it. Only the newest request counts; the answer to
/// an older one (after a take-back) is dropped.
pub struct RodentPlayer {
tx: Sender<Request>,
shared: Arc<Shared>,
}
impl RodentPlayer {
/// The engine of `config` (its folder, or its home in the environment: Android)
/// playing `style_id` at `uci_elo` (none: full strength), with its opening book when
/// `use_book`. `wake` is called when an answer or a failure comes (the app draws again).
pub fn start(
config: uci::EngineConfig,
style_id: &str,
uci_elo: Option<u32>,
use_book: bool,
wake: Box<dyn Fn() + Send>,
) -> RodentPlayer {
let (tx, rx) = channel::<Request>();
let shared = Arc::new(Shared::default());
let sh = shared.clone();
let st = style(style_id);
let _ = std::thread::Builder::new()
.name("rodent".into())
.spawn(move || {
let fail = |f: Failure| {
sh.fail(f);
wake();
};
let engine = match uci::Engine::spawn_with(config, Box::new(|| {})) {
Ok(e) => e,
Err(e) => return fail(Failure::Start(e.to_string())),
};
// V reads a personality file; IV picks one of its list (with its books).
let book = use_book.to_string();
let mut setup = match st.rodent {
Gen::V => vec![
("PersonalityFile", format!("personalities/{}.txt", st.id)),
("OwnBook", book),
],
Gen::IV => vec![
("Personality", st.personality.to_owned()),
("UseBook", book),
],
};
if let Some(elo) = uci_elo {
setup.push(("UCI_LimitStrength", "true".to_owned()));
setup.push(("UCI_Elo", elo.to_string()));
}
let ready = engine.set_threads(1).and_then(|()| engine.set_hash_mb(64));
if let Err(e) = ready {
return fail(Failure::Start(e.to_string()));
}
for (name, value) in &setup {
if let Err(e) = engine.set_option(name, Some(value)) {
return fail(Failure::Start(e.to_string()));
}
}
let _ = engine.new_game();
while let Ok(mut r) = rx.recv() {
while let Ok(newer) = rx.try_recv() {
r = newer;
}
let started = Instant::now();
let id = uci::SearchId(r.generation);
// Its own limit (from UCI_Elo) ends the search early; at full strength
// it thinks for the pause.
let think = r.pause.max(Duration::from_millis(300));
if let Err(e) = engine.search(r.pos, id, uci::SearchLimits::MoveTime(think)) {
return fail(Failure::Search(e.to_string()));
}
let mut stopped: Option<Instant> = None;
let best = loop {
match engine.recv_timeout(Duration::from_millis(200)) {
Some(uci::EngineEvent::BestMove {
search_id, best: b, ..
}) if search_id == id => break b,
Some(uci::EngineEvent::Terminated(_)) => {
return fail(Failure::Stopped);
}
// A search that does not end: stopped, then given up on.
_ => match stopped {
None if started.elapsed() > think + Duration::from_secs(20) => {
let _ = engine.stop();
stopped = Some(Instant::now());
}
Some(t) if t.elapsed() > Duration::from_secs(5) => {
return fail(Failure::Stopped);
}
_ => {}
},
}
};
let m = best
.and_then(|b| b.parse::<shakmaty::uci::UciMove>().ok())
.and_then(|u| u.to_move(&r.now).ok());
std::thread::sleep(r.pause.saturating_sub(started.elapsed()));
let spent = r.pause.max(started.elapsed());
{
let mut s = sh.lock();
s.answered = s.answered.max(r.generation);
s.answer = Some((r.generation, (m, spent)));
}
sh.changed.notify_all();
wake();
}
engine.quit();
});
RodentPlayer { tx, shared }
}
/// Asks for a move in `now` (`pos`: the game to it for the engine) after `pause`;
/// the request's number, for [`RodentPlayer::wait`].
pub fn ask(&self, pos: uci::EnginePosition, now: Chess, pause: Duration) -> u64 {
let generation = {
let mut s = self.shared.lock();
s.generation += 1;
s.generation
};
let _ = self.tx.send(Request {
generation,
pos,
now,
pause,
});
generation
}
/// Forgets what was asked (its answer will be dropped; a wait for it ends).
pub fn forget(&self) {
self.shared.lock().generation += 1;
self.shared.changed.notify_all();
}
/// The answer to the request asked last, once it has come (given once).
pub fn answer(&self) -> Option<Answer> {
let mut s = self.shared.lock();
let generation = s.generation;
match s.answer {
Some((g, _)) if g == generation => s.answer.take().map(|(_, a)| a),
_ => None,
}
}
/// Waits for the answer to request `generation`: none when it was forgotten or
/// passed over by a newer one, or Rodent failed.
pub fn wait(&self, generation: u64) -> Option<Answer> {
let mut s = self.shared.lock();
while s.generation == generation && s.answered < generation && s.failure.is_none() {
s = self
.shared
.changed
.wait(s)
.unwrap_or_else(|e| e.into_inner());
}
match s.answer {
Some((g, _)) if g == generation && s.generation == generation => {
s.answer.take().map(|(_, a)| a)
}
_ => None,
}
}
/// Why Rodent does not play, if it does not.
pub fn failure(&self) -> Option<Failure> {
self.shared.lock().failure.clone()
}
}
#[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 read under another name are in the authors' files.
for (file, _) in BOOK_NAMES {
assert!(FILES.iter().any(|f| f.0 == *file), "{file}");
}
}
#[test]
fn the_pack_has_the_books_of_every_character_and_no_other() {
let pack = book_pack();
let has = |local: &str| pack.iter().any(|b| b.local == local);
let iv: Vec<&Style> = STYLES.iter().filter(|s| s.rodent == Gen::IV).collect();
assert_eq!(iv.len(), 35);
for st in iv {
let (_, guide, main) = PERSONALITY_BOOKS
.iter()
.find(|p| p.0 == st.personality)
.unwrap_or_else(|| panic!("no books for {}", st.personality));
assert!(has(&format!("books/{guide}")), "{guide}");
assert!(has(&format!("books/{main}")), "{main}");
}
// The three named otherwise come from their files in the repository.
let spassky = pack
.iter()
.find(|b| b.local == "books/players/ph_spassky2.bin")
.unwrap();
assert_eq!(spassky.file, "books/players/ph-spassky2.bin");
assert!(has("books/guide/strangler.bin") && has("books/guide/guide.bin"));
// Nobody's books stay out: 59 MB of the 69.
assert!(!has("books/guide/ph-exoticbook.bin"));
let total: u64 = pack.iter().map(|b| b.size).sum();
assert_eq!((total + 500_000) / 1_000_000, 59);
assert!(
file_url(spassky.file).ends_with(&format!("/{COMMIT}/books/players/ph-spassky2.bin"))
);
}
#[test]
fn rodent_is_named_with_its_strength_and_personality() {
assert_eq!(name(1800, "iv_tal"), "Rodent IV 1800 (Tal)");
assert_eq!(name(2400, "rodent"), "Rodent V 2400");
assert_eq!(name(2400, "tal_hybrid"), "Rodent V 2400 (Tal)");
assert_eq!(style("iv_spassky").rodent.range(), (800, 2800));
// An unknown style (of a later version) is the default one; of Rodent IV, Tal.
assert_eq!(style("nobody").id, "rodent");
assert_eq!(iv_style("nobody").id, "iv_tal");
assert_eq!(iv_style("ampere").id, "iv_tal");
assert_eq!(iv_style("iv_karpov").id, "iv_karpov");
}
/// Needs Rodent IV and its files: `RODENT4=/path/rodent_iv cargo test -p play -- --ignored`
/// (the folder of the executable has `personalities/` and `books/`).
#[test]
#[ignore = "needs Rodent IV (RODENT4)"]
fn rodent_answers_the_newest_request_only() {
let exe = std::env::var("RODENT4").expect("RODENT4");
let player = RodentPlayer::start(
uci::EngineConfig::new(exe),
"iv_tal",
Some(1800),
true,
Box::new(|| {}),
);
let start = || uci::EnginePosition::startpos(Vec::<String>::new());
let pause = Duration::from_millis(400);
// Asked twice: the first is passed over, the second answered with a legal move.
let first = player.ask(start(), Chess::default(), pause);
let second = player.ask(start(), Chess::default(), pause);
assert_eq!(player.wait(first), None);
let (m, spent) = player.wait(second).expect("an answer");
assert!(m.is_some(), "{:?}", player.failure());
assert!(spent >= pause);
// A request forgotten ends its wait at once.
let third = player.ask(start(), Chess::default(), pause);
player.forget();
assert_eq!(player.wait(third), None);
assert_eq!(player.failure(), None);
}
}

View file

@ -452,3 +452,48 @@ pub const FILES: &[(&str, u64, &str)] = &[
"0e5a9fc33d3ade50d7eaa68a06d29131151d270d5d0f3afd5d408bfb9081e4d8",
),
];
/// The personalities of the engine's list: (name, guide book, main book), the books
/// as the personality's file names them (under `books/`).
pub const PERSONALITY_BOOKS: &[(&str, &str, &str)] = &[
("Alekhine", "players/rj-alekhine.bin", "hist/_pre30.bin"),
("Amanda", "guide/ph-gambitbook.bin", "rodent.bin"),
("Ampere", "guide/active.bin", "rodent.bin"),
("Anand", "players/ph-anand2.bin", "hist/_post06.bin"),
("Anderssen", "players/ph-anderssen2.bin", "hist/_pre30.bin"),
("Bosboom.txt", "players/bn-bosboom.bin", "hist/_post06.bin"),
("Botvinnik", "players/ph-botvinnik2.bin", "hist/_31to80.bin"),
("Cloe", "guide/closed.bin", "rodent.bin"),
("Deborah", "guide/guide.bin", "rodent.bin"),
("Defender", "guide/solid.bin", "rodent.bin"),
("Dynamic", "guide/active.bin", "rodent.bin"),
("Fischer", "players/ph-fischer2.bin", "hist/_31to80.bin"),
("Grumpy", "guide/grandpa.bin", "rodent.bin"),
("Karpov", "players/ph-karpov2.bin", "hist/_81to06.bin"),
("Kasparov", "players/rj-kasparov.bin", "hist/_81to06.bin"),
("Kortchnoi", "players/rj-kortchnoi.bin", "hist/_31to80.bin"),
("Larsen", "players/ph-larsen2.bin", "hist/_31to80.bin"),
("Lasker", "players/ph-lasker2.bin", "hist/_pre30.bin"),
("Marshall", "players/rj-marshall.bin", "hist/_pre30.bin"),
("Morphy", "players/morphy.bin", "hist/_pre30.bin"),
("Nimzowitsch", "players/nimzowitsch.bin", "hist/_pre30.bin"),
("Partisan", "guide/low.bin", "rodent.bin"),
("Pawnsacker", "rodent.bin", "rodent.bin"),
("Pedrita", "guide/solid.bin", "rodent.bin"),
("Petrosian", "players/petrosian.bin", "hist/_31to80.bin"),
("Preston", "guide/cs.bin", "rodent.bin"),
("Reti", "players/ph-reti2.bin", "hist/_pre30.bin"),
(
"Rubinstein",
"players/ph-rubinstein2.bin",
"hist/_pre30.bin",
),
("Simple", "guide/simple.bin", "rodent.bin"),
("Spassky", "players/ph_spassky2.bin", "hist/_31to80.bin"),
("Spitfire", "guide/active.bin", "rodent.bin"),
("Steinitz", "players/steinitz.bin", "hist/_pre30.bin"),
("Strangler", "guide/strangler.bin", "rodent.bin"),
("Tal", "players/ph-tal2.bin", "hist/_31to80.bin"),
("Tarrasch", "players/ph-tarrasch2.bin", "hist/_pre30.bin"),
("Topalov", "players/ph-topalov2.bin", "hist/_post06.bin"),
];

View file

@ -81,6 +81,9 @@ pub struct EngineConfig {
/// Added to the engine's nice value on Unix (0 = as the app): a phone keeps its
/// interface smooth while the engine thinks. Every thread of the engine has it.
pub nice: i32,
/// Variables added to the engine's environment (Rodent IV on Android finds its
/// personalities and books by `RODENT4HOME`).
pub env: Vec<(OsString, OsString)>,
}
impl EngineConfig {
@ -91,6 +94,7 @@ impl EngineConfig {
working_dir: None,
timeouts: Timeouts::default(),
nice: 0,
env: Vec::new(),
}
}
}
@ -389,6 +393,7 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result<EngineHandle, EngineErr
let mut command = Command::new(&path);
command
.args(&cfg.args)
.envs(cfg.env.iter().map(|(k, v)| (k, v)))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());

View file

@ -676,3 +676,25 @@ fn an_engine_can_run_below_the_app() {
calm.quit();
plain.quit();
}
#[cfg(target_os = "linux")]
#[test]
fn an_engine_gets_the_variables_given() {
let engine = Engine::spawn_with(
EngineConfig {
env: vec![("CP_TEST_HOME".into(), "/some/where".into())],
..config(&[])
},
Box::new(|| {}),
)
.expect("spawn");
let environ = std::fs::read(format!("/proc/{}/environ", engine.pid())).expect("environ");
assert!(
environ
.split(|&b| b == 0)
.any(|v| v == b"CP_TEST_HOME=/some/where")
);
// The app's own environment goes on as well.
assert!(environ.split(|&b| b == 0).any(|v| v.starts_with(b"PATH=")));
engine.quit();
}

View file

@ -122,7 +122,15 @@
Владелец: «заюзаем rodent 4 со всеми его стилями… людям хочется больше персонажей». Согласовано:
- **Один соперник «Rodent»** в диалоге игры: его список расширяется персонажами Rodent IV — характеры (Аманда, Защитник, Удав… — названия переведены на все языки, в записи партии английское имя движка) к стилям, 22 великих шахматиста (Алехин… Таль) к «Как игрок». Какой движок играет (V или IV), программа выбирает по персонажу; сила — по шкале движка (IV 800–2800, V 800–3000).
- **Движок IV собираем сами** из исходников авторов (GPL-3, зафиксированная версия) в нашем CI для Linux, Windows и macOS и выкладываем отдельным выпуском на GitHub; программа скачивает его по кнопке с проверкой суммы. Персонажи и книги скачиваются из репозитория авторов на той же версии, каждый файл с проверкой суммы. На macOS Rodent появляется впервые (V там нет).
- **На телефоне** — только Maia (игра) и Stockfish (анализ), других движков нет.
- **На телефоне** — только Maia (игра) и Stockfish (анализ), других движков нет. *Изменено 2026-10-27, см. ниже.*
## Rodent IV на телефоне (2026-10-27)
Владелец: «хочу чтобы в мобилке мы все же внедрили 4 версию движка… при старте игры показывали какой движок мы хотим выбрать». Согласовано (проект `docs/design/android-rodent.md`):
- Соперник в игре на телефоне — Maia или Rodent IV (13 характеров и 22 великих шахматиста); Stockfish остаётся для анализа. Rodent V на телефоне нет.
- Движок собирается нашим скриптом (`androidApp/scripts/rodent4.sh`) из исходников авторов на той же версии и лежит в APK обеих сборок; характеры — в APK.
- Дебютные книги — **одним пакетом** (≈ 59 МБ: только используемые характерами), скачиваются один раз по кнопке с проверкой сумм; удаляются в «Настройки → Движок». Кнопка «Без книги» позволяет играть без них.
- Первый раз выбрана Maia; при первом выборе Rodent сам открывается список с предложенным Талем. С позиции книги не нужны. Сила запоминается отдельно для Maia и Rodent. Кнопка «Играть с Maia» на «Базах» становится «Играть».
## Сила соперника — по шкале самого движка (2026-10-26)

View file

@ -0,0 +1,474 @@
# Rodent IV на телефоне: выбор соперника и его характера
Статус: проект дизайнера, 2026-10-27, **для согласования**. Продолжает `android-play.md` §31 (игра с Maia) и `android-lists.md` §5.4–5.5; эталон 360×800 dp, размеры — dp, текст — sp (`android-ui.md` §0). Настольный образец — `rodent-opponent.md` и нынешний `Dialog::show` в `apps/desktop/src/play.rs` (список `STYLES`, переводы в `apps/desktop/src/i18n.rs`). Исследование — `docs/research/rodent.md`.
**Что меняется в решениях.** `docs/decisions.md`, «Rodent IV: его персонажи…», п. 3: «На телефоне — только Maia (игра) и Stockfish (анализ)». Владелец 2026-10-27 это меняет: «хочу чтобы в мобилке мы все же внедрили 4 версию движка где у нас куча режимов, и при старте игры показывали какой движок мы хотим выбрать (майя 5м или же этот движок 4 версии) и если его, то чтобы был выбор его режимов». На телефоне соперников в игре два — **Maia** и **Rodent IV**; анализ по-прежнему только Stockfish. Rodent V на телефон не идёт: у него нет сборки под ARM (`research/rodent.md` §5). Запись в `decisions.md` делает оркестратор.
Технические условия (установил оркестратор): исполняемый Rodent IV собирается NDK и лежит в APK, как `libstockfish.so`, в обеих сборках (полной и лёгкой), около 1 МБ на ABI. Скачанный файл Android запускать не даёт, поэтому сам движок не скачивается. Файлы характеров (`personalities/*.txt`, 109 КБ) тоже лежат в APK. Скачиваются только дебютные книги.
## 0. Коротко
1. Кнопка «Играть» на «Базах» открывает тот же лист «Игра с компьютером». **Новое — вверху листа:** две карточки соперника, «Maia» и «Rodent IV», а под ними строка характера. Для Rodent в строке выбранный характер («Таль»), касание открывает экран выбора «С кем играть». Для Maia строка неактивна: «Как человек».
2. **Характер выбирается на полноэкранном списке.** Там 35 строк в двух группах: «Великие шахматисты» (22) и «Характеры» (13). У каждой строки буквица, имя и описание с компьютера. Выбор одним касанием сразу возвращает к листу.
3. **Сила у каждого движка своя и запоминается отдельно.** У Maia шкала 600–2600, у Rodent IV — 800–2800. При смене соперника ползунок встаёт на последнее значение этого движка, подписи концов и пояснение меняются.
4. **Дебютные книги Rodent IV скачиваются одним пакетом, один раз** (решение владельца 2026-10-27, §5). Кнопка та же, что у Maia: «Скачать и играть». Движок в APK играет и без книг, поэтому без сети или при отказе от загрузки можно «Без книги».
5. **Лист не прыгает.** Карточки, строка характера, пояснение под ползунком и строка состояния — фиксированной высоты. Строка состояния и кнопка «Играть» закреплены внизу листа, остальное прокручивается.
6. В партии на плашке и в заголовке: «Rodent IV 1800 · Таль». В PGN, как на компьютере: `Rodent IV 1800 (Tal)`. Отложенную партию с Rodent можно продолжить, как партию с Maia.
## 1. Пути пользователя
### 1.1. Первый раз (ничего не скачано, Rodent ни разу не выбирали)
1. «Базы» → «Играть». Лист: выбрана карточка **Maia** (как сейчас, вопрос 1). Строка характера неактивна: «Как человек · Maia не выбирает стиль…». Ползунок показывает «Сила: 1500» (600–2600). Внизу: «Maia скачивается один раз (21 МБ…)» и «Скачать и играть».
2. Пользователь касается карточки **Rodent IV**. Карточка выбрана, ползунок переходит на шкалу Rodent (800–2800, «Сила: 1500»). Так как характер ещё ни разу не выбирали, **сразу открывается «С кем играть»** (только этот раз, §3.4). Список прокручен к предложенному «Талю», он отмечен.
3. Касание «Карпов» возвращает на лист. В строке характера «Карпов — Позиционное давление, профилактика и техника.» Внизу: «Дебютные книги Rodent IV · 59 МБ, скачиваются один раз с github.com (файлы авторов)», «Скачать и играть», справа в строке — «Без книги».
4. «Скачать и играть»: полоса «12 из 59 МБ» с ✕, затем «Проверка…». Когда всё проверено, партия начинается сама, если лист ещё открыт и выбран Rodent (характер можно было сменить — книги общие). После этого книги есть у всех 35 характеров; больше Rodent ничего не качает.
5. Если пользователь закрыл «С кем играть» «назад» без выбора, остаётся предложенный Таль. Выбор не обязателен, но список он увидел.
### 1.2. Возвращается
- Лист открывается с последним выбором: соперник, характер, сила этого соперника, цвет, имя. Книги уже есть: «Играть» — одно касание, как сейчас с Maia.
- Отложенная партия есть — сначала прежний вопрос `AdjournedQuestion` («Есть отложенная партия с Rodent IV 1800»), §6.5.
### 1.3. Сменить соперника или характер
- Касание другой карточки меняет соперника, силу (своя у каждого, §4) и строку состояния. Характер Rodent при переходе на Maia не теряется, при возврате он снова в строке. Повторно экран выбора сам не открывается.
- Сменить характер: касание строки характера → «С кем играть» → касание имени. Сила при смене характера не меняется: шкала у всех характеров одна (UCI_Elo).
- Сменить характер, пока Maia выбрана, нельзя: строка неактивна. Сначала карточка Rodent IV. Так же устроено на компьютере, где комбо стиля выключено у Maia.
### 1.4. Скачивания
| Ситуация | Что видит пользователь |
|---|---|
| Выбрана Maia, её нет | как сейчас (§31.2): «Maia скачивается один раз…», «Скачать и играть» |
| Выбран Rodent, книг нет | «Дебютные книги Rodent IV · 59 МБ…» + «Без книги»; кнопка «Скачать и играть» |
| Выбран Rodent, книги есть, а Maia не скачана | «Играть»; о Maia ни слова: строка состояния относится только к выбранному сопернику (как на компьютере, `rodent-opponent.md` §6) |
| Нет ни Maia, ни книг | показано то, что нужно выбранному сопернику; другой не упоминается |
| Идёт загрузка, пользователь переключил соперника на готового | «Играть» активна; загрузка продолжается в фоне (уведомление `DownloadManager`, как у Maia); партия по окончании сама не начнётся |
| Идёт загрузка книг, пользователь меняет характер | ничего не меняется: книги общие, загрузка идёт, по окончании партия начнётся с новым характером |
| ✕ во время загрузки | загрузка останавливается. Скачанные и проверенные файлы пакета остаются, при следующем «Скачать и играть» докачивается остаток; размер в строке — остаток |
| Нет сети / обрыв / нет места / файл не тот | красная строка, прежние тексты `no_internet`, `interrupted`, `no_space` (нужно 59 МБ), `corrupt`; кнопка «Повторить», справа «Без книги» (§5.5) |
| Закрыли лист во время загрузки | загрузка продолжается в фоне с уведомлением; партия не начинается (как у Maia) |
### 1.5. Играть с позиции (§31.6)
Лист тот же, с блоком позиции вверху; соперник и характер — последние. **Книги с позиции не требуются.** Если книг нет, строка состояния: «С позиции дебютная книга не нужна — Rodent IV играет сразу», кнопка «Играть» (вопрос 4). Если книги есть, движок ими пользуется. Заставлять качать 59 МБ ради позиции из середины партии, где книга почти никогда не срабатывает, не стоит.
### 1.6. Реванш
Тот же соперник, характер и сила; цвета меняются (§31.4). Книги уже скачаны, так что начинается сразу. Если книги удалили в настройках между партиями, реванш открывает лист (как «Новая игра»), а не стартует молча с загрузкой.
### 1.7. Отложенная партия с Rodent
«Назад» откладывает партию с Rodent так же, как с Maia (§31.7). Карточка на «Базах»: «Партия с Rodent IV 1800», вторая строка — «Таль · вы белыми · 6-й ход». «Продолжить» поднимает Rodent IV с тем же характером и силой. **Книги для продолжения не требуются**: если их удалили, партия продолжается без книги, без вопросов (к середине партии книга обычно уже не нужна).
### 1.8. В партии
Плашка соперника: «Rodent IV 1800 · Таль». Заголовок: «Партия с Rodent IV 1800», под ним «Таль · вы белыми · без часов». Ничья, сдача, «Ход назад», просмотр и конец партии — как с Maia (§31.3–31.4), с текстами для Rodent (§9).
## 2. Лист «Игра с компьютером»
### 2.1. Компоновка (360×800, портрет)
```
┌────────────────────────────────────┐
│ ─── │ ручка 22
│ Игра с компьютером │ 22sp titleLarge
│ ┌──────┐ После 14…Ке7 │ только «Играть отсюда»,
│ │доска │ из партии Карлсен — Каруана│ мини-доска 96 dp (как сейчас)
│ └──────┘ │
│ ┌───────────────┐┌───────────────┐ │
│ │✓ Maia ││ Rodent IV │ │ 64 две карточки по 152, зазор 8
│ │играет как ││сильный, со │ │ имя titleSmall 500,
│ │человек ││стилем │ │ подпись bodySmall, 2 строки
│ └───────────────┘└───────────────┘ │
│ ┌────────────────────────────────┐ │
│ │(Т) Таль › │ │ 80 строка характера (§2.3)
│ │ Рижский волшебник: жертвы │ │ описание bodyMedium, ≤ 2 строк
│ │ и атака. │ │
│ └────────────────────────────────┘ │
│ Сила: 1800 │ 24 titleMedium 500, Tabular
│ 800 ━━━━━━━━━━━●━━━━━━━━━━━━ 2800 │ 48 Slider, шаг 50
│ Собственный рейтинг Rodent │ 32 12sp onSurfaceVariant,
│ (UCI_Elo): он не равен Эло человека│ всегда 2 строки (minLines 2)
│ Цвет │ 20
│ [ Белыми ][▌Случайно▐][ Чёрными ] │ 48
│ ┌ Ваше имя ────────────────── ▾ ┐ │ 56 как сейчас (player-games.md §6)
│ └───────────────────────────────┘ │
│ В «Роман — партии с компьютером» … │ 20
╞════════════════════════════════════╡ ← граница прокрутки (тень при прокрутке)
│ Дебютные книги Rodent IV · 59 МБ, │ 40 строка состояния, 2 строки 12sp;
│ один раз с github.com [Без книги]│ справа TextButton 48
│ ┌────────────────────────────────┐ │
│ │ Скачать и играть │ │ 56 Button на всю ширину
│ └────────────────────────────────┘ │
└────────────────────────────────────┘
```
- **Высота без позиции** ≈ 22 + 44 + 64 + 8 + 80 + 8 + 24 + 48 + 32 + 16 + 76 + 12 + 76 = 510 dp прокручиваемой части и 128 dp подвала (строка 40, зазор 8, кнопка 56, поле 24). Итого ≈ 640 dp плюс системная панель — помещается в 800 без прокрутки. С блоком позиции (+108) — ≈ 750, на маленьких экранах прокручивается.
- **Подвал закреплён** (новое по сравнению с §31.1): строка состояния и кнопка вне `verticalScroll`, под ними `navigationBarsPadding`, над ними `imePadding`. Когда клавиатура открыта (поле имени), подвал стоит над ней. Пока часть содержимого скрыта под подвалом, над ним тень `Elevation 2`/линия `outlineVariant` 1 dp. Без этого при новых 150 dp кнопка «Играть» уходила бы под край на маленьком телефоне с позицией.
- **Порядок блоков:** соперник → характер → сила → цвет → имя. Сначала *кто*, потом *насколько сильный*: шкала силы зависит от соперника.
- Заголовок листа — нынешняя строка `play_title` («Игра с компьютером»). Прежний заголовок секции «Соперник — Maia 1500» убирается: соперник виден на карточках, сила — в «Сила: 1800». Это возвращает строку, которую берёт строка характера.
### 2.2. Карточки соперника
- Две `OutlinedCard`, каждая с `Modifier.selectable(role = RadioButton)` в общей `selectableGroup`. Размер 152×64 (вес 1, зазор 8), скругление 12, поля 12.
- **Выбранная:** заливка `secondaryContainer`, рамка 2 dp `primary`, слева от имени значок `check` 18 dp. **Невыбранная:** заливка `surface`, рамка 1 dp `outlineVariant`. Значок с галочкой нужен, чтобы выбор был виден не только цветом.
- Строки — переводы с компьютера: имя (`Maia`, `Rodent IV` — не переводятся) и подпись «играет как человек» / «сильный, со стилем» (`plays like a human` / `strong, with a style`), не больше 2 строк, затем «…».
- Касание меняет соперника; сила, концы ползунка, строка характера и строка состояния обновляются сразу, без анимации высоты. Высота листа не меняется.
- Rodent IV в APK всегда есть, поэтому неактивного состояния карточки нет. Если движок не запустился на этом устройстве, см. §6.6.
### 2.3. Строка характера
Одна и та же строка 80 dp при обоих соперниках, меняется только содержимое:
| | Rodent IV | Maia |
|---|---|---|
| слева | буквица 40 dp (§3.2) | значок `person` 24 dp в круге 40 dp `surfaceContainerHighest` |
| первая строка | имя характера («Таль», «Удав»), bodyLarge 500 | «Как человек» (`Like a human`) |
| вторая | описание (`about` с компьютера), bodyMedium `onSurfaceVariant`, ≤ 2 строк | «Maia не выбирает стиль: она играет, как люди её рейтинга.» |
| справа | `chevron_right` | ничего |
| касание | открывает «С кем играть» (§3) | нет; вся строка цвета `onSurface` 0,38 |
| фон | `surfaceContainerHigh`, скругление 12 | тот же, неактивный |
- Почему строка есть и у Maia: высота листа не меняется при смене соперника. Кроме того, неактивная строка подсказывает, что стиль — свойство Rodent (на компьютере так же).
- Почему не выпадающий список, как на компьютере: 35 пунктов с описаниями в `ExposedDropdownMenu` — это узкое меню на 4 экрана высоты без заголовков групп и без размеров книг. Полноэкранный список читается лучше и даёт место под описание.
### 2.4. Строка состояния и кнопка (подвал)
Высота строки всегда 40 dp (2 строки 12sp), кнопка всегда 56 dp. Содержимое — только о выбранном сопернике. Для Maia всё по `android-play.md` §31.2 без изменений. Для Rodent:
| Состояние | Строка (`bodySmall`) | Кнопка |
|---|---|---|
| книги есть | «Rodent IV и его дебютные книги на телефоне» `onSurfaceVariant` | «Играть» |
| книг нет | «Дебютные книги Rodent IV · {n} МБ, скачиваются один раз с github.com (файлы авторов)»; справа `TextButton` «Без книги» | «Скачать и играть» |
| книг нет, игра с позиции | «С позиции дебютная книга не нужна — Rodent IV играет сразу» | «Играть» |
| загрузка | `LinearProgressIndicator` + «{a} из {b} МБ» + ✕ 48 dp (`cancel_download`) | «Играть», неактивна |
| проверка | «Проверка…» | неактивна |
| ошибка | `error`: `no_internet` / `interrupted` / `no_space` / `corrupt`; справа «Без книги» | «Повторить» |
- `{n}` — сколько **осталось** скачать (после ✕ или обрыва — остаток), целым с округлением вверх, как сейчас `megabytes()`.
- Текст строки при «книг нет» обрезается справа кнопкой «Без книги» (≈ 96 dp): строка 2 строки по ≈ 230 dp — укладывается на русском и английском; на длинных языках — «…», полный текст в TalkBack.
- «Скачать и играть»: партия начнётся сама после проверки, если лист открыт и выбран Rodent (иначе флаг `playAfter` сбрасывается — правило компьютера, `rodent-opponent.md` §6). Смена характера флаг не сбрасывает: книги общие.
## 3. Экран «С кем играть»
### 3.1. Компоновка
Полноэкранный `Dialog` (`usePlatformDefaultWidth = false`) поверх листа, как форма «Данные партии» (§30.5). Лист под ним остаётся открытым.
```
┌────────────────────────────────────┐
│ ← С кем играть │ 64 TopAppBar
├────────────────────────────────────┤
│ Характер — это стиль и дебюты, │ 14sp onSurfaceVariant, поля 16
│ силу задаёт ползунок. │
│ Великие шахматисты │ 48 заголовок группы, прилипает
│ (А) Алехин │ 72+ ListItem
│ Динамичные атаки и глубокие │
│ комбинации. │
│ (А) Ананд │
│ Быстрая, универсальная игра… │
│ … │
│▌(Т) Таль ✓ ▐│ выбранный: фон secondaryContainer
│ Рижский волшебник: жертвы… │
│ … │
│ Характеры │ 48
│ (А) Аманда │
│ Сначала атакует, потом… │
│ … │
└────────────────────────────────────┘
```
- **Группы и порядок.** Первыми «Великие шахматисты» (22), затем «Характеры» (13). Имена шахматистов — главное, ради чего ставится Rodent IV («Таль», «Карпов»). Внутри группы — по алфавиту переведённых имён (на компьютере игроки упорядочены так же). Заголовки групп — `titleSmall` `primary`, `stickyHeader`.
- **Строка** — `ListItem` не ниже 72 dp: буквица слева (§3.2), имя (`bodyLarge`), описание (`bodyMedium` `onSurfaceVariant`, без ограничения строк — здесь как раз место прочитать его целиком). Выбранная строка: фон `secondaryContainer`, справа `check`. Размеров и отметок «скачано» в строках нет: книги одним пакетом, их состояние — в подвале листа.
- **Касание строки** выбирает и сразу закрывает экран (список одиночного выбора, M3 «simple dialog»). ← и системный «назад» закрывают без изменений. Кнопок «Готово» и «Отмена» нет.
- **Открывается прокрученным** так, чтобы выбранная строка была видна (третьей сверху, как отмеченная партия в списке, `android-lists.md` §10).
- **Поиска нет.** 35 строк в двух группах, около 4 экранов. Алфавит и заголовки находят «Карпова» быстрее, чем клавиатура. Если список вырастет за 60, вернуться к поиску.
- Без сети и без книг экран не меняется: выбор характера к сети не относится.
### 3.2. Буквица
Круг 40 dp с первой буквой переведённого имени (`titleMedium` 500). Цвет по группе: шахматисты — `tertiaryContainer` / `onTertiaryContainer`, характеры — `secondaryContainer` / `onSecondaryContainer`. Портретов нет: у портретов чемпионов разные и часто неясные лицензии, а рисовать «похожих» — хуже, чем букву. TalkBack буквицу не читает (декорация).
### 3.3. Список характеров
Ровно 35 характеров компьютерного списка `STYLES` с `rodent: Gen::IV` (id `iv_*`, имя для PGN, название и описание с переводами на 9 языков). Ampere и Swapper из `basic.ini` на компьютере не показаны (Ampere есть у V), на телефоне их тоже нет. Названия и описания берутся с компьютера, новых не придумывается. Единственное отличие: «Таль (классика)» на телефоне — просто «Таль» (ключ `Tal` в `i18n.rs` уже переведён), потому что второго Таля (V) здесь нет. Размеры — в приложении A.
### 3.4. Первое открытие
Первое касание карточки Rodent IV, пока `rodentPersonality` в настройках не записан, само открывает «С кем играть». Предложен и отмечен «Таль»: самое известное имя (вопрос 2). Больше экран сам не открывается никогда, даже если пользователь закрыл его без выбора (тогда записывается Таль).
## 4. Сила: две шкалы
- **У каждого движка своя память силы:** `maiaStrength` (есть) и `rodentStrength` (новое, впервые 1500). При переключении карточки ползунок встаёт на сохранённое значение этого движка. Так переход Maia ↔ Rodent ничего не портит: 2600 у Maia не обрезается до 2800 → 2600 при возврате и т. п. На компьютере сила одна, со сдвигом в диапазон (вопрос 5).
- **Диапазоны** — заявленные авторами (`decisions.md` «Сила соперника — по шкале самого движка»): Maia 600–2600 (`maia_range()`), Rodent IV 800–2800 (`RODENT_MIN`, `RODENT_IV_MAX` в `play.rs`, их нужно вынести в общий крейт `play`). Шаг 50, рисок нет. Концы подписаны числами слева и справа (как сейчас).
- **Заголовок** «Сила: {elo}» (`Strength:` с компьютера + число), `Tabular`, меняется при движении.
- **Пояснение под ползунком** — всегда 2 строки, строки компьютера: Maia — «Собственный рейтинг Maia: он не равен Эло человека.» (уже есть, `play_measured`); Rodent — «Собственный рейтинг Rodent (UCI_Elo): он не равен Эло человека.». Именно оно объясняет, почему у соседних карточек разные числа и почему Rodent 1500 ≠ Maia 1500.
- 2800 у Rodent IV — полная сила (без `UCI_LimitStrength`), как на компьютере. Подпись конца — «2800», не «макс.».
- Сила не зависит от характера (`UCI_Elo` и `Personality` разведены). Таль 1200 — это слабый игрок в стиле Таля; это сказано вводной фразой экрана «С кем играть».
## 5. Книги Rodent: один пакет
### 5.1. Решение владельца (2026-10-27)
Дебютные книги Rodent IV скачиваются **одним пакетом, один раз** (как на компьютере, где Rodent IV качается целиком), а не по характеру. После загрузки все 35 характеров играют со своими дебютами без сети. Вариант «книги каждого характера при первой партии с ним» рассмотрен и отклонён.
### 5.2. Факты для пакета
- Каталог `books/` авторов на зафиксированном коммите — **69,3 МБ**, но **35 характеров используют 59,0 МБ**. 10,3 МБ не нужны никому (`guide/ph-exoticbook.bin` 9,4 МБ, `main/*`, `flank`, `tricky`…). Расчёт — `apps/desktop/src/rodent4_files.rs` и `GuideBookFile`/`MainBookFile` из `personalities/*.txt` на коммите `e8d84c8`; по характерам — приложение A. **Рекомендация разработчику:** в пакет брать только используемые книги (59 МБ). Если проще взять общий с компьютером манифест целиком — 69 МБ; тексты берут размер из манифеста, поэтому от выбора не зависят.
- Три характера ссылаются на имя книги, которого в репозитории нет: Удав — `guide/strangler.bin` (в репозитории `Strangler.bin`; на Android файловая система различает регистр), Спасский — `ph_spassky2.bin` (в репозитории через дефис), Дебора — `guide/guide.bin` (в репозитории `books/guide.bin`). На компьютере это решено копией под нужным именем (`BOOK_NAMES` в `apps/desktop/src/rodent4_download.rs`). Телефону нужно то же самое, из общего кода.
- Источник — `raw.githubusercontent.com/nescitus/rodent-iv/<коммит>/books/…`, каждый файл с проверкой SHA-256 из общего с компьютером манифеста. Подпись «с github.com (файлы авторов)», как у Maia «с huggingface.co (файл авторов)».
- Лицензии части книг (Hase `ph-*`, Robinson `rj-*`) не уточнены (`research/rodent.md` §5, его вопрос 5). Программа скачивает их по кнопке из репозитория авторов, как на компьютере, а не раздаёт сама. Поэтому книги — не в APK (кроме того, APK вырос бы на 59 МБ, и лёгкая сборка потеряла бы смысл).
### 5.3. Где предлагается загрузка
1. **На листе**, когда выбран Rodent и книг нет: строка «Дебютные книги Rodent IV · 59 МБ…», кнопка «Скачать и играть», справа «Без книги» (§2.4). Путь тот же, что у Maia: после проверки партия начинается сама.
2. **В «Настройки → Движок»**: строка «Rodent IV — дебютные книги» с «Скачать» / «Удалить» (§7.2).
Подтверждения перед загрузкой на мобильной сети нет (у Maia его тоже нет): размер написан в строке, а кнопка — явное действие.
### 5.4. Как идёт загрузка
- Тот же механизм, что у Maia (`CheckedDownload`/`DownloadManager` в `filesDir`): одна полоса на весь пакет (сумма байт), «{a} из {b} МБ», затем «Проверка…». Закрытие листа загрузку не отменяет — она идёт в фоне с уведомлением (заголовок «Дебютные книги Rodent IV»). Отменяет только ✕.
- **Докачка.** Пакет — около 50 файлов, каждый проверяется отдельно. После ✕, обрыва или нехватки места проверенные файлы остаются, «Повторить» докачивает остаток, а строка показывает остаток. Пакет считается готовым, только когда на месте все файлы: частично скачанный пакет для игры — как «книг нет».
- **Нет места:** «Мало места: нужно {n} МБ, свободно {m} МБ» (существующая `no_space`).
### 5.5. «Без книги»
`TextButton` «Без книги» справа в строке состояния: при «книг нет» и при любой ошибке загрузки. Партия начинается без дебютной книги: движок, характер и сила те же. Над нотацией ничего не пишется. В PGN имя то же (`Rodent IV 1800 (Tal)`): книга — дебютный репертуар соперника, а не он сам. Без книги шахматисты теряют свои дебюты (`research/rodent.md` §4), поэтому кнопка второстепенная (текстовая), а главная — «Скачать и играть». Это явный выбор пользователя, а не молчаливая подмена, поэтому правило «без обходных путей» не нарушается (вопрос 3). Нужна она затем, чтобы в самолёте и на дорогом трафике Rodent IV — единственный соперник, который не требует сети, — всё же играл. У Maia такой кнопки нет: без файла Maia не играет вовсе.
Сделанный выбор «Без книги» не запоминается: в следующий раз лист снова предлагает скачать.
## 6. В партии
### 6.1. Экран игры
Как §31.3. Меняются только имена:
```
│ ← Партия с Rodent IV 1800 │ 64 titleLarge
│ Таль · вы белыми · без часов │ bodyMedium
├────────────────────────────────────┤
│ ● Rodent IV 1800 · Таль ◌ думает… │ 36 плашка соперника
```
- **Заголовок:** «Партия с {соперник}», где {соперник} = «Maia 1500» / «Rodent IV 1800» (строка `play_adjourned_title`, которая уже есть, — один и тот же шаблон для карточки, вопроса и заголовка). Вторая строка — «{характер} · вы белыми · без часов»; у Maia, как сейчас, без характера.
- Сейчас заголовок у Maia — «Играть с Maia 1500» (`play_with_maia` + сила). Предлагаю у обоих «Партия с …»: это название, а не команда.
- **Плашка:** «Rodent IV 1800 · Таль». Если не помещается рядом с «думает…», обрезается имя характера («Rodent IV 1800 · Рубинш…»), число силы не обрезается никогда. TalkBack: «Rodent IV 1800, Таль, думает».
- **Темп.** Rodent на ограничении силы отвечает почти мгновенно, поэтому пауза «как человек» общая с Maia (`pause`), как на компьютере. На 2800 (полная сила) — лимит времени на ход из общего крейта (на компьютере 0,5 с). «думает…» появляется после 300 мс, как у Maia.
- Ход назад, просмотр, поворот экрана, фон — без изменений. Rodent — дочерний процесс UCI (`crates/uci`) с остановкой и таймаутами; ответ на старую позицию не применяется (инварианты AGENTS.md).
### 6.2. Ничья, сдача, конец
Те же правила и Stockfish (`play::hopeless`, `accepts_draw`). В лёгкой сборке без скачанной сети Rodent, как Maia, не сдаётся и отвечает на ничью строкой «…с помощью Stockfish». Тексты — пары к строкам Maia (§9): «Rodent сдаётся» / «Его позиция проиграна…», «Rodent отказывается от ничьей», «Rodent сдался» (причина конца). Род согласуется, поэтому строки отдельные, а не `{name}` (`rodent-opponent.md` §7).
### 6.3. Запись партии
Как на компьютере (крейт `play`): `White`/`Black` — `Rodent IV 1800 (Tal)` (английское имя характера, PGN — формат обмена, не переводится), `…Type "program"`, `Event` «Партия с компьютером». В базу игрока пишется так же, как партия с Maia (`player-games.md`).
### 6.4. Реванш, «Новая игра», «Играть отсюда»
- «Реванш» — §1.6. «Новая игра» (⋮) открывает лист с этим же соперником.
- Пункт листа хода «Играть отсюда с Maia…» (`play_from_maia`) становится «Играть отсюда…» (`play_from_here`, строка уже есть): соперник выбирается на листе. TalkBack-действие — так же.
### 6.5. Отложенная партия
- Карточка (`android-lists.md` §5.4): «Партия с Rodent IV 1800» / «Таль · вы белыми · 6-й ход». У Maia вторая строка прежняя. TalkBack: «Отложенная партия с Rodent IV 1800, Таль, вы белыми, 6-й ход. Продолжить, кнопка».
- Вопрос при новой игре: «Есть отложенная партия с Rodent IV 1800» — «Продолжить её» · «Начать новую», как сейчас.
- Разработчику: в `PlayMeta` (`data/MaiaGames.kt`) добавить соперника (`maia` | `rodent4`) и id характера (`iv_tal`). Партия, отложенная до обновления, без этих полей — партия с Maia. Название класса (`MaiaGames`) можно оставить, но смысл теперь «партия с компьютером».
### 6.6. Сбои
- **Rodent не запустился** (не та ABI, повреждён APK): карточка в партии «Rodent не запустился.» — «Перезапустить» · «Прервать» (`play-mode.md` §3.8). Скачать его заново нельзя (он в APK), поэтому кнопки «Скачать заново», как у Maia, нет.
- **Книга не читается** (файл повреждён после проверки): движок играет без неё. Это не ошибка для пользователя; в журнал приложения пишется предупреждение.
## 7. Что запоминается
### 7.1. Настройки (`app.settings.prefs`)
| Ключ | Значение | Впервые | Когда пишется |
|---|---|---|---|
| `opponent` | `maia` \| `rodent4` | `maia` | при «Играть» (и «Без книги») |
| `maiaStrength` | 600–2600 (есть) | 1500 | при «Играть» с Maia |
| `rodentStrength` | 800–2800 | 1500 | при «Играть» с Rodent |
| `rodentPersonality` | id компьютера (`iv_tal`…) | нет → при первом выборе Rodent предлагается `iv_tal` и открывается список (§3.4) | при выборе в списке или закрытии списка, открытого в первый раз |
| `maiaColor` → лучше переименовать в `playColor` | 1 / 0 / −1 | 0 | при «Играть», кроме «Играть отсюда» (как сейчас) |
| `yourName` | есть | — | как сейчас |
- Ползунок и карточки при закрытии листа без «Играть» **не** запоминаются (как сейчас: сила пишется при «Играть»). Характер запоминается сразу при выборе: выбор в отдельном экране — уже осознанное действие, и терять его было бы обидно.
- Неизвестный id характера (из будущей версии) — `iv_tal`.
### 7.2. «Настройки → Движок»
Под строкой Maia (§31.2) — строка «Rodent IV — дебютные книги»:
- вторая строка: «скачаны · 59 МБ» / «не скачаны · 59 МБ»; справа действие «Скачать» или «Удалить»; во время загрузки — полоса «{a} из {b} МБ» и ✕;
- «Удалить» без диалога, снекбар «Книги удалены» (без «Вернуть»: восстановление — та же загрузка). Пока идёт партия с Rodent, «Удалить» неактивна (как у Maia);
- о самом движке строки нет: он в приложении, удалить его нельзя.
## 8. Ориентация, планшет, доступность
### 8.1. Альбомная ориентация и планшет
- **Телефон в альбомной ориентации** (800×360): лист на всю высоту, подвал закреплён (≈ 128 dp), прокручиваемой части ≈ 200 dp. Карточки и строка характера те же. Лист `ModalBottomSheet` шириной не больше 640 dp (так в M3 по умолчанию).
- **Планшет** (средний и расширенный класс, `android-ui.md` §13): лист тот же, по центру, до 640 dp. «С кем играть» на ширине от 600 dp — не полноэкранный, а обычный `Dialog` 560 × до 90 % высоты, с той же верхней панелью (M3: полноэкранные диалоги только на компактной ширине).
### 8.2. Доступность и TalkBack
- **Карточки соперника** — `selectableGroup`, роль `RadioButton`: «Maia, играет как человек, выбрано» / «Rodent IV, сильный, со стилем, не выбрано».
- **Строка характера** (Rodent) — одна кнопка: «Характер: Таль. Рижский волшебник: жертвы и атака. Изменить, кнопка» (`onClickLabel` «Изменить»). Для Maia строка читается как текст, без роли кнопки: «Как человек. Maia не выбирает стиль…».
- **Ползунок:** `contentDescription` «Сила», значение «1800, от 800 до 2800». Смена соперника объявляется (`liveRegion` polite у заголовка «Сила»): «Сила: 1800».
- **«С кем играть»:** строки — `selectable` с ролью `RadioButton`: «Таль, великий шахматист. Рижский волшебник: жертвы и атака. Выбрано». Заголовки групп — `heading()`. ← — «Назад».
- **Строка состояния** — `liveRegion` polite, но объявляются только смены состояния («Скачивание», «Проверка», «Скачано», ошибка), а не каждый процент. ✕ — «Отменить скачивание». «Без книги» — «Играть без дебютной книги».
- **Цели касания:** карточки 64, строки 72–80, ✕ и «Без книги» 48 — всё не меньше 48 dp.
- **Шрифт 200 %:** высоты строк растут (min, а не фиксированные значения). Лист прокручивается, подвал остаётся видимым. Описания в строке характера — максимум 2 строки с «…», полный текст в списке и TalkBack.
- Выбор отмечается не только цветом: ✓ на карточке и в списке.
- Клавиатура (аппаратная): порядок фокуса — карточки → строка характера → ползунок (стрелки ±50) → цвет → имя → «Играть». Enter на строке открывает список; в списке стрелки и Enter, Esc = назад. Специально под клавиатуру ничего не делается.
## 9. Тексты RU / EN
Где строка совпадает с компьютерной (`i18n.rs`), она и её переводы на все 9 языков берутся оттуда — в таблице отмечено «комп.». Остальные новые, их переводят на 7 языков.
**Имена и описания характеров** (35 пар) — без изменений с компьютера: `title` и `about` записей `iv_*` в `STYLES` (например, «Удав» / «Удав: медленно душит, очень по-человечески.», «Strangler» / «A boa constrictor: squeezes slowly, very human-like.»). Исключение: `iv_tal` на телефоне называется ключом `Tal` («Таль»), а не `Tal (classic)`.
| Ключ (предложение) | RU | EN | Источник |
|---|---|---|---|
| `play_title` | Игра с компьютером | (как сейчас) | есть |
| `play_button` (кнопка на «Базах», вместо `play_with_maia`) | Играть | Play | новое; TalkBack: `play_button_cd` «Играть с компьютером» / «Play the computer» |
| `opp_maia_sub` | играет как человек | plays like a human | комп. |
| `opp_rodent_sub` | сильный, со стилем | strong, with a style | комп. |
| `like_human` | Как человек | Like a human | комп. |
| `maia_no_style` | Maia не выбирает стиль: она играет, как люди её рейтинга. | Maia does not pick a style: she plays like people of her rating. | комп. |
| `strength_n` | Сила: {elo} | Strength: {elo} | комп. `Strength:` + число |
| `rodent_measured` | Собственный рейтинг Rodent (UCI_Elo): он не равен Эло человека. | Rodent's own rating (UCI_Elo): it does not match a person's Elo. | комп. |
| `pick_title` | С кем играть | Who to play | новое |
| `pick_intro` | Характер — это стиль и дебюты, силу задаёт ползунок. Книги дебютов скачиваются при первой партии; их размер — справа. | A character is a style and openings; the slider sets the strength. Opening books are downloaded for the first game; their size is on the right. | новое |
| `pick_players` | Великие шахматисты | Great players | новое |
| `pick_characters` | Характеры | Characters | новое (комп. `Character` — ед. число) |
| `pick_change` | Изменить | Change | новое (TalkBack) |
| `pick_row_cd` | {name}, великий шахматист / {name}, характер | {name}, great player / {name}, character | новое (TalkBack) |
| `books_ready` | Rodent IV и его дебютные книги на телефоне | Rodent IV and its opening books are on the phone | новое |
| `books_offer` | Дебютные книги Rodent IV: {mb} МБ, скачиваются один раз с github.com | Rodent IV opening books: {mb} MB, downloaded once from github.com | новое (короче: строка делит место с «Без книги») |
| `books_not_needed` | С позиции дебютная книга не нужна — Rodent IV играет сразу | From a position no opening book is needed: Rodent IV plays at once | новое |
| `books_without` | Без книги | No book | новое; TalkBack `books_without_cd` «Без книги: играть без дебютной книги» / «No book: play without the opening book» |
| `books_notification` | Дебютные книги Rodent IV | Rodent IV opening books | новое (заголовок уведомления загрузки) |
| `books_settings` | Rodent IV — дебютные книги | Rodent IV — opening books | новое |
| `books_settings_sub` | скачаны · {mb} МБ / не скачаны · {mb} МБ | downloaded · {mb} MB / not downloaded · {mb} MB | новое |
| `books_deleted` | Дебютные книги удалены | Opening books deleted | новое; TalkBack «Удалить» — `books_delete_cd` «Удалить дебютные книги» / «Delete the opening books» |
| `play_adjourned_title` | Партия с {opponent} | Game against {opponent} | меняется: было «…с Maia %1$s»; {opponent} = «Maia 1500» / «Rodent IV 1800» |
| `play_adjourned_q` | Есть отложенная партия с {opponent} | There is a game put aside against {opponent} | меняется так же |
| `play_sub_style` | {style} · вы {colour} · без часов | {style} · you play {colour} · no clock | новое (заголовок игры, Rodent) |
| `play_card_sub_style` | {style} · вы {colour} · {n}-й ход | {style} · you play {colour} · move {n} | новое (карточка, Rodent) |
| `rodent_resigns` | Rodent сдаётся | Rodent resigns | комп. |
| `rodent_position_lost` | Его позиция проиграна. Принять победу или доиграть? | Its position is lost. Accept the win, or play to the end? | EN — комп.; RU как у Maia на телефоне (`play_her_position_lost`), на компьютере «…играть до конца?» |
| `end_rodent_resigned` | Rodent сдался | Rodent resigned | комп. |
| `rodent_draw_declined` | Rodent отказывается от ничьей | Rodent declines the draw | комп. |
| `rodent_draw_later` | Rodent отказался; снова можно предложить через два его хода | Rodent declined; offer again after two of its moves | комп. |
| `rodent_draw_no_engine` | Rodent отвечает на ничью с помощью Stockfish: скачайте его кнопкой «Движок» | Rodent answers a draw offer with Stockfish: download it in the game screen («Engine») | новое (пара к `play_draw_no_engine`) |
| `rodent_stopped_playing` | Rodent остановился во время игры. | Rodent stopped during the game. | комп. «it stopped while playing» (процесс оборвался посреди партии) |
| `rodent_stopped` | Rodent не запустился. | Rodent did not start. | новое (пара к `play_maia_stopped`); комп. `Rodent did not start: {e}` — для журнала |
| `play_note_from_rodent` | Дальше — игра с Rodent IV {elo} · {style}. | From here on, a game against Rodent IV {elo} · {style}. | новое (пара к `play_note_from`, комментарий в PGN «Играть отсюда») |
| `record_games` | Записывать партии с компьютером в базу игрока | Write games against the computer to the player's database | меняется (было «с Maia»), текст из `player-games.md` §8 |
| `own_empty` | Здесь будут партии, которые вы введёте или сыграете с компьютером | Games you enter or play against the computer will be here | меняется |
Существующие строки без изменений: `play_download_and_play`, `play_play`, `play_retry`, `play_checking`, `downloaded_of`, `cancel_download`, `no_internet`, `interrupted`, `no_space`, `corrupt`, `play_from_here`, `play_continue_it`, `play_start_new`.
## 10. Критерии приёмки (для тестировщика)
**Лист**
1. Первый запуск: лист открыт с выбранной Maia, «Сила: 1500», концы 600 / 2600, строка характера неактивна и читает «Как человек».
2. Касание «Rodent IV» в первый раз само открывает «С кем играть»; Таль отмечен и виден без прокрутки. «Назад» → на листе «Таль». Второе касание Maia → Rodent экран больше не открывает.
3. Переключение Maia ↔ Rodent: снимки листа совпадают по высоте и положению кнопки «Играть» до пикселя (снимки до/после, оба соперника, все состояния строки состояния).
4. Maia 2400 → Rodent 1200 → обратно: у Maia снова 2400, у Rodent 1200. Концы и пояснение под ползунком меняются вместе с соперником.
5. Выбор «Карпов» в списке сразу закрывает экран; строка характера показывает имя и описание с компьютера; после перезапуска приложения выбран Карпов.
6. Все 35 характеров есть, 22 в «Великих шахматистах» и 13 в «Характерах», по алфавиту в языке интерфейса; описания совпадают с компьютерными на всех 9 языках.
7. С открытой клавиатурой (поле имени) кнопка «Играть» видна над клавиатурой.
**Книги**
8. Чистая установка, выбран Rodent: строка «Дебютные книги Rodent IV · 59 МБ…» и «Без книги»; «Скачать и играть» → полоса → «Проверка…» → партия начинается сама. Скачаны все книги, которые называют 35 характеров (и только они, если принят пакет 59 МБ), суммы SHA-256 совпадают с манифестом.
9. После загрузки смена характера (любой из 35) не предлагает ничего скачивать; «Играть» сразу, в том числе в режиме полёта.
10. Удав, Спасский, Дебора действительно открывают свою книгу (первый ход из книги-гида, проверка журналом UCI движка), несмотря на имена в их файлах.
11. ✕ на середине: проверенные файлы остались, «Скачать и играть» показывает остаток и докачивает только его; частичный пакет не считается готовым.
12. Режим полёта, книг нет: «Скачать и играть» → «Не удалось скачать: нет соединения», «Повторить» и «Без книги». «Без книги» начинает партию; в PGN `Rodent IV {сила} ({Name})`. В следующий раз лист снова предлагает скачать.
13. Смена характера во время загрузки: загрузка продолжается, по окончании партия начинается с новым характером. Переход на Maia во время загрузки: загрузка идёт в фоне, партия сама не начинается.
14. «Играть отсюда» с Rodent без книг: «Играть» сразу, без загрузки.
15. «Настройки → Движок»: «Скачать» качает тот же пакет (общий с листом, вторая загрузка не начинается параллельно); «Удалить» удаляет все книги, лист снова предлагает скачать; во время партии с Rodent «Удалить» неактивна.
16. Ни один файл книг не лежит в APK; движок лежит в обеих сборках и запускается без сети.
**Партия**
17. Плашка «Rodent IV 1800 · Таль», заголовок «Партия с Rodent IV 1800» / «Таль · вы белыми · без часов»; на 360 dp при «думает…» обрезается имя характера, не сила.
18. Сила реально передаётся: `UCI_LimitStrength true`, `UCI_Elo 1800`; на 2800 ограничения нет. Характер — опцией движка; книга — из папки на телефоне.
19. Ход назад во время расчёта Rodent: ответ старой позиции не применяется (гонка UCI). «Прервать», «Сдаться», конец партии и реванш (тот же характер и сила, цвета меняются) работают как у Maia.
20. «Назад» в середине партии → карточка «Партия с Rodent IV 1800» / «Таль · вы белыми · {n}-й ход»; убить процесс приложения → карточка та же; «Продолжить» → тот же характер и сила, позиция та же. Удалить книги, затем «Продолжить» — партия продолжается без вопросов.
21. Партия, отложенная версией без Rodent, после обновления продолжается как партия с Maia.
22. Тексты сдачи и ничьей у Rodent — свои («Rodent сдаётся», «Его позиция…»), не «Maia».
23. Запись в базу игрока: `White`/`Black` `Rodent IV 1800 (Tal)`, `…Type "program"`.
**Доступность и вид**
24. TalkBack: карточки — переключатели с «выбрано»; строка характера — одна кнопка с именем и описанием; строки списка читают имя, группу и описание; ползунок — «Сила, 1800, от 800 до 2800».
25. Шрифт 200 %, обе темы, альбомная ориентация телефона, планшет (список — диалог 560 dp): ничего не обрезается без «…», подвал виден.
## 11. Вопросы владельцу
1. **Кто выбран при первом открытии листа — Maia, как сейчас?** Рекомендую Maia: прежние пользователи ничего не теряют, а карточка Rodent IV стоит рядом на виду. Другой вариант — ничего не выбирать и попросить выбрать; это лишнее касание каждому новичку.
2. **Первый характер Rodent — Таль, и при первом выборе Rodent список открывается сам?** Рекомендую да: Таль — самое узнаваемое имя, а список сразу показывает, сколько всего характеров.
3. **Кнопка «Без книги» рядом с «Скачать и играть»?** Рекомендую да: 59 МБ на мобильной сети или в самолёте — серьёзный барьер, а движок в приложении играть может; пользователь сам видит, что дебютов не будет.
4. **С позиции играть без загрузки книг?** Рекомендую да: книга почти не нужна в середине партии, а ждать загрузку ради неё странно.
5. **Сила у Maia и Rodent запоминается отдельно (на компьютере одна общая)?** Рекомендую отдельно: шкалы разные, общая сила при переключениях обрезается и теряется. Если нравится, позже так же сделать на компьютере.
6. **Кнопка на «Базах»: «Играть» (со значком робота) вместо «Играть с Maia»?** Рекомендую «Играть»: «Играть с компьютером» в кнопку шириной 158 dp не помещается в одну строку.
## Приложение A. Книги характеров (коммит `e8d84c8`)
Какие книги нужны каждому характеру (книга-гид + основная) и сколько это с нуля — справочно, для состава пакета и проверки (критерии 8, 10). Пакет — их объединение.
**Великие шахматисты** (основная книга — эпоха):
| id | RU | Гид | Основная | МБ |
|---|---|---|---|---|
| iv_alekhine | Алехин | players/rj-alekhine 0,87 | hist/_pre30 0,17 | 1,0 |
| iv_anand | Ананд | players/ph-anand2 2,00 | hist/_post06 1,47 | 3,5 |
| iv_anderssen | Андерсен | players/ph-anderssen2 8,54 | hist/_pre30 | 8,7 |
| iv_bosboom | Босбум | players/bn-bosboom 0,54 | hist/_post06 | 2,0 |
| iv_botvinnik | Ботвинник | players/ph-botvinnik2 1,76 | hist/_31to80 0,59 | 2,4 |
| iv_kasparov | Каспаров | players/rj-kasparov 1,62 | hist/_81to06 1,39 | 3,0 |
| iv_karpov | Карпов | players/ph-karpov2 2,29 | hist/_81to06 | 3,7 |
| iv_kortchnoi | Корчной | players/rj-kortchnoi 0,14 | hist/_31to80 | 0,7 |
| iv_larsen | Ларсен | players/ph-larsen2 2,09 | hist/_31to80 | 2,7 |
| iv_lasker | Ласкер | players/ph-lasker2 1,75 | hist/_pre30 | 1,9 |
| iv_marshall | Маршалл | players/rj-marshall 0,30 | hist/_pre30 | 0,5 |
| iv_morphy | Морфи | players/morphy 0,001 | hist/_pre30 | 0,2 |
| iv_nimzowitsch | Нимцович | players/nimzowitsch 0,26 | hist/_pre30 | 0,4 |
| iv_petrosian | Петросян | players/petrosian 0,85 | hist/_31to80 | 1,4 |
| iv_reti | Рети | players/ph-reti2 1,64 | hist/_pre30 | 1,8 |
| iv_rubinstein | Рубинштейн | players/ph-rubinstein2 1,71 | hist/_pre30 | 1,9 |
| iv_spassky | Спасский | players/ph-spassky2 2,02 (в файле `ph_spassky2`) | hist/_31to80 | 2,6 |
| iv_steinitz | Стейниц | players/steinitz 0,08 | hist/_pre30 | 0,3 |
| iv_tal | Таль | players/ph-tal2 2,06 | hist/_31to80 | 2,7 |
| iv_tarrasch | Тарраш | players/ph-tarrasch2 1,68 | hist/_pre30 | 1,8 |
| iv_topalov | Топалов | players/ph-topalov2 1,83 | hist/_post06 | 3,3 |
| iv_fischer | Фишер | players/ph-fischer2 1,73 | hist/_31to80 | 2,3 |
Все 22 вместе — 39,4 МБ.
**Характеры** (основная книга у всех — `rodent.bin` 10,18 МБ):
| id | RU | Гид | МБ с нуля |
|---|---|---|---|
| iv_amanda | Аманда | guide/ph-gambitbook 8,41 | 18,6 |
| iv_cloe | Клои | guide/closed 0,001 | 10,2 |
| iv_deborah | Дебора | books/guide.bin 0,003 (в файле `guide/guide.bin`) | 10,2 |
| iv_defender | Защитник | guide/solid 0,70 | 10,9 |
| iv_dynamic | Динамик | guide/active 0,30 | 10,5 |
| iv_grumpy | Ворчун | guide/grandpa 0,01 | 10,2 |
| iv_partisan | Партизан | guide/low 0,002 | 10,2 |
| iv_pawnsacker | Гамбитист | rodent.bin (гид = основная) | 10,2 |
| iv_pedrita | Педрита | guide/solid | 10,9 |
| iv_preston | Престон | guide/cs 0,004 | 10,2 |
| iv_simple | Простак | guide/simple 0,001 | 10,2 |
| iv_spitfire | Задира | guide/active | 10,5 |
| iv_strangler | Удав | guide/Strangler 0,01 (в файле `strangler`) | 10,2 |
Все 13 вместе — 19,6 МБ. После первого характера (кроме Аманды) остальные обычно добавляют от 0,01 до 0,7 МБ.
**Итого:** нужно 35 характерам — 59,0 МБ; весь каталог `books/` — 69,3 МБ.

View file

@ -0,0 +1,41 @@
Android (NDK, bionic): no wordexp.h. The authors' sources leave out the wordexp code only
when ANDROID is defined, which also selects their /sdcard/Rodent4 home folder; NDK clang
defines __ANDROID__, so leave it out for that too and keep the RODENT4HOME home folder.
Only the RODENT4BOOKS/RODENT4PERSONALITIES overrides go (ChDirEnv is false), as in the
authors' Android build.
diff --git a/sources/src/rodent.h b/sources/src/rodent.h
index 30ccf22..8580d86 100755
--- a/sources/src/rodent.h
+++ b/sources/src/rodent.h
@@ -1078,7 +1078,7 @@ extern const int ph_value[7];
#endif
void PrintOverrides();
// change dir and return true on success
- #ifndef ANDROID
+ #if !defined(ANDROID) && !defined(__ANDROID__)
bool ChDirEnv(const char *env_name);
#else
#define ChDirEnv(dummy) false
diff --git a/sources/src/util.cpp b/sources/src/util.cpp
index b0a028b..e32be00 100644
--- a/sources/src/util.cpp
+++ b/sources/src/util.cpp
@@ -28,7 +28,7 @@ If not, see <http://www.gnu.org/licenses/>.
#else
#include <unistd.h>
#include <sys/time.h>
- #ifndef ANDROID
+ #if !defined(ANDROID) && !defined(__ANDROID__) // bionic has no wordexp
#include <wordexp.h>
#endif
#endif
@@ -330,7 +330,7 @@ void PrintOverrides() {
if (char *ptr = getenv("RODENT4PERSONALITIES"))
printfUciOut("info string override for personalities path: '%s'\n", ptr);
}
-#ifndef ANDROID
+#if !defined(ANDROID) && !defined(__ANDROID__)
bool ChDirEnv(const char *env_name) {
char *env_path;
env_path = getenv(env_name);

View file

@ -0,0 +1,18 @@
The search thread's lambda took the parameter p by reference, and StartThinkThread
returns at once: the thread then read p from a dead stack frame. GCC builds happened
to work; clang builds (the NDK's, AddressSanitizer: stack-use-after-return) searched
garbage and answered illegal moves (bestmove a1b1 from the start). Take p by value.
diff --git a/sources/src/rodent.h b/sources/src/rodent.h
index 30ccf22..3e100a0 100755
--- a/sources/src/rodent.h
+++ b/sources/src/rodent.h
@@ -981,7 +981,7 @@ class cEngine {
std::thread mWorker;
void StartThinkThread(POS *p) {
mDpCompleted = 0;
- mWorker = std::thread([&] { Think(p); });
+ mWorker = std::thread([this, p] { Think(p); });
}
~cEngine() { WaitThinkThread(); }; // should fix crash on windows on console closing

View file

@ -1,11 +1,16 @@
#!/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.
and the books each personality opens, written as crates/play/src/rodent4_files.rs (the
desktop and the phone download from it).
git clone https://github.com/nescitus/rodent-iv /tmp/rodent-iv
git -C /tmp/rodent-iv checkout <COMMIT>
python3 -I scripts/rodent4-manifest.py /tmp/rodent-iv
An unpacked archive of the commit (no git) is read too, with the commit given:
python3 -I scripts/rodent4-manifest.py /tmp/rodent-iv-<COMMIT> <COMMIT>
"""
import hashlib
import os
@ -14,7 +19,10 @@ 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()
if len(sys.argv) > 2:
commit = sys.argv[2]
else:
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)):
@ -27,6 +35,29 @@ for top in ("personalities", "books"):
data = open(path, "rb").read()
files.append((rel, len(data), hashlib.sha256(data).hexdigest()))
files.sort()
# The personalities of the list the engine offers (basic.ini, PERSONALITY_SET=all) and the
# books each one opens, named as its file names them (under books/).
personalities = []
section = None
for line in open(os.path.join(repo, "personalities", "basic.ini"), encoding="latin-1"):
line = line.strip()
if line.startswith("PERSONALITY_SET="):
section = line.split("=", 1)[1]
elif section == "all" and "=" in line and not line.startswith(("#", ";")):
name, file = line.split("=", 1)
# basic.ini names one more than the repository has (classicist.txt).
if not os.path.isfile(os.path.join(repo, "personalities", file)):
continue
books = {}
for opt in open(os.path.join(repo, "personalities", file), encoding="latin-1"):
words = opt.split()
if len(words) >= 5 and words[:2] == ["setoption", "name"] and words[3] == "value":
if words[2] in ("GuideBookFile", "MainBookFile"):
books[words[2]] = words[4]
personalities.append((name, books["GuideBookFile"], books["MainBookFile"]))
personalities.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",
@ -38,6 +69,14 @@ out = [
"pub const FILES: &[(&str, u64, &str)] = &[",
]
out += [f' ("{p}", {s}, "{h}"),' for p, s, h in files]
out += [
"];",
"",
"/// The personalities of the engine's list: (name, guide book, main book), the books",
"/// as the personality's file names them (under `books/`).",
"pub const PERSONALITY_BOOKS: &[(&str, &str, &str)] = &[",
]
out += [f' ("{n}", "{g}", "{m}"),' for n, g, m in personalities]
out += ["];", ""]
open(os.path.join(root, "apps", "desktop", "src", "rodent4_files.rs"), "w").write("\n".join(out))
open(os.path.join(root, "crates", "play", "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)