diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a0c7a3..5af9783 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 81c6c26..f280bcc 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -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) diff --git a/androidApp/app/build.gradle.kts b/androidApp/app/build.gradle.kts index f283633..55d5d9e 100644 --- a/androidApp/app/build.gradle.kts +++ b/androidApp/app/build.gradle.kts @@ -68,6 +68,17 @@ val stockfish = tasks.register("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("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("bundleAssets") { @@ -95,7 +106,14 @@ val bundleAssets = tasks.register("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 { diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt index 0786ed6..d0b2b30 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt @@ -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) } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt index 62028be..295b566 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/CheckedDownload.kt @@ -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 -> { diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt index 166b0ce..ac49c80 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt @@ -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 } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/RodentFiles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/RodentFiles.kt new file mode 100644 index 0000000..8d38fe1 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/RodentFiles.kt @@ -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 = 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(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 = _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 + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt index 271637d..5236d82 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt @@ -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) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt index 298ef14..8e5c50f 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/AboutScreen.kt @@ -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", diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt index 4816f0e..5ca8204 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt @@ -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) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt index 1a53c4a..078116c 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -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), diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt index 00f745a..21a8267 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt @@ -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(null) - /// Maia failed to start: why. - val failure = mutableStateOf(null) + /// The opponent does not play: why. + val failure = mutableStateOf(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)) } }, diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt index 1a40c75..6ae4900 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt @@ -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, 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 + }) } } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/RodentStyles.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/RodentStyles.kt new file mode 100644 index 0000000..52e9def --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/RodentStyles.kt @@ -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> = 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" diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt index e65eccb..7e2fdfa 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SettingsScreen.kt @@ -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, val selected: Int, val hint: Int? = null, val pick: (Int) -> Unit) @Composable diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index a4572d9..23b6a2c 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -396,7 +396,7 @@ Neue Partie Meine Datenbanken + Neue Datenbank - Hier stehen die Partien, die Sie eingeben oder gegen Maia spielen + Hier stehen die Partien, die Sie eingeben oder gegen den Computer spielen Dateien Meine Partien Neue Datenbank @@ -479,7 +479,6 @@ Weiß Schwarz Zufällig - Gegner — Maia %1$s Die eigene Wertung von Maia: sie entspricht nicht der Elo eines Menschen. Maia wird einmalig heruntergeladen (%1$s MB, von huggingface.co, die Datei der Autoren selbst). Herunterladen und spielen @@ -496,7 +495,6 @@ Maia gibt auf Ab hier eine Partie gegen Maia %1$s. Abbrechen - Gegen Maia spielen Ihr Name Maia ist heruntergeladen Erneut versuchen @@ -511,7 +509,6 @@ ✓ Gespeichert Speichern… Sie spielen %1$s · %2$s - Von hier gegen Maia weiterspielen… Nach %1$s Ton Rückgängig @@ -523,7 +520,7 @@ die Ausgangsstellung Maia ist nicht gestartet. Maia neu herunterladen - Eine Partie gegen Maia %1$s ist zurückgestellt + Eine Partie gegen %1$s ist zurückgestellt Fortsetzen Neue beginnen Eine neue Partie ersetzt sie; das Gespielte kommt unvollendet in die Datenbank des Spielers. @@ -537,7 +534,7 @@ ✓ In „%1$s“, Nr. %2$s › Partie unvollendet in „%1$s“ gespeichert werden selbst gespeichert - Partien gegen Maia in die Datenbank des Spielers schreiben + Partien gegen den Computer in die Datenbank des Spielers schreiben Partien werden in „%1$s“ gespeichert Die Partien werden in eine neue Datenbank „%1$s“ gespeichert. Ohne Namen gehen die Partien in „%1$s“. Geben Sie einen Namen ein, um eine eigene Datenbank zu bekommen. @@ -546,6 +543,116 @@ Konnte nicht in „%1$s“ schreiben: %2$s Eine neue Partie ersetzt sie. Zuletzt geöffnet - Partie gegen Maia %1$s + Partie gegen %1$s Zug %1$d + + Amanda + Greift zuerst an, spielt dann auf aktive Figuren. + Cloe + Mag geschlossene Stellungen. + Deborah + Verteidigt gut und mag ihre Läufer. + Verteidiger + Solide und vorsichtig; mit Remis zufrieden. + Dynamiker + Greift an, mag Läufer, opfert ab und zu. + Brummbär + Angriff und Einengung; mag blockierte Stellungen, meidet Remis. + Partisan + Greift nach ruhigen, unauffälligen Eröffnungen an. + Bauernopferer + Ausgewogen, gibt aber eher Bauern her. + Pedrita + Bauern, Verteidigung und Einengung. + Preston + Ein materialistischer, maßvoller Angreifer. + Schlicht + Am computerhaftesten: schlichtes, solides Schach. + Hitzkopf + Scharf und aggressiv. + Würger + Eine Würgeschlange: würgt langsam, sehr menschlich. + Aljechin + Dynamische Angriffe und tiefe Kombinationen. + Anand + Schnelles, universelles Spiel mit scharfen Eröffnungen. + Anderssen + Ein romantischer Angreifer des 19. Jahrhunderts: Opfer. + Bosboom + Ausgefallene Eröffnungen und kreatives Blitzspiel. + Botvinnik + Wissenschaftliches, strategisches Spiel aus tiefer Vorbereitung. + Fischer + Klar, klassisch und präzise. + Karpov + Positioneller Druck, Prophylaxe und Technik. + Kasparov + Initiative und kraftvoller Angriff. + Kortchnoi + Ein zäher Verteidiger und Konterspieler. + Larsen + Originell und riskant, mit ausgefallenen Eröffnungen. + Lasker + Ein praktischer, psychologischer Kämpfer. + Marshall + Ein verwegener Angreifer mit Gambits. + Morphy + Schnelle Entwicklung und offene Linien. + Nimzowitsch + Einengung, Blockade und Überdeckung. + Petrosian + Prophylaxe und Sicherheit zuerst. + Reti + Hypermodern: kontrolliert das Zentrum aus der Ferne. + Rubinstein + Klassisches Positionsspiel, stark im Endspiel. + Spassky + Ein Universalspieler, in jeder Stellung zu Hause. + Steinitz + Der Begründer des Positionsspiels, ein hartnäckiger Verteidiger. + Tal + Der Zauberer aus Riga: Opfer und Angriff. + Tarrasch + Klassische Regeln: Raum, Entwicklung, aktive Figuren. + Topalov + Aggressiv und dynamisch, opfert die Qualität. + spielt wie ein Mensch + stark, mit Stil + Wie ein Mensch + Maia wählt keinen Stil: Sie spielt wie Menschen ihrer Wertung. + Die eigene Wertung von Rodent (UCI_Elo): sie entspricht nicht der Elo eines Menschen. + Rodent gibt auf + Rodent hat aufgegeben + Rodent lehnt das Remis ab + Rodent hat abgelehnt; nach zwei seiner Züge wieder anbieten + Seine Stellung ist verloren. Sieg annehmen oder zu Ende spielen? + Spielen + Gegen den Computer spielen + Spielstärke: %1$s + Gegen wen spielen + Ein Charakter ist ein Stil mit seinen Eröffnungen; die Spielstärke stellt der Schieberegler ein. + Große Spieler + Charaktere + Ändern + %1$s, großer Spieler + %1$s, Charakter + Charakter: %1$s + Rodent IV und seine Eröffnungsbücher sind auf dem Telefon + Eröffnungsbücher von Rodent IV: %1$s MB, einmalig von github.com + Aus einer Stellung heraus ist kein Eröffnungsbuch nötig: Rodent IV spielt sofort + Ohne Buch + Ohne Buch: ohne Eröffnungsbuch spielen + Eröffnungsbücher von Rodent IV + Rodent IV — Eröffnungsbücher + heruntergeladen · %1$s MB + nicht heruntergeladen · %1$s MB + Eröffnungsbücher gelöscht + Rodent beantwortet Remis mit Stockfish: über „Engine“ herunterladen + Rodent ist nicht gestartet. + Neu starten + Ab hier eine Partie gegen Rodent IV %1$s · %2$s. + Rodent hat während der Partie aufgehört. + %1$s, von %2$s bis %3$s + Spielstärke + Eröffnungsbücher löschen diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 3c1cbfa..054c60d 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -402,7 +402,7 @@ Nueva partida Mis bases + Nueva base - Aquí estarán las partidas que introduzcas o juegues contra Maia + Aquí estarán las partidas que introduzcas o juegues contra el ordenador Archivos Mis partidas Nueva base @@ -487,7 +487,6 @@ Blancas Negras Al azar - Rival — Maia %1$s El rating propio de Maia: no equivale al Elo de una persona. Maia se descarga una sola vez (%1$s MB, desde huggingface.co, el archivo de los propios autores). Descargar y jugar @@ -504,7 +503,6 @@ Maia se rinde A partir de aquí, una partida contra Maia %1$s. Abortar - Jugar con Maia Tu nombre Maia está descargada Reintentar @@ -519,7 +517,6 @@ ✓ Guardada Guardar… juegas con %1$s · %2$s - Seguir desde aquí contra Maia… Tras %1$s Sonido Deshacer @@ -531,7 +528,7 @@ la posición inicial Maia no se inició. Volver a descargar Maia - Hay una partida aplazada contra Maia %1$s + Hay una partida aplazada contra %1$s Continuarla Empezar una nueva Una partida nueva la sustituye; lo jugado va sin terminar a la base del jugador. @@ -545,7 +542,7 @@ ✓ En «%1$s», n.º %2$s › Partida guardada sin terminar en «%1$s» se guardan solas - Guardar las partidas contra Maia en la base del jugador + Guardar las partidas contra el ordenador en la base del jugador Las partidas se guardan en «%1$s» Las partidas se guardarán en una base nueva «%1$s». Sin nombre, las partidas van a «%1$s». Escribe un nombre para tener tu propia base. @@ -554,6 +551,116 @@ No se pudo escribir en «%1$s»: %2$s Una partida nueva la sustituye. Abierta por última vez - Partida contra Maia %1$s + Partida contra %1$s jugada %1$d + + Amanda + Primero ataca, luego busca piezas activas. + Cloe + Le gustan las posiciones cerradas. + Débora + Defiende bien y le gustan sus alfiles. + Defensor + Sólido y prudente; se conforma con tablas. + Dinámico + Ataca, le gustan los alfiles, sacrifica de vez en cuando. + Gruñón + Ataque y restricción; le gustan las posiciones bloqueadas, evita las tablas. + Partisano + Ataca tras aperturas tranquilas y discretas. + Gambitero + Equilibrado, pero entrega peones con más facilidad. + Pedrita + Peones, defensa y restricción. + Preston + Un atacante materialista y moderado. + Sencillo + El más «computadora»: ajedrez sencillo y sólido. + Fogoso + Agudo y agresivo. + Estrangulador + Una boa: asfixia despacio, muy humano. + Alekhine + Ataques dinámicos y combinaciones profundas. + Anand + Juego rápido y universal con aperturas agudas. + Anderssen + Un atacante romántico del siglo XIX: sacrificios. + Bosboom + Aperturas poco habituales y blitz creativo. + Botvinnik + Juego estratégico y científico, preparación profunda. + Fischer + Claro, clásico y preciso. + Karpov + Presión posicional, profilaxis y técnica. + Kasparov + Iniciativa y ataque poderoso. + Kortchnoi + Un defensor tenaz y contraatacante. + Larsen + Original y arriesgado, con aperturas inusuales. + Lasker + Un luchador práctico y psicológico. + Marshall + Un atacante audaz, amigo de los gambitos. + Morphy + Desarrollo rápido y líneas abiertas. + Nimzowitsch + Restricción, bloqueo y sobreprotección. + Petrosian + Profilaxis y seguridad ante todo. + Reti + Hipermoderno: controla el centro a distancia. + Rubinstein + Juego posicional clásico, gran finalista. + Spassky + Un jugador universal, cómodo en cualquier posición. + Steinitz + El fundador del juego posicional, un defensor obstinado. + Tal + El mago de Riga: sacrificios y ataque. + Tarrasch + Reglas clásicas: espacio, desarrollo, piezas activas. + Topalov + Agresivo y dinámico, sacrifica la calidad. + juega como una persona + fuerte, con estilo + Como una persona + Maia no elige estilo: juega como la gente de su nivel. + El rating propio de Rodent (UCI_Elo): no equivale al Elo de una persona. + Rodent se rinde + Rodent se rindió + Rodent rechaza las tablas + Rodent lo rechazó; ofrece de nuevo tras dos de sus jugadas + Su posición está perdida. ¿Aceptar la victoria o jugar hasta el final? + Jugar + Jugar contra el ordenador + Fuerza: %1$s + Contra quién jugar + Un carácter es un estilo y unas aperturas; la fuerza la marca el control deslizante. + Grandes jugadores + Caracteres + Cambiar + %1$s, gran jugador + %1$s, carácter + Carácter: %1$s + Rodent IV y sus libros de aperturas están en el teléfono + Libros de aperturas de Rodent IV: %1$s MB, una sola vez de github.com + Desde una posición no hace falta libro de aperturas: Rodent IV juega enseguida + Sin libro + Sin libro: jugar sin libro de aperturas + Libros de aperturas de Rodent IV + Rodent IV — libros de aperturas + descargados · %1$s MB + no descargados · %1$s MB + Libros de aperturas eliminados + Rodent responde a las tablas con Stockfish: descárgalo con «Motor» + Rodent no se inició. + Reiniciar + A partir de aquí, una partida contra Rodent IV %1$s · %2$s. + Rodent se detuvo durante la partida. + %1$s, de %2$s a %3$s + Fuerza + Eliminar los libros de aperturas diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index bc46835..90cb3c1 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -402,7 +402,7 @@ Nouvelle partie Mes bases + Nouvelle base - Ici seront les parties que vous saisirez ou jouerez contre Maia + Ici seront les parties que vous saisirez ou jouerez contre l’ordinateur Fichiers Mes parties Nouvelle base @@ -487,7 +487,6 @@ Blancs Noirs Au hasard - Adversaire — Maia %1$s Le classement propre de Maia : il ne correspond pas à l’Elo d’une personne. Maia est téléchargée une seule fois (%1$s Mo, depuis huggingface.co, le fichier des auteurs eux-mêmes). Télécharger et jouer @@ -504,7 +503,6 @@ Maia abandonne À partir d’ici, une partie contre Maia %1$s. Abandonner - Jouer contre Maia Votre nom Maia est téléchargée Réessayer @@ -519,7 +517,6 @@ ✓ Enregistrée Enregistrer… vous jouez %1$s · %2$s - Continuer d’ici contre Maia… Après %1$s Son Annuler @@ -531,7 +528,7 @@ la position initiale Maia n’a pas démarré. Retélécharger Maia - Une partie contre Maia %1$s est en attente + Une partie contre %1$s est en attente La continuer En commencer une nouvelle Une nouvelle partie la remplace ; ce qui a été joué va, inachevé, dans la base du joueur. @@ -545,7 +542,7 @@ ✓ Dans « %1$s », n° %2$s › Partie enregistrée inachevée dans « %1$s » enregistrées d’elles-mêmes - Enregistrer les parties contre Maia dans la base du joueur + Enregistrer les parties contre l’ordinateur dans la base du joueur Les parties sont enregistrées dans « %1$s » Les parties seront enregistrées dans une nouvelle base « %1$s ». Sans nom, les parties vont dans « %1$s ». Saisissez un nom pour avoir votre propre base. @@ -554,6 +551,116 @@ Impossible d’écrire dans « %1$s » : %2$s Une nouvelle partie la remplace. Ouverte en dernier - Partie contre Maia %1$s + Partie contre %1$s coup %1$d + + Amanda + Attaque d’abord, puis joue pour l’activité des pièces. + Cloé + Aime les positions fermées. + Déborah + Défend bien et aime ses fous. + Défenseur + Solide et prudent ; se contente de la nulle. + Dynamique + Attaque, aime les fous, sacrifie de temps en temps. + Grincheux + Attaque et restriction ; aime les positions bloquées, évite la nulle. + Partisan + Attaque après des ouvertures calmes et discrètes. + Gambiteur + Équilibré, mais cède plus volontiers des pions. + Pedrita + Pions, défense et restriction. + Preston + Un attaquant matérialiste et modéré. + Simplet + Le plus « ordinateur » : un jeu simple et sain. + Boutefeu + Tranchant et agressif. + Étrangleur + Un boa : étouffe lentement, très humain. + Alekhine + Attaques dynamiques et combinaisons profondes. + Anand + Jeu rapide et universel, ouvertures tranchantes. + Anderssen + Un attaquant romantique du XIXe siècle : sacrifices. + Bosboom + Ouvertures originales et blitz créatif. + Botvinnik + Jeu stratégique et scientifique, préparation profonde. + Fischer + Clair, classique et précis. + Karpov + Étau positionnel, prophylaxie et technique. + Kasparov + Initiative et attaque puissante. + Kortchnoi + Un défenseur tenace et contre-attaquant. + Larsen + Original et risqué, aux ouvertures insolites. + Lasker + Un combattant pratique et psychologue. + Marshall + Un attaquant fougueux, amateur de gambits. + Morphy + Développement rapide et lignes ouvertes. + Nimzowitsch + Restriction, blocus et surprotection. + Petrosian + Prophylaxie et sécurité avant tout. + Reti + Hypermoderne : contrôle le centre à distance. + Rubinstein + Jeu positionnel classique, excellent en finale. + Spassky + Un joueur universel, à l’aise partout. + Steinitz + Le fondateur du jeu positionnel, défenseur obstiné. + Tal + Le magicien de Riga : sacrifices et attaque. + Tarrasch + Règles classiques : espace, développement, pièces actives. + Topalov + Agressif et dynamique, sacrifie la qualité. + joue comme un humain + fort, avec un style + Comme un humain + Maia ne choisit pas de style : elle joue comme les gens de son niveau. + Le classement propre de Rodent (UCI_Elo) : il ne correspond pas à l’Elo d’une personne. + Rodent abandonne + Rodent a abandonné + Rodent refuse la nulle + Rodent a refusé ; reproposez après deux de ses coups + Sa position est perdue. Accepter la victoire ou jouer jusqu’au bout ? + Jouer + Jouer contre l’ordinateur + Force : %1$s + Contre qui jouer + Un caractère, c’est un style et des ouvertures ; le curseur règle la force. + Grands joueurs + Caractères + Changer + %1$s, grand joueur + %1$s, caractère + Caractère : %1$s + Rodent IV et ses livres d’ouvertures sont sur le téléphone + Livres d’ouvertures de Rodent IV : %1$s Mo, une seule fois depuis github.com + Depuis une position, pas besoin de livre d’ouvertures : Rodent IV joue tout de suite + Sans livre + Sans livre : jouer sans livre d’ouvertures + Livres d’ouvertures de Rodent IV + Rodent IV — livres d’ouvertures + téléchargés · %1$s Mo + non téléchargés · %1$s Mo + Livres d’ouvertures supprimés + Rodent répond à la nulle avec Stockfish : téléchargez-le avec « Moteur » + Rodent n’a pas démarré. + Redémarrer + À partir d’ici, une partie contre Rodent IV %1$s · %2$s. + Rodent s’est arrêté pendant la partie. + %1$s, de %2$s à %3$s + Force + Supprimer les livres d’ouvertures diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 6ee5e33..a91652f 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -402,7 +402,7 @@ Nuova partita I miei database + Nuovo database - Qui ci saranno le partite che inserisci o giochi contro Maia + Qui ci saranno le partite che inserisci o giochi contro il computer File Le mie partite Nuovo database @@ -487,7 +487,6 @@ Bianco Nero Casuale - Avversario — Maia %1$s Il rating proprio di Maia: non corrisponde all’Elo di una persona. Maia si scarica una sola volta (%1$s MB, da huggingface.co, il file degli autori stessi). Scarica e gioca @@ -504,7 +503,6 @@ Maia abbandona Da qui, una partita contro Maia %1$s. Annulla - Gioca con Maia Il tuo nome Maia è scaricata Riprova @@ -519,7 +517,6 @@ ✓ Salvata Salva… giochi con %1$s · %2$s - Continua da qui contro Maia… Dopo %1$s Suono Annulla @@ -531,7 +528,7 @@ la posizione iniziale Maia non si è avviata. Riscarica Maia - C’è una partita sospesa contro Maia %1$s + C’è una partita sospesa contro %1$s Continuala Iniziarne una nuova Una nuova partita la sostituisce; quanto giocato va, non finito, nel database del giocatore. @@ -545,7 +542,7 @@ ✓ In «%1$s», n. %2$s › Partita salvata non finita in «%1$s» salvate da sole - Salvare le partite contro Maia nel database del giocatore + Salvare le partite contro il computer nel database del giocatore Le partite vengono salvate in «%1$s» Le partite saranno salvate in un nuovo database «%1$s». Senza nome le partite vanno in «%1$s». Inserisci un nome per avere un database tuo. @@ -554,6 +551,116 @@ Impossibile scrivere in «%1$s»: %2$s Una nuova partita la sostituisce. Aperta per ultima - Partita contro Maia %1$s + Partita contro %1$s mossa %1$d + + Amanda + Prima attacca, poi gioca per l’attività dei pezzi. + Cloe + Ama le posizioni chiuse. + Debora + Difende bene e ama i suoi alfieri. + Difensore + Solido e prudente; si accontenta della patta. + Dinamico + Attacca, ama gli alfieri, sacrifica di tanto in tanto. + Brontolo + Attacco e restrizione; ama le posizioni bloccate, evita la patta. + Partigiano + Attacca dopo aperture tranquille e discrete. + Gambettista + Equilibrato, ma cede pedoni più volentieri. + Pedrita + Pedoni, difesa e restrizione. + Preston + Un attaccante materialista e moderato. + Semplice + Il più «computer»: scacchi semplici e solidi. + Testa calda + Tagliente e aggressivo. + Strangolatore + Un boa: stringe lentamente, molto umano. + Aljechin + Attacchi dinamici e combinazioni profonde. + Anand + Gioco rapido e universale con aperture taglienti. + Anderssen + Un attaccante romantico dell’Ottocento: sacrifici. + Bosboom + Aperture insolite e blitz creativo. + Botvinnik + Gioco strategico e scientifico, preparazione profonda. + Fischer + Chiaro, classico e preciso. + Karpov + Morsa posizionale, profilassi e tecnica. + Kasparov + Iniziativa e attacco potente. + Kortchnoi + Un difensore tenace e contrattaccante. + Larsen + Originale e rischioso, con aperture insolite. + Lasker + Un combattente pratico e psicologico. + Marshall + Un attaccante spavaldo con i gambetti. + Morphy + Sviluppo rapido e linee aperte. + Nimzowitsch + Restrizione, blocco e sovraprotezione. + Petrosian + Profilassi e sicurezza prima di tutto. + Reti + Ipermoderno: controlla il centro da lontano. + Rubinstein + Gioco posizionale classico, ottimo nei finali. + Spassky + Un giocatore universale, a suo agio ovunque. + Steinitz + Il fondatore del gioco posizionale, difensore ostinato. + Tal + Il mago di Riga: sacrifici e attacco. + Tarrasch + Regole classiche: spazio, sviluppo, pezzi attivi. + Topalov + Aggressivo e dinamico, sacrifica la qualità. + gioca come un umano + forte, con uno stile + Come un umano + Maia non sceglie uno stile: gioca come le persone del suo livello. + Il rating proprio di Rodent (UCI_Elo): non corrisponde all’Elo di una persona. + Rodent abbandona + Rodent ha abbandonato + Rodent rifiuta la patta + Rodent ha rifiutato; riproponi dopo due sue mosse + La sua posizione è persa. Accettare la vittoria o giocare fino in fondo? + Gioca + Gioca contro il computer + Forza: %1$s + Contro chi giocare + Un carattere è uno stile con le sue aperture; la forza la regola il cursore. + Grandi giocatori + Caratteri + Cambia + %1$s, grande giocatore + %1$s, carattere + Carattere: %1$s + Rodent IV e i suoi libri di aperture sono sul telefono + Libri di aperture di Rodent IV: %1$s MB, una sola volta da github.com + Da una posizione non serve il libro di aperture: Rodent IV gioca subito + Senza libro + Senza libro: gioca senza libro di aperture + Libri di aperture di Rodent IV + Rodent IV — libri di aperture + scaricati · %1$s MB + non scaricati · %1$s MB + Libri di aperture eliminati + Rodent risponde alla patta con Stockfish: scaricalo con «Motore» + Rodent non si è avviato. + Riavvia + Da qui, una partita contro Rodent IV %1$s · %2$s. + Rodent si è fermato durante la partita. + %1$s, da %2$s a %3$s + Forza + Elimina i libri di aperture diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 9e1f17f..3a01899 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -397,7 +397,7 @@ Жаңа ойын Менің базаларым + Жаңа база - Мұнда сіз енгізген немесе Maia-мен ойнаған ойындар болады + Мұнда сіз енгізген немесе компьютермен ойнаған ойындар болады Файлдар Менің ойындарым Жаңа база @@ -480,7 +480,6 @@ Ақтар Қаралар Кездейсоқ - Қарсылас — Maia %1$s Maia-ның өз рейтингі: ол адамның Эло рейтингіне сәйкес келмейді. Maia бір рет жүктеледі (%1$s МБ, huggingface.co сайтынан — авторлардың өз файлы). Жүктеп алып ойнау @@ -497,7 +496,6 @@ Maia беріледі Бұдан әрі — Maia %1$s-мен ойын. Тоқтату - Maia-мен ойнау Атыңыз Maia жүктелді Қайталау @@ -512,7 +510,6 @@ ✓ Сақталды Сақтау… сіз %1$s · %2$s - Осы жерден Maia-мен жалғастыру… %1$s кейін Дыбыс Болдырмау @@ -524,7 +521,7 @@ бастапқы позиция Maia іске қосылмады. Maia-ны қайта жүктеу - Maia %1$s-мен кейінге қалдырылған ойын бар + %1$s-мен кейінге қалдырылған ойын бар Жалғастыру Жаңасын бастау Жаңа ойын оның орнын басады; ойналғаны аяқталмаған күйде ойыншы базасына жазылады. @@ -538,7 +535,7 @@ ✓ «%1$s» базасында, № %2$s › Ойын аяқталмаған күйде «%1$s» базасына жазылды өзі жазылады - Maia-мен ойындарды ойыншы базасына жазу + Компьютермен ойындарды ойыншы базасына жазу Ойындар «%1$s» базасына жазылады Ойындар жаңа «%1$s» базасына жазылады. Атсыз ойындар «%1$s» базасына түседі. Өз базаңыз болуы үшін атыңызды жазыңыз. @@ -547,6 +544,116 @@ «%1$s» базасына жазу мүмкін болмады: %2$s Жаңа ойын оның орнын басады. Соңғы ашылған - Maia %1$s-мен ойын + %1$s-мен ойын %1$d-жүріс + + Аманда + Алдымен шабуылдайды, кейін фигуралар белсенділігіне ойнайды. + Клои + Жабық позицияларды ұнатады. + Дебора + Жақсы қорғанады және пілдерін ұнатады. + Қорғаушы + Сенімді әрі сақ; тең ойынға келіседі. + Динамик + Шабуылдайды, пілдерді ұнатады, анда-санда құрбан етеді. + Күңкілдек + Шабуыл мен қысу; бітелген позицияларды ұнатады, тең ойыннан қашады. + Партизан + Тыныш, байқалмайтын дебюттерден кейін шабуылдайды. + Гамбитші + Теңгерімді, бірақ пешкаларды оңай береді. + Педрита + Пешкалар, қорғаныс және қысу. + Престон + Материалист, қалыпты шабуылшы. + Қарапайым + Ең «компьютерлік»: қарапайым, дұрыс шахмат. + Қызба + Өткір және агрессивті. + Тұншықтырушы + Айдаһар-жылан: баяу қысады, өте адамға ұқсас. + Алехин + Серпінді шабуылдар мен терең комбинациялар. + Ананд + Жылдам, әмбебап ойын, өткір дебюттермен. + Андерсен + XIX ғасырдың романтик шабуылшысы: құрбандар. + Босбум + Әдеттен тыс дебюттер және шығармашыл блиц. + Ботвинник + Терең дайындыққа негізделген ғылыми, стратегиялық ойын. + Фишер + Анық, классикалық және дәл. + Карпов + Позициялық қысым, профилактика және техника. + Каспаров + Бастама және қуатты шабуыл. + Корчной + Табанды қорғаушы және қарсы шабуылшы. + Ларсен + Өзгеше және тәуекелшіл, әдеттен тыс дебюттермен. + Ласкер + Практикалық, психолог күрескер. + Маршалл + Гамбиттері бар батыл шабуылшы. + Морфи + Жылдам дамыту және ашық сызықтар. + Нимцович + Қысу, блокада және артық қорғау. + Петросян + Профилактика және қауіпсіздік бірінші. + Рети + Гиперзаманауи: орталықты алыстан бақылайды. + Рубинштейн + Классикалық позициялық ойын, эндшпильде мықты. + Спасский + Әмбебап ойыншы, кез келген позицияда өзін үйдегідей сезінеді. + Стейниц + Позициялық ойынның негізін салушы, қыңыр қорғаушы. + Таль + Ригалық сиқыршы: құрбандар мен шабуыл. + Тарраш + Классикалық ережелер: кеңістік, дамыту, белсенді фигуралар. + Топалов + Агрессивті және серпінді, сапаны құрбан етеді. + адам сияқты ойнайды + күшті, стилімен + Адам сияқты + Maia стиль таңдамайды: ол өз рейтингіндегі адамдар сияқты ойнайды. + Rodent-тің өз рейтингі (UCI_Elo): ол адамның Эло рейтингіне сәйкес келмейді. + Rodent беріледі + Rodent берілді + Rodent тең ойыннан бас тартады + Rodent бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз + Оның позициясы ұтылды. Жеңісті қабылдайсыз ба, әлде соңына дейін ойнайсыз ба? + Ойнау + Компьютермен ойнау + Күші: %1$s + Кіммен ойнау + Мінез — бұл стиль мен дебюттер, күшті жүгірткі белгілейді. + Ұлы шахматшылар + Мінездер + Өзгерту + %1$s, ұлы шахматшы + %1$s, мінез + Мінез: %1$s + Rodent IV және оның дебют кітаптары телефонда + Rodent IV дебют кітаптары: %1$s МБ, github.com сайтынан бір рет + Позициядан ойнағанда дебют кітабы керек емес — Rodent IV бірден ойнайды + Кітапсыз + Кітапсыз: дебют кітабысыз ойнау + Rodent IV дебют кітаптары + Rodent IV — дебют кітаптары + жүктелген · %1$s МБ + жүктелмеген · %1$s МБ + Дебют кітаптары жойылды + Rodent тең ойынға Stockfish арқылы жауап береді: оны «Қозғалтқыш» батырмасымен жүктеңіз + Rodent іске қосылмады. + Қайта іске қосу + Бұдан әрі — Rodent IV %1$s-мен ойын (%2$s). + Rodent ойын кезінде тоқтады. + %1$s, %2$s-ден %3$s-ге дейін + Күші + Дебют кітаптарын жою diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index eadbc7f..85a74ec 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -403,7 +403,7 @@ Nova partida Minhas bases + Nova base - Aqui ficarão as partidas que você inserir ou jogar contra a Maia + Aqui ficarão as partidas que você inserir ou jogar contra o computador Arquivos Minhas partidas Nova base @@ -488,7 +488,6 @@ Brancas Pretas Aleatório - Adversário — Maia %1$s O rating próprio da Maia: não corresponde ao Elo de uma pessoa. A Maia é baixada uma única vez (%1$s MB, de huggingface.co, o arquivo dos próprios autores). Baixar e jogar @@ -505,7 +504,6 @@ Maia desiste A partir daqui, uma partida contra Maia %1$s. Abortar - Jogar com a Maia O seu nome A Maia foi baixada Tentar de novo @@ -520,7 +518,6 @@ ✓ Salva Salvar… você joga de %1$s · %2$s - Continuar daqui contra a Maia… Depois de %1$s Som Desfazer @@ -532,7 +529,7 @@ a posição inicial A Maia não iniciou. Baixar a Maia de novo - Há uma partida adiada contra a Maia %1$s + Há uma partida adiada contra %1$s Continuá-la Começar uma nova Uma nova partida a substitui; o que foi jogado vai, inacabado, para a base do jogador. @@ -546,7 +543,7 @@ ✓ Em «%1$s», n.º %2$s › Partida gravada inacabada em «%1$s» gravadas sozinhas - Gravar as partidas contra a Maia na base do jogador + Gravar as partidas contra o computador na base do jogador As partidas são gravadas em «%1$s» As partidas serão gravadas numa nova base «%1$s». Sem nome, as partidas vão para «%1$s». Escreva um nome para ter a sua própria base. @@ -555,6 +552,116 @@ Não foi possível gravar em «%1$s»: %2$s Uma nova partida a substitui. Aberta por último - Partida contra a Maia %1$s + Partida contra %1$s lance %1$d + + Amanda + Primeiro ataca, depois joga pela atividade das peças. + Cloe + Gosta de posições fechadas. + Débora + Defende bem e gosta dos seus bispos. + Defensor + Sólido e cuidadoso; contenta-se com o empate. + Dinâmico + Ataca, gosta de bispos, sacrifica de vez em quando. + Rabugento + Ataque e restrição; gosta de posições bloqueadas, evita empates. + Partisano + Ataca depois de aberturas calmas e discretas. + Gambiteiro + Equilibrado, mas entrega peões com mais facilidade. + Pedrita + Peões, defesa e restrição. + Preston + Um atacante materialista e moderado. + Simples + O mais «computador»: xadrez simples e sólido. + Esquentado + Agudo e agressivo. + Estrangulador + Uma jiboia: aperta devagar, muito humano. + Alekhine + Ataques dinâmicos e combinações profundas. + Anand + Jogo rápido e universal com aberturas agudas. + Anderssen + Um atacante romântico do século XIX: sacrifícios. + Bosboom + Aberturas incomuns e blitz criativo. + Botvinnik + Jogo estratégico e científico, preparação profunda. + Fischer + Claro, clássico e preciso. + Karpov + Pressão posicional, profilaxia e técnica. + Kasparov + Iniciativa e ataque poderoso. + Kortchnoi + Um defensor tenaz e contra-atacante. + Larsen + Original e arriscado, com aberturas incomuns. + Lasker + Um lutador prático e psicológico. + Marshall + Um atacante ousado com gambitos. + Morphy + Desenvolvimento rápido e linhas abertas. + Nimzowitsch + Restrição, bloqueio e superproteção. + Petrosian + Profilaxia e segurança acima de tudo. + Reti + Hipermoderno: controla o centro à distância. + Rubinstein + Jogo posicional clássico, ótimo em finais. + Spassky + Um jogador universal, à vontade em qualquer posição. + Steinitz + O fundador do jogo posicional, um defensor obstinado. + Tal + O mágico de Riga: sacrifícios e ataque. + Tarrasch + Regras clássicas: espaço, desenvolvimento, peças ativas. + Topalov + Agressivo e dinâmico, sacrifica a qualidade. + joga como um humano + forte, com estilo + Como um humano + A Maia não escolhe estilo: joga como as pessoas do nível dela. + O rating próprio do Rodent (UCI_Elo): não corresponde ao Elo de uma pessoa. + O Rodent desiste + O Rodent desistiu + O Rodent recusa o empate + O Rodent recusou; ofereça de novo após dois lances dele + A posição dele está perdida. Aceitar a vitória ou jogar até o fim? + Jogar + Jogar contra o computador + Força: %1$s + Contra quem jogar + Um caráter é um estilo e suas aberturas; a força é definida pelo controle deslizante. + Grandes jogadores + Caracteres + Alterar + %1$s, grande jogador + %1$s, caráter + Caráter: %1$s + O Rodent IV e seus livros de aberturas estão no telefone + Livros de aberturas do Rodent IV: %1$s MB, baixados uma vez de github.com + A partir de uma posição não é preciso livro de aberturas: o Rodent IV joga na hora + Sem livro + Sem livro: jogar sem livro de aberturas + Livros de aberturas do Rodent IV + Rodent IV — livros de aberturas + baixados · %1$s MB + não baixados · %1$s MB + Livros de aberturas excluídos + O Rodent responde ao empate com o Stockfish: baixe-o com «Motor» + O Rodent não iniciou. + Reiniciar + A partir daqui, uma partida contra Rodent IV %1$s · %2$s. + O Rodent parou durante a partida. + %1$s, de %2$s a %3$s + Força + Excluir os livros de aberturas diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 8bde649..328b6f2 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -408,7 +408,7 @@ Новая партия Мои базы + Новая база - Здесь будут партии, которые вы введёте или сыграете с Maia + Здесь будут партии, которые вы введёте или сыграете с компьютером Файлы Мои партии Новая база @@ -495,7 +495,6 @@ Белые Чёрные Случайно - Соперник — Maia %1$s Собственный рейтинг Maia: он не равен Эло человека. Maia скачивается один раз (%1$s МБ, с huggingface.co — файл самих авторов). Скачать и играть @@ -512,7 +511,6 @@ Maia сдаётся Дальше — игра с Maia %1$s. Прервать - Играть с Maia Ваше имя Maia скачана Повторить @@ -527,7 +525,6 @@ ✓ Сохранено Сохранить… вы %1$s · %2$s - Играть отсюда с Maia… После %1$s Звук Отменить @@ -539,7 +536,7 @@ начальная позиция Maia не запустилась. Скачать Maia заново - Есть отложенная партия с Maia %1$s + Есть отложенная партия с %1$s Продолжить её Начать новую Новая партия заменит её; сыгранное запишется в базу игрока неоконченным. @@ -553,7 +550,7 @@ ✓ В «%1$s», № %2$s › Партия записана в «%1$s» неоконченной пишутся сами - Записывать партии с Maia в базу игрока + Записывать партии с компьютером в базу игрока Партии записываются в «%1$s» Партии будут записываться в новую базу «%1$s». Без имени партии идут в «%1$s». Впишите имя — заведём вашу базу. @@ -562,6 +559,116 @@ Не удалось записать в «%1$s»: %2$s Новая партия заменит её. Открыта последней - Партия с Maia %1$s + Партия с %1$s %1$d-й ход + + Аманда + Сначала атакует, потом играет на активность фигур. + Клои + Любит закрытые позиции. + Дебора + Хорошо защищается и любит слонов. + Защитник + Надёжный и осторожный, согласен на ничью. + Динамик + Атакует, любит слонов, время от времени жертвует. + Ворчун + Атака и сковывание; любит запертые позиции, избегает ничьих. + Партизан + Атакует после тихих, неприметных дебютов. + Гамбитист + Сбалансированный, но охотнее отдаёт пешки. + Педрита + Пешки, защита и сковывание. + Престон + Материалист, атакует умеренно. + Простак + Самый «компьютерный»: простые, правильные шахматы. + Задира + Острый и агрессивный. + Удав + Удав: медленно душит, очень по-человечески. + Алехин + Динамичные атаки и глубокие комбинации. + Ананд + Быстрая, универсальная игра с острыми дебютами. + Андерсен + Романтик-атакёр XIX века: жертвы. + Босбум + Необычные дебюты и творческая блиц-игра. + Ботвинник + Научная стратегическая игра на глубокой подготовке. + Фишер + Ясная, классическая и точная игра. + Карпов + Позиционное давление, профилактика и техника. + Каспаров + Инициатива и мощная атака. + Корчной + Упорный защитник и мастер контратаки. + Ларсен + Оригинальный и рискованный, с необычными дебютами. + Ласкер + Практичный боец-психолог. + Маршалл + Лихой атакёр с гамбитами. + Морфи + Быстрое развитие и открытые линии. + Нимцович + Сковывание, блокада и сверхзащита. + Петросян + Профилактика и безопасность прежде всего. + Рети + Гиперсовременный: контролирует центр издалека. + Рубинштейн + Классическая позиционная игра, силён в эндшпиле. + Спасский + Универсал, в любой позиции как дома. + Стейниц + Основатель позиционной игры, упрямый защитник. + Таль + Рижский волшебник: жертвы и атака. + Тарраш + Классические правила: пространство, развитие, активные фигуры. + Топалов + Агрессивный и динамичный, жертвует качество. + играет как человек + сильный, со стилем + Как человек + Maia не выбирает стиль: она играет, как люди её рейтинга. + Собственный рейтинг Rodent (UCI_Elo): он не равен Эло человека. + Rodent сдаётся + Rodent сдался + Rodent отказывается от ничьей + Rodent отказался; снова можно предложить через два его хода + Его позиция проиграна. Принять победу или доиграть? + Играть + Играть с компьютером + Сила: %1$s + С кем играть + Характер — это стиль и дебюты, силу задаёт ползунок. + Великие шахматисты + Характеры + Изменить + %1$s, великий шахматист + %1$s, характер + Характер: %1$s + Rodent IV и его дебютные книги на телефоне + Дебютные книги Rodent IV: %1$s МБ, скачиваются один раз с github.com + С позиции дебютная книга не нужна — Rodent IV играет сразу + Без книги + Без книги: играть без дебютной книги + Дебютные книги Rodent IV + Rodent IV — дебютные книги + скачаны · %1$s МБ + не скачаны · %1$s МБ + Дебютные книги удалены + Rodent отвечает на ничью с помощью Stockfish: скачайте его кнопкой «Движок» + Rodent не запустился. + Перезапустить + Дальше — игра с Rodent IV %1$s · %2$s. + Rodent остановился во время игры. + %1$s, от %2$s до %3$s + Сила + Удалить дебютные книги diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index 123eaa4..dc03225 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -395,7 +395,7 @@ Yangi o‘yin Mening bazalarim + Yangi baza - Bu yerda siz kiritgan yoki Maia bilan o‘ynagan o‘yinlar bo‘ladi + Bu yerda siz kiritgan yoki kompyuter bilan o‘ynagan o‘yinlar bo‘ladi Fayllar Mening o‘yinlarim Yangi baza @@ -478,7 +478,6 @@ Oqlar Qoralar Tasodifiy - Raqib — Maia %1$s Maia ning o‘z reytingi: u odamning Elo reytingiga teng emas. Maia bir marta yuklab olinadi (%1$s MB, huggingface.co dan — mualliflarning o‘z fayli). Yuklab olish va o‘ynash @@ -495,7 +494,6 @@ Maia taslim bo‘lmoqda Bundan keyin — Maia %1$s bilan o‘yin. To‘xtatish - Maia bilan o‘ynash Ismingiz Maia yuklab olindi Qayta urinish @@ -510,7 +508,6 @@ ✓ Saqlandi Saqlash… siz %1$s · %2$s - Shu yerdan Maia bilan davom ettirish… %1$s dan keyin Ovoz Bekor qilish @@ -522,7 +519,7 @@ boshlang‘ich pozitsiya Maia ishga tushmadi. Maia’ni qayta yuklab olish - Maia %1$s bilan to‘xtatilgan o‘yin bor + %1$s bilan to‘xtatilgan o‘yin bor Davom ettirish Yangisini boshlash Yangi o‘yin uning o‘rnini oladi; o‘ynalgani tugallanmagan holda o‘yinchi bazasiga yoziladi. @@ -536,7 +533,7 @@ ✓ «%1$s» da, № %2$s › O‘yin tugallanmagan holda «%1$s» ga yozildi o‘zi yoziladi - Maia bilan o‘yinlarni o‘yinchi bazasiga yozish + Kompyuter bilan o‘yinlarni o‘yinchi bazasiga yozish O‘yinlar «%1$s» ga yoziladi O‘yinlar yangi «%1$s» bazasiga yoziladi. Ismsiz o‘yinlar «%1$s» ga tushadi. O‘z bazangiz bo‘lishi uchun ismingizni yozing. @@ -545,6 +542,116 @@ «%1$s» ga yozib bo‘lmadi: %2$s Yangi o‘yin uning o‘rnini oladi. Oxirgi ochilgan - Maia %1$s bilan o‘yin + %1$s bilan o‘yin %1$d-yurish + + Amanda + Avval hujum qiladi, keyin donalar faolligi uchun o‘ynaydi. + Kloe + Yopiq pozitsiyalarni yaxshi ko‘radi. + Debora + Yaxshi himoyalanadi va filllarini yaxshi ko‘radi. + Himoyachi + Mustahkam va ehtiyotkor; duranga rozi. + Dinamik + Hujum qiladi, fillarni yaxshi ko‘radi, ba’zan qurbon qiladi. + G‘udranuvchi + Hujum va siqish; yopiq pozitsiyalarni yoqtiradi, durangdan qochadi. + Partizan + Sokin, sezilmas debyutlardan keyin hujum qiladi. + Gambitchi + Muvozanatli, lekin piyodalarni osonroq beradi. + Pedrita + Piyodalar, himoya va siqish. + Preston + Materialist, o‘rtacha hujumchi. + Oddiy + Eng «kompyuterona»: oddiy, to‘g‘ri shaxmat. + Jo‘shqin + O‘tkir va tajovuzkor. + Bo‘g‘uvchi + Bo‘g‘ma ilon: sekin siqadi, juda insoniy. + Alyoxin + Dinamik hujumlar va chuqur kombinatsiyalar. + Anand + Tez, universal o‘yin, o‘tkir debyutlar bilan. + Anderssen + XIX asrning romantik hujumchisi: qurbonlar. + Bosboom + Noodatiy debyutlar va ijodiy blits. + Botvinnik + Chuqur tayyorgarlikka asoslangan ilmiy, strategik o‘yin. + Fischer + Aniq, klassik va puxta. + Karpov + Pozitsion bosim, profilaktika va texnika. + Kasparov + Tashabbus va kuchli hujum. + Kortchnoi + Qat’iyatli himoyachi va qarshi hujumchi. + Larsen + O‘ziga xos va tavakkalchi, noodatiy debyutlar bilan. + Lasker + Amaliy, psixolog kurashchi. + Marshall + Gambitlar bilan dadil hujumchi. + Morphy + Tez rivojlanish va ochiq chiziqlar. + Nimzowitsch + Siqish, blokada va ortiqcha himoya. + Petrosian + Profilaktika va xavfsizlik birinchi. + Reti + Gipermodern: markazni uzoqdan nazorat qiladi. + Rubinstein + Klassik pozitsion o‘yin, endshpilda kuchli. + Spassky + Universal o‘yinchi, har qanday pozitsiyada o‘zini uydagidek his qiladi. + Steinitz + Pozitsion o‘yin asoschisi, qaysar himoyachi. + Tal + Rigalik sehrgar: qurbonlar va hujum. + Tarrasch + Klassik qoidalar: makon, rivojlanish, faol donalar. + Topalov + Tajovuzkor va dinamik, sifatni qurbon qiladi. + odamdek o‘ynaydi + kuchli, uslubli + Odamdek + Maia uslub tanlamaydi: u o‘z reytingidagi odamlardek o‘ynaydi. + Rodent ning o‘z reytingi (UCI_Elo): u odamning Elo reytingiga teng emas. + Rodent taslim bo‘lmoqda + Rodent taslim bo‘ldi + Rodent durangdan bosh tortadi + Rodent rad etdi; uning ikki yurishidan keyin yana taklif qiling + Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki oxirigacha o‘ynaysizmi? + O‘ynash + Kompyuter bilan o‘ynash + Kuch: %1$s + Kim bilan o‘ynash + Xarakter — bu uslub va debyutlar, kuchni esa slayder belgilaydi. + Buyuk shaxmatchilar + Xarakterlar + O‘zgartirish + %1$s, buyuk shaxmatchi + %1$s, xarakter + Xarakter: %1$s + Rodent IV va uning debyut kitoblari telefonda + Rodent IV debyut kitoblari: %1$s MB, github.com dan bir marta + Pozitsiyadan o‘ynashda debyut kitobi kerak emas — Rodent IV darhol o‘ynaydi + Kitobsiz + Kitobsiz: debyut kitobisiz o‘ynash + Rodent IV debyut kitoblari + Rodent IV — debyut kitoblari + yuklab olingan · %1$s MB + yuklab olinmagan · %1$s MB + Debyut kitoblari o‘chirildi + Rodent durangga Stockfish bilan javob beradi: uni «Dvigatel» tugmasi bilan yuklab oling + Rodent ishga tushmadi. + Qayta ishga tushirish + Bundan keyin — Rodent IV %1$s · %2$s bilan o‘yin. + Rodent o‘yin paytida to‘xtadi. + %1$s, %2$s dan %3$s gacha + Kuch + Debyut kitoblarini o‘chirish diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index 511c347..7d73ee7 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -400,7 +400,7 @@ New game My databases + New database - Games you enter or play against Maia will be here + Games you enter or play against the computer will be here Files My games New database @@ -483,7 +483,6 @@ White Black Random - Opponent — Maia %1$s Maia’s own rating: it does not match a person’s Elo. Maia is downloaded once (%1$s MB, from huggingface.co, the authors\' own file). Download and play @@ -500,7 +499,6 @@ Maia resigns From here on, a game against Maia %1$s. Abort - Play with Maia Your name Maia is downloaded Try again @@ -515,7 +513,6 @@ ✓ Saved Save… you play %1$s · %2$s - Play on from here with Maia… After %1$s Sound Undo @@ -527,7 +524,7 @@ the starting position Maia did not start. Download Maia again - There is a game put aside against Maia %1$s + There is a game put aside against %1$s Continue it Start a new one A new game replaces it; what was played goes into the player’s database, unfinished. @@ -535,13 +532,13 @@ by agreement Maia declines the draw Maia declined; offer again after two of her moves - Maia answers a draw offer with Stockfish: download it in the game screen («Engine») + Maia answers a draw offer with Stockfish: download it in the game screen (“Engine”) %1$s — games against the computer Games against the computer ✓ In “%1$s”, No. %2$s › Game written to “%1$s” unfinished recorded automatically - Write games against Maia to the player’s database + Write games against the computer to the player’s database Games are written to “%1$s” Games will be written to a new database “%1$s”. Without a name games go to “%1$s”. Enter a name to have a database of your own. @@ -550,6 +547,116 @@ Could not write to “%1$s”: %2$s A new game replaces it. Last opened - Game against Maia %1$s + Game against %1$s move %1$d + + Amanda + Attacks first, then plays for active pieces. + Cloe + Likes closed positions. + Deborah + Defends well and likes her bishops. + Defender + Solid and careful; content with a draw. + Dynamic + Attacks, likes bishops, sacrifices now and then. + Grumpy + Attack and restraint; likes blocked positions, avoids draws. + Partisan + Attacks after quiet, stealthy openings. + Pawnsacker + Balanced, but gives up pawns more readily. + Pedrita + Pawns, defence and restraint. + Preston + A materialistic, moderate attacker. + Simple + The most computer-like: plain, sound chess. + Spitfire + Sharp and aggressive. + Strangler + A boa constrictor: squeezes slowly, very human-like. + Alekhine + Dynamic attacks and deep combinations. + Anand + Quick, universal play with sharp openings. + Anderssen + A romantic attacker of the 19th century: sacrifices. + Bosboom + Offbeat openings and creative blitz play. + Botvinnik + Scientific, strategic play from deep preparation. + Fischer + Clear, classical and precise. + Karpov + Positional squeeze, prophylaxis and technique. + Kasparov + Initiative and powerful attack. + Kortchnoi + A tenacious defender and counter-attacker. + Larsen + Original and risky, with offbeat openings. + Lasker + A practical, psychological fighter. + Marshall + A swashbuckling attacker with gambits. + Morphy + Quick development and open lines. + Nimzowitsch + Restraint, blockade and overprotection. + Petrosian + Prophylaxis and safety first. + Reti + Hypermodern: controls the centre from afar. + Rubinstein + Classical positional play, great in endgames. + Spassky + A universal player, at home in any position. + Steinitz + The founder of positional play, a stubborn defender. + Tal + The magician from Riga: sacrifices and attack. + Tarrasch + Classical rules: space, development, active pieces. + Topalov + Aggressive and dynamic, sacrifices the exchange. + plays like a human + strong, with a style + Like a human + Maia does not pick a style: she plays like people of her rating. + Rodent’s own rating (UCI_Elo): it does not match a person’s Elo. + Rodent resigns + Rodent resigned + Rodent declines the draw + Rodent declined; offer again after two of its moves + Its position is lost. Accept the win, or play to the end? + Play + Play the computer + Strength: %1$s + Who to play + A character is a style and openings; the slider sets the strength. + Great players + Characters + Change + %1$s, great player + %1$s, character + Character: %1$s + Rodent IV and its opening books are on the phone + Rodent IV opening books: %1$s MB, downloaded once from github.com + From a position no opening book is needed: Rodent IV plays at once + No book + No book: play without the opening book + Rodent IV opening books + Rodent IV — opening books + downloaded · %1$s MB + not downloaded · %1$s MB + Opening books deleted + Rodent answers a draw offer with Stockfish: download it in the game screen (“Engine”) + Rodent did not start. + Restart + From here on, a game against Rodent IV %1$s · %2$s. + Rodent stopped during the game. + %1$s, from %2$s to %3$s + Strength + Delete the opening books diff --git a/androidApp/scripts/rodent4.sh b/androidApp/scripts/rodent4.sh new file mode 100755 index 0000000..f8e8db6 --- /dev/null +++ b/androidApp/scripts/rodent4.sh @@ -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//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}" diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 5694654..1f0f27d 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -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}" } }; diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 30bd94a..4ad7451 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -28,7 +28,6 @@ mod player_games; mod reference; mod review; mod rodent4_download; -mod rodent4_files; mod rodent_download; mod san; mod settings; diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 82dd833..35416a5 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -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; + 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 { + fn installed(self) -> Option { 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 { 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, @@ -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, } -/// 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, + rx: Receiver<(u64, Option, Duration)>, + generation: u64, + error: Arc>>, + }, + /// 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, - rx: Receiver<(u64, Option, Duration)>, - generation: u64, - /// Loading failed: why (shown to the user). - pub error: Arc>>, + 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, ctx: &egui::Context, ) -> Opponent { - let (tx, req_rx) = channel::(); - let (ans_tx, rx) = channel(); - let error = Arc::new(Mutex::new(None)); - let err = error.clone(); + let 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::().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 { - 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), } } diff --git a/apps/desktop/src/rodent4_download.rs b/apps/desktop/src/rodent4_download.rs index e19ad1b..03817e8 100644 --- a/apps/desktop/src/rodent4_download.rs +++ b/apps/desktop/src/rodent4_download.rs @@ -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 { 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 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 } result } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_file_is_where_the_engine_looks_for_it() { - assert_eq!(COMMIT.len(), 40); - assert!(FILES.iter().any(|f| f.0 == "personalities/basic.ini")); - assert!(FILES.iter().any(|f| f.0 == "personalities/tal.txt")); - assert!(FILES.iter().any(|f| f.0 == "books/rodent.bin")); - assert!(FILES.iter().all(|f| f.2.len() == 64 && !f.0.contains(".."))); - assert_eq!(url_path("books/#readme.txt"), "books/%23readme.txt"); - // The books copied under the names the personalities use are downloaded. - for (file, _) in BOOK_NAMES { - assert!(FILES.iter().any(|f| f.0 == *file), "{file}"); - } - } -} diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index afd36de..f409152 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -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}; diff --git a/crates/mobile-api/src/play.rs b/crates/mobile-api/src/play.rs index 09fe51b..2862142 100644 --- a/crates/mobile-api/src/play.rs +++ b/crates/mobile-api/src/play.rs @@ -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 { 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 { - 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 { + 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 { + 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 { + ::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 { + // 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, at: u32, pause_ms: u64) -> Option { + 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 { + 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); + } } diff --git a/crates/play/Cargo.toml b/crates/play/Cargo.toml index b2bf56c..4713787 100644 --- a/crates/play/Cargo.toml +++ b/crates/play/Cargo.toml @@ -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 diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index 26eb512..f4b9f39 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -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)] diff --git a/crates/play/src/rodent.rs b/crates/play/src/rodent.rs new file mode 100644 index 0000000..6865562 --- /dev/null +++ b/crates/play/src/rodent.rs @@ -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 { + 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, 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, +} + +#[derive(Default)] +struct Shared { + state: Mutex, + 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, + shared: Arc, +} + +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, + use_book: bool, + wake: Box, + ) -> RodentPlayer { + let (tx, rx) = channel::(); + 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 = 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::().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 { + 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 { + 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 { + 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::::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); + } +} diff --git a/apps/desktop/src/rodent4_files.rs b/crates/play/src/rodent4_files.rs similarity index 84% rename from apps/desktop/src/rodent4_files.rs rename to crates/play/src/rodent4_files.rs index e7d3611..aaf115f 100644 --- a/apps/desktop/src/rodent4_files.rs +++ b/crates/play/src/rodent4_files.rs @@ -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"), +]; diff --git a/crates/uci/src/engine.rs b/crates/uci/src/engine.rs index f5f5785..6377e6e 100644 --- a/crates/uci/src/engine.rs +++ b/crates/uci/src/engine.rs @@ -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. + #else + #include + #include +- #ifndef ANDROID ++ #if !defined(ANDROID) && !defined(__ANDROID__) // bionic has no wordexp + #include + #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); diff --git a/packaging/rodent-iv/think-thread.patch b/packaging/rodent-iv/think-thread.patch new file mode 100644 index 0000000..c0c7b30 --- /dev/null +++ b/packaging/rodent-iv/think-thread.patch @@ -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 diff --git a/scripts/rodent4-manifest.py b/scripts/rodent4-manifest.py index c19dfbe..07f8221 100644 --- a/scripts/rodent4-manifest.py +++ b/scripts/rodent4-manifest.py @@ -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 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- """ 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)