From 07a9e120b1a6cedaa2043024626b6a173a622452 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 26 Oct 2026 16:30:16 +0300 Subject: [PATCH] =?UTF-8?q?Android:=20Maia=20on=20her=20own=20scale=20(600?= =?UTF-8?q?=E2=80=932600);=20games=20written=20into=20the=20player's=20dat?= =?UTF-8?q?abase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As on the desktop (decisions «Партии игрока записываются сами», «Сила соперника — по шкале самого движка»): - mobile-api: Maia plays the rating on the slider, temperature 1; the sheet says it is her own rating, not a person's Elo. - PlayerGames: « — games against the computer» (no name: «Games against the computer»), an own database made at the first game; a game ends → written once (the mark kept with commit, guarded by the game's serial against a rematch); a game put aside and let go (×, «Start new», Maia failing) → written unfinished, once both have moved. - Play sheet: «Your name» with the phone's players (filtered by what is typed), the line where games go; result card «✓ В «…», № n ›» (a new database said there), opens it; no third button; a failed write said with its reason. ♞ on the row, «пишутся сами»; a setting. - «Play from here» and «Continue it» inside a play game show the new game. Checked on the emulator by the tester (kill right after the end, rematch, rename/delete of the database, setting off) and the designer. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- .../chesspenguin/ChessPenguinApp.kt | 3 + .../vrubelroman/chesspenguin/Navigation.kt | 2 +- .../chesspenguin/data/MaiaGames.kt | 23 +++- .../chesspenguin/data/PlayerGames.kt | 111 ++++++++++++++++++ .../vrubelroman/chesspenguin/data/Settings.kt | 4 + .../chesspenguin/ui/DatabasesScreen.kt | 27 ++++- .../vrubelroman/chesspenguin/ui/GameScreen.kt | 52 +++++++- .../vrubelroman/chesspenguin/ui/PlayMode.kt | 49 +++++++- .../vrubelroman/chesspenguin/ui/PlaySheet.kt | 50 +++++++- .../vrubelroman/chesspenguin/ui/SaveGame.kt | 4 + .../chesspenguin/ui/SettingsScreen.kt | 1 + .../app/src/main/res/values-de/strings.xml | 19 ++- .../app/src/main/res/values-es/strings.xml | 19 ++- .../app/src/main/res/values-fr/strings.xml | 19 ++- .../app/src/main/res/values-it/strings.xml | 19 ++- .../app/src/main/res/values-kk/strings.xml | 19 ++- .../app/src/main/res/values-pt/strings.xml | 19 ++- .../app/src/main/res/values-ru/strings.xml | 19 ++- .../app/src/main/res/values-uz/strings.xml | 19 ++- .../app/src/main/res/values/strings.xml | 19 ++- crates/mobile-api/src/play.rs | 17 ++- docs/decisions.md | 2 +- docs/design/player-games.md | 19 ++- 24 files changed, 487 insertions(+), 55 deletions(-) create mode 100644 androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 4889d5d..8ccfc68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,14 +10,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https games go; the result strip says «Written to …, No. n · Open». A game the program stopped in (a crash, a power cut) is written at the next start, unfinished. Several players of one computer each get their own database (the ▾ list by the name). It can - be turned off: Settings → Interface → Your databases. + be turned off: Settings → Interface → Your databases. Android: the same in «My + databases» (♞), the result card says where the game went; a game put aside and let + go is written unfinished; Settings → «Write games against Maia…». - Play against Rodent V (desktop, Linux and Windows): a strong engine with a style — balanced, attacking, chaotic, restricting, classical, or Tal. It is downloaded once on request (48 MB, the authors' release). - The opponent's strength is on the engine's own scale, as its authors give it: Maia 600–2600, Rodent V 800–3000 (its UCI_Elo). The dialog says that these are the engines' ratings, not a person's Elo. (1.5's slider showed Maia's strength measured on the - Lichess blitz scale; a remembered strength keeps its number.) + Lichess blitz scale; a remembered strength keeps its number.) Android too: Maia + 600–2600. - Offer Maia a draw (desktop and Android): she accepts when she is clearly worse, or when the position is about level (at most +0.2 for her) and has kept its character for her last three moves; after a refusal, again two of her moves later. She judges with 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 618fcec..f95231c 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 @@ -11,6 +11,7 @@ import io.github.vrubelroman.chesspenguin.data.DbEntry 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.Sounds import io.github.vrubelroman.chesspenguin.data.Library import io.github.vrubelroman.chesspenguin.data.OnlineDownloads @@ -37,6 +38,8 @@ class ChessPenguinApp : Application() { val maiaFiles by lazy { MaiaFiles(this, scope) } /// The game against Maia 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) } /// The sounds of moves and of the end of a game (android-play.md §33). val sounds by lazy { Sounds(this, settings) } /// Games from Lichess and Chess.com being downloaded (android-ui.md §23). diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt index 3121775..e572cee 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt @@ -133,7 +133,7 @@ fun MainNavigation() { GameScreen(PLAY_GAME, 0, "", onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.removeLastOrNull() backStack.add(PlayKey) - }) + }, onOpenDatabase = { id -> backStack.add(Games(id)) }) } entry { key -> GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }) 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 9b180db..166b0ce 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 @@ -34,10 +34,18 @@ class MaiaGames(context: Context) { /// The PGN of the game in hand. fun pgn(): String? = runCatching { file.readText() }.getOrNull() + /// Which game is in hand: bumped by each new one (a write that ends after a rematch + /// began is not taken for the new game's). + var serial = 0 + private set + /// A new game: it replaces the one in hand. fun begin(pgn: String, meta: PlayMeta) { + serial++ write(pgn) prefs.edit() + .remove("writtenDb") + .remove("writtenIndex") .putInt("strength", meta.strength) .putBoolean("white", meta.userWhite) .putString("name", meta.name) @@ -55,10 +63,23 @@ class MaiaGames(context: Context) { /// The game ended: it is not offered to go on with any more. fun finish(pgn: String) { save(pgn) - prefs.edit().putBoolean("over", true).apply() + // At once (commit): a game over must not come back as one to go on with. + prefs.edit().putBoolean("over", true).commit() _current.value = _current.value?.copy(over = true) } + /// The game was written into its player's database: database and number there. + fun setWritten(id: String, index: UInt, game: Int) { + if (game != serial) return + prefs.edit().putString("writtenDb", id).putLong("writtenIndex", index.toLong()).commit() + } + + /// Where the game in hand was written, if it was. + fun written(): Pair? { + val id = prefs.getString("writtenDb", null) ?: return null + return id to prefs.getLong("writtenIndex", 0).toUInt() + } + /// The game is gone (left after its end, removed by the user). fun clear() { file.delete() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt new file mode 100644 index 0000000..66375cf --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PlayerGames.kt @@ -0,0 +1,111 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import io.github.vrubelroman.chesspenguin.R +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/// A game written into its player's database: the database, its number there (from 0), +/// and whether the database was made for it. +data class Written(val id: String, val name: String, val index: UInt, val created: Boolean) + +/// The players' databases (docs/design/player-games.md §6, decisions «Партии игрока +/// записываются сами»): every game against Maia goes by itself into an own database of +/// its player — «Roman — games against the computer», made at their first game; without +/// a name, «Games against the computer». Only new games are added; replacing and +/// deleting stay the user's. +class PlayerGames(private val context: Context, private val library: Library) { + private val store = context.getSharedPreferences("players", Context.MODE_PRIVATE) + private val lock = Mutex() + + /// The name as it is kept: trimmed, inner spaces single. + fun tidy(name: String): String = name.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.joinToString(" ") + + /// Names that are the same player: «Иван» and «иван ». + private fun key(name: String) = tidy(name).lowercase() + + /// The name of a new database for the player. + fun dbName(name: String): String = tidy(name).let { + if (it.isEmpty()) context.getString(R.string.player_db_shared) else context.getString(R.string.player_db_name, it) + } + + /// The player's database, while it is on the list. + fun database(name: String): DbEntry? = + store.getString("db:" + key(name), null)?.let { library.entry(it) }?.takeIf { it.source == Source.Own } + + /// Whether `id` is a player's database (a knight on its row). + fun isPlayers(id: String): Boolean = store.all.any { (k, v) -> k.startsWith("db:") && v == id } + + /// The players who played here, the last first (named ones). + fun players(): List = + (store.getString("order", "") ?: "").split('\n').filter { it.isNotEmpty() } + .mapNotNull { store.getString("name:$it", null) } + + /// The player who starts a game goes first in the list. + fun remember(name: String) { + val k = key(name) + if (k.isEmpty()) return + val order = listOf(k) + (store.getString("order", "") ?: "").split('\n').filter { it.isNotEmpty() && it != k } + store.edit().putString("name:$k", tidy(name)).putString("order", order.joinToString("\n")).apply() + } + + /// The game in hand let go unfinished (× on its card, a new game in its place, Maia + /// failing): kept in the player's database with `*` once both have moved, unless it + /// was written already or the user turned writing off. What is in hand is taken at + /// once (the caller may put a new game there right after); `then` on `scope`. + /// Whether it is written (a game without moves of both sides is not). + fun keepUnfinished(games: MaiaGames, record: Boolean, scope: CoroutineScope, then: (Written) -> Unit = {}): Boolean { + if (!wouldKeep(games, record)) return false + val m = games.current.value ?: return false + val pgn = games.pgn() ?: return false + scope.launch { runCatching { writeUnfinished(m, pgn) }.getOrNull()?.let(then) } + return true + } + + /// Whether the game in hand, let go now, would be kept. + fun wouldKeep(games: MaiaGames, record: Boolean): Boolean { + val m = games.current.value ?: return false + if (m.over || !record || games.written() != null) return false + val pgn = games.pgn() ?: return false + return plies(pgn) - m.floor >= 2 + } + + /// Half-moves of the main line. + private fun plies(pgn: String): Int { + val s = uniffi.mobile_api.GameSession.fromPgn(pgn) + try { + val d = s.data() + var n = 0 + var plies = 0 + while (true) { + n = d.nodes[n].children.firstOrNull()?.toInt() ?: return plies + plies++ + } + } finally { + s.close() + } + } + + private suspend fun writeUnfinished(m: PlayMeta, pgn: String): Written { + val s = uniffi.mobile_api.GameSession.fromPgn(pgn) + val text = try { + s.setData(listOf(uniffi.mobile_api.Tag("Termination", "Unterminated")), "*") + s.pgn() + } finally { + s.close() + } + return write(m.name, text) + } + + /// Adds `pgn` to the player's database, making it first when they have none. + suspend fun write(name: String, pgn: String): Written = lock.withLock { + val existing = database(name) + val entry = existing ?: library.createOwn(dbName(name)).also { + store.edit().putString("db:" + key(name), it.id).apply() + } + val n = library.saveOwn(entry.id, null, pgn) + Written(entry.id, entry.name, n, existing == null) + } +} 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 1ddd1b3..271637d 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 @@ -36,6 +36,8 @@ data class Prefs( 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). + val recordGames: Boolean = true, ) /// Half the cores, at most 2: the engine leaves the phone's interface room (§9). @@ -76,6 +78,7 @@ class Settings(context: Context) { maiaColor = store.getInt("maiaColor", d.maiaColor).coerceIn(-1, 1), yourName = store.getString("yourName", d.yourName) ?: d.yourName, sound = store.getBoolean("sound", d.sound), + recordGames = store.getBoolean("recordGames", d.recordGames), ) } @@ -100,6 +103,7 @@ class Settings(context: Context) { .putInt("maiaColor", p.maiaColor) .putString("yourName", p.yourName) .putBoolean("sound", p.sound) + .putBoolean("recordGames", p.recordGames) .apply() } } 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 3290f9f..f7be3fb 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 @@ -176,6 +176,7 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett val theApp = app() val adjourned by theApp.maiaGames.current.collectAsState() val playRemovedText = stringResource(R.string.play_removed) + val keptText = stringResource(R.string.player_kept_unfinished) var playing by remember { mutableStateOf(false) } // A game put aside: asked about before a new one replaces it. var askingAdjourned by remember { mutableStateOf(false) } @@ -276,6 +277,18 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett ) TextButton(onClick = onPlay) { Text(stringResource(R.string.play_continue)) } IconButton(onClick = { + // Played on both sides: kept in the player's database, + // unfinished (no «Undo»: it is there to be deleted). + val kept = theApp.playerGames.keepUnfinished(theApp.maiaGames, theApp.settings.prefs.value.recordGames, scope) { w -> + scope.launch { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(String.format(keptText, w.name)) + } + } + if (kept) { + theApp.maiaGames.clear() + return@IconButton + } val pgn = theApp.maiaGames.pgn() theApp.maiaGames.clear() scope.launch { @@ -321,6 +334,7 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett items(own, key = { it.id }) { e -> OwnRow( e, + player = theApp.playerGames.isPlayers(e.id), onOpen = { onOpen(e.id) }, onRename = { renaming = e }, onExport = { @@ -526,7 +540,7 @@ private fun NewOwnDialog(suggested: String, onDismiss: () -> Unit, onCreate: (St /// An own database: its games are the user's, kept on the phone (android-play.md §30.2). @OptIn(ExperimentalFoundationApi::class) @Composable -private fun OwnRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, onExport: () -> Unit, onDelete: () -> Unit, modifier: Modifier) { +private fun OwnRow(e: DbEntry, player: Boolean, onOpen: () -> Unit, onRename: () -> Unit, onExport: () -> Unit, onDelete: () -> Unit, modifier: Modifier) { var menu by remember { mutableStateOf(false) } val n = e.games ?: 0 Box(modifier) { @@ -541,11 +555,18 @@ private fun OwnRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, onExpor Box( Modifier.size(40.dp).clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.primaryContainer), contentAlignment = Alignment.Center, - ) { Icon(Icons.Rounded.EditNote, null, tint = MaterialTheme.colorScheme.onPrimaryContainer) } + ) { + // A player's database (games against Maia written by themselves): a knight. + if (player) { + Text("♞", style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onPrimaryContainer) + } else { + Icon(Icons.Rounded.EditNote, null, tint = MaterialTheme.colorScheme.onPrimaryContainer) + } + } Column(Modifier.weight(1f).padding(start = 16.dp)) { Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( - pluralStringResource(R.plurals.games_count, n, groupDigits(n)) + " · " + stringResource(R.string.own_on_phone), + pluralStringResource(R.plurals.games_count, n, groupDigits(n)) + " · " + stringResource(if (player) R.string.player_db_row else R.string.own_on_phone), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, 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 2ea9411..7f3532c 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 @@ -109,6 +109,7 @@ import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.viewmodel.compose.viewModel import io.github.vrubelroman.chesspenguin.data.Source +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 @@ -137,9 +138,19 @@ private data class Preview(val line: EngineLine, val step: Int, val best: Boolea /// under the thumb; ‹ › page the games of the list (android-ui.md §7). @OptIn(ExperimentalMaterial3Api::class) @Composable -fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, onSettings: () -> Unit, onPlayGame: () -> Unit = {}) { +fun GameScreen( + db: String, + startPlace: Int, + query: String, + onBack: () -> Unit, + onSettings: () -> Unit, + onPlayGame: () -> Unit = {}, + onOpenDatabase: (String) -> Unit = {}, +) { val app = app() val context = LocalContext.current + // Configuration-aware (the language can change while the screen is up). + val resources = androidx.compose.ui.platform.LocalResources.current val prefs by app.settings.prefs.collectAsState() val libraryEntries by app.library.entries.collectAsState() val dbEntry = libraryEntries.firstOrNull { it.id == db } @@ -184,7 +195,11 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o return@LaunchedEffect } held.key = PLAY_GAME - held.savedTo = null + // A game written into its player's database is that database's game. + val written = app.maiaGames.written() + held.savedTo = written + held.recordError.value = null + held.recorded.value = written?.let { (id, n) -> Written(id, app.library.entry(id)?.name ?: "", n, false) } val s = GameSession.fromPgn(pgn) edit = s val d = s.data() @@ -443,6 +458,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o fun persist() { if (run != null) edit?.let { app.maiaGames.save(it.pgn()) } } + val recordFailedText = stringResource(R.string.player_write_failed) fun finishGame(over: PlayOver) { val r = run ?: return val e = edit ?: return @@ -452,7 +468,27 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o e.setData(listOf(uniffi.mobile_api.Tag("Termination", "Normal")), over.result) game = e.data().copy(notes = held.notes) r.over.value = over - app.maiaGames.finish(e.pgn()) + val pgn = e.pgn() + app.maiaGames.finish(pgn) + // Into the player's database by itself (player-games.md); a new one is said once. + val serial = app.maiaGames.serial + if (prefs.recordGames && app.maiaGames.written() == null) scope.launch { + runCatching { app.playerGames.write(r.meta.name, pgn) } + .onSuccess { w -> + app.maiaGames.setWritten(w.id, w.index, serial) + // The screen still shows that game (no rematch since). + if (app.maiaGames.serial == serial) { + if (edit === e && e.pgn() == pgn) e.markSaved() + held.savedTo = w.id to w.index + held.recorded.value = w + } + } + .onFailure { err -> + if (app.maiaGames.serial != serial) return@onFailure + val name = app.playerGames.database(r.meta.name)?.name ?: app.playerGames.dbName(r.meta.name) + held.recordError.value = String.format(recordFailedText, name, err.message ?: err.javaClass.simpleName) + } + } app.sounds.play( when (over.heading) { R.string.play_won -> io.github.vrubelroman.chesspenguin.data.Sound.Success @@ -758,6 +794,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o onResign = { resigning = true }, onDraw = ::offerDraw, onAbort = { + app.playerGames.keepUnfinished(app.maiaGames, prefs.recordGames, app.scope) app.maiaGames.clear() onBack() }, @@ -927,6 +964,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o maiaRetry = true }, onAbort = { + app.playerGames.keepUnfinished(app.maiaGames, prefs.recordGames, app.scope) app.maiaGames.clear() onBack() }, @@ -934,6 +972,9 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o runOver != null && !resultClosed -> ResultCard( runOver, saved = held.savedTo != null && !modified, + recorded = held.recorded.value, + recordError = held.recordError.value, + onOpenRecorded = { id -> onOpenDatabase(id) }, onAnalyse = { val e = edit // The report takes the place: the card would be squeezed. @@ -1283,8 +1324,10 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o onPlay = { strength, white, name -> playFrom = null val s = runCatching { edit?.playFrom(fromMove.toUInt()) }.getOrNull() ?: return@PlaySheet - beginMaiaGame(app, s, strength, white, name, depth(g, fromMove), eventText, context.getString(R.string.play_note_from, strength.toString())) + beginMaiaGame(app, s, strength, white, name, depth(g, fromMove), eventText, resources.getString(R.string.play_note_from, strength.toString())) s.close() + // On the play screen itself the game in hand is read anew. + held.key = null onPlayGame() }, onDismiss = { playFrom = null }, @@ -1296,6 +1339,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o if (askAt != null && adjournedMeta != null) { AdjournedQuestion(adjournedMeta, onContinue = { askFrom = null + held.key = null onPlayGame() }, onNew = { askFrom = null 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 23dafec..00f745a 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 @@ -1,5 +1,11 @@ package io.github.vrubelroman.chesspenguin.ui +import androidx.compose.foundation.layout.wrapContentHeight + +import androidx.compose.foundation.layout.heightIn + +import androidx.compose.foundation.clickable + import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -27,6 +33,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Alignment +import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.res.stringResource @@ -164,7 +171,17 @@ fun OfferCard(onAccept: () -> Unit, onPlayOn: () -> Unit) { /// The end of the game (§31.4): the result, then analyse, rematch, save. @Composable -fun ResultCard(over: PlayOver, saved: Boolean, onAnalyse: () -> Unit, onRematch: () -> Unit, onSave: () -> Unit, onClose: () -> Unit) { +fun ResultCard( + over: PlayOver, + saved: Boolean, + recorded: io.github.vrubelroman.chesspenguin.data.Written?, + recordError: String?, + onOpenRecorded: (String) -> Unit, + onAnalyse: () -> Unit, + onRematch: () -> Unit, + onSave: () -> Unit, + onClose: () -> Unit, +) { Card { Row(verticalAlignment = Alignment.CenterVertically) { Text( @@ -174,14 +191,32 @@ fun ResultCard(over: PlayOver, saved: Boolean, onAnalyse: () -> Unit, onRematch: ) IconButton(onClick = onClose) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } } + // Where the game went by itself: its player's database, opened by a tap. + // A new database says so here, once (no snackbar over the buttons). + recorded?.let { w -> + Text( + stringResource(if (w.created) R.string.player_written_new else R.string.player_written, w.name, (w.index + 1u).toString()), + Modifier.fillMaxWidth().heightIn(min = 40.dp).clickable { onOpenRecorded(w.id) }.wrapContentHeight(Alignment.CenterVertically), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.primary, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + recordError?.let { + Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, maxLines = 3) + } Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { val pad = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp) Button(onClick = onAnalyse, modifier = Modifier.weight(1f), contentPadding = pad) { Text(stringResource(R.string.play_analyse_short), maxLines = 1, overflow = TextOverflow.Ellipsis) } OutlinedButton(onClick = onRematch, modifier = Modifier.weight(1f), contentPadding = pad) { Text(stringResource(R.string.play_rematch).removePrefix("↻ "), maxLines = 1, overflow = TextOverflow.Ellipsis) } - OutlinedButton(onClick = onSave, enabled = !saved, modifier = Modifier.weight(1f), contentPadding = pad) { - Text(stringResource(if (saved) R.string.play_saved else R.string.play_save), maxLines = 1, overflow = TextOverflow.Ellipsis) + // Written by itself: the line above says where; no third button. + if (recorded == null) { + OutlinedButton(onClick = onSave, enabled = !saved, modifier = Modifier.weight(1f), contentPadding = pad) { + Text(stringResource(if (saved) R.string.play_saved else R.string.play_save), maxLines = 1, overflow = TextOverflow.Ellipsis) + } } } } @@ -220,6 +255,9 @@ fun beginMaiaGame( 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)) } @@ -239,10 +277,13 @@ fun FailureCard(onRetry: () -> Unit, onAbort: () -> Unit) { /// replaced). @Composable fun AdjournedQuestion(meta: PlayMeta, onContinue: () -> Unit, onNew: () -> Unit, onDismiss: () -> Unit) { + val app = app() + // Said only when the game will be kept (moves of both sides, writing on). + 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())) }, - text = { Text(stringResource(R.string.play_adjourned_new_text)) }, + 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 56329ff..3a8eb4a 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 @@ -14,6 +14,10 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Close import androidx.compose.material3.Button +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -123,7 +127,51 @@ fun PlaySheet(from: PlayFrom?, onPlay: (Int, Boolean, String) -> Unit, onDismiss } } Spacer(Modifier.height(12.dp)) - OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.play_your_name)) }, singleLine = true) + // 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)) + } + } + // 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) } + } + }, + singleLine = true, + ) + ExposedDropdownMenu(expanded = picking && matching.isNotEmpty(), onDismissRequest = { picking = false }) { + matching.forEach { p -> + DropdownMenuItem(text = { Text(p) }, onClick = { + name = p + picking = false + }) + } + } + } 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) { diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt index fd0fa3e..7cc5995 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/SaveGame.kt @@ -50,6 +50,10 @@ class GameEdit : ViewModel() { var notes: List = emptyList() /// Where a new game or a copy was saved: saving again replaces it there. var savedTo: Pair? = null + /// Where the game against Maia went by itself (its player's database), if it did. + val recorded = mutableStateOf(null) + /// Why it did not (the card says so; «Save…» stays). + val recordError = mutableStateOf(null) /// An opening being learned over the game (android-play.md §32), how far, the board's side. val trainer = mutableStateOf(null) /// The game against Maia, when this screen plays one (§31). 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 849c896..f6be7f5 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 @@ -118,6 +118,7 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () -> Toggle(stringResource(R.string.best_arrow), prefs.bestArrow) { v -> set { it.copy(bestArrow = v) } } Toggle(stringResource(R.string.sound), prefs.sound) { v -> set { it.copy(sound = v) } } Toggle(stringResource(R.string.vibration), prefs.vibration) { v -> set { it.copy(vibration = v) } } + Toggle(stringResource(R.string.record_games), prefs.recordGames) { v -> set { it.copy(recordGames = v) } } Group(stringResource(R.string.group_look)) Item(stringResource(R.string.board_and_pieces), boardLabel(prefs.board) + " · " + prefs.pieces.dir, onClick = onBoardStyle) diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index f231948..158729a 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -480,7 +480,7 @@ Schwarz Zufällig Gegner — Maia %1$s - Ihre gemessene Spielstärke, auf der Lichess-Blitz-Skala. + 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 Spielen @@ -497,7 +497,7 @@ Ab hier eine Partie gegen Maia %1$s. Abbrechen Gegen Maia spielen - Ihr Name (für die Partie) + Ihr Name Maia ist heruntergeladen Erneut versuchen Ihre Stellung ist verloren. Sieg annehmen oder weiterspielen? @@ -526,10 +526,23 @@ Eine Partie gegen Maia %1$s ist zurückgestellt Fortsetzen Neue beginnen - Eine neue Partie ersetzt sie. + Eine neue Partie ersetzt sie; das Gespielte kommt unvollendet in die Datenbank des Spielers. Remis durch Einigung Maia lehnt das Remis ab Maia hat abgelehnt; nach zwei ihrer Züge wieder anbieten Maia beantwortet Remis mit Stockfish: über „Engine“ herunterladen + %1$s — Partien gegen den Computer + Partien gegen den Computer + ✓ 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 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. + Partien werden nicht von selbst gespeichert (Einstellungen). + ✓ Neue Datenbank „%1$s“, Nr. %2$s › + Konnte nicht in „%1$s“ schreiben: %2$s + Eine neue Partie ersetzt sie. diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index e4b56db..d5e362e 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -488,7 +488,7 @@ Negras Al azar Rival — Maia %1$s - Su fuerza medida, en la escala de blitz de Lichess. + 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 Jugar @@ -505,7 +505,7 @@ A partir de aquí, una partida contra Maia %1$s. Abortar Jugar con Maia - Tu nombre (para la partida) + Tu nombre Maia está descargada Reintentar Su posición está perdida. ¿Aceptar la victoria o seguir? @@ -534,10 +534,23 @@ Hay una partida aplazada contra Maia %1$s Continuarla Empezar una nueva - Una partida nueva la sustituye. + Una partida nueva la sustituye; lo jugado va sin terminar a la base del jugador. Tablas por acuerdo Maia rechaza las tablas Maia lo rechazó; ofrece de nuevo tras dos de sus jugadas Maia responde a las tablas con Stockfish: descárgalo con «Motor» + %1$s — partidas contra el ordenador + Partidas contra el ordenador + ✓ 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 + 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. + Las partidas no se guardan solas (Ajustes). + ✓ Base nueva «%1$s», n.º %2$s › + No se pudo escribir en «%1$s»: %2$s + Una partida nueva la sustituye. diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 6949078..fff8512 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -488,7 +488,7 @@ Noirs Au hasard Adversaire — Maia %1$s - Sa force mesurée, sur l’échelle du blitz Lichess. + 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 Jouer @@ -505,7 +505,7 @@ À partir d’ici, une partie contre Maia %1$s. Abandonner Jouer contre Maia - Votre nom (pour la partie) + Votre nom Maia est téléchargée Réessayer Sa position est perdue. Accepter la victoire ou continuer ? @@ -534,10 +534,23 @@ Une partie contre Maia %1$s est en attente La continuer En commencer une nouvelle - Une nouvelle partie la remplace. + Une nouvelle partie la remplace ; ce qui a été joué va, inachevé, dans la base du joueur. Nulle par accord mutuel Maia refuse la nulle Maia a refusé ; reproposez après deux de ses coups Maia répond à la nulle avec Stockfish : téléchargez-le avec « Moteur » + %1$s — parties contre l’ordinateur + Parties contre l’ordinateur + ✓ 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 + 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. + Les parties ne sont pas enregistrées d’elles-mêmes (Réglages). + ✓ Nouvelle base « %1$s », n° %2$s › + Impossible d’écrire dans « %1$s » : %2$s + Une nouvelle partie la remplace. diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index acf42b3..549a34f 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -488,7 +488,7 @@ Nero Casuale Avversario — Maia %1$s - La sua forza misurata, sulla scala del blitz di Lichess. + 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 Gioca @@ -505,7 +505,7 @@ Da qui, una partita contro Maia %1$s. Annulla Gioca con Maia - Il tuo nome (per la partita) + Il tuo nome Maia è scaricata Riprova La sua posizione è persa. Accettare la vittoria o continuare? @@ -534,10 +534,23 @@ C’è una partita sospesa contro Maia %1$s Continuala Iniziarne una nuova - Una nuova partita la sostituisce. + Una nuova partita la sostituisce; quanto giocato va, non finito, nel database del giocatore. Patta per accordo Maia rifiuta la patta Maia ha rifiutato; riproponi dopo due sue mosse Maia risponde alla patta con Stockfish: scaricalo con «Motore» + %1$s — partite contro il computer + Partite contro il computer + ✓ 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 + 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. + Le partite non vengono salvate da sole (Impostazioni). + ✓ Nuovo database «%1$s», n. %2$s › + Impossibile scrivere in «%1$s»: %2$s + Una nuova partita la sostituisce. diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 67cc7a7..9846e45 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -481,7 +481,7 @@ Қаралар Кездейсоқ Қарсылас — Maia %1$s - Оның өлшенген күші, Lichess блиц шкаласы бойынша. + Maia-ның өз рейтингі: ол адамның Эло рейтингіне сәйкес келмейді. Maia бір рет жүктеледі (%1$s МБ, huggingface.co сайтынан — авторлардың өз файлы). Жүктеп алып ойнау Ойнау @@ -498,7 +498,7 @@ Бұдан әрі — Maia %1$s-мен ойын. Тоқтату Maia-мен ойнау - Атыңыз (ойын жазбасы үшін) + Атыңыз Maia жүктелді Қайталау Оның позициясы ұтылды. Жеңісті қабылдайсыз ба, әлде жалғастырасыз ба? @@ -527,10 +527,23 @@ Maia %1$s-мен кейінге қалдырылған ойын бар Жалғастыру Жаңасын бастау - Жаңа ойын оның орнын басады. + Жаңа ойын оның орнын басады; ойналғаны аяқталмаған күйде ойыншы базасына жазылады. Тең келісім бойынша Maia тең ойыннан бас тартады Maia бас тартты; оның екі жүрісінен кейін қайта ұсыныңыз Maia тең ойынға Stockfish арқылы жауап береді: оны «Қозғалтқыш» батырмасымен жүктеңіз + %1$s — компьютермен ойындар + Компьютермен ойындар + ✓ «%1$s» базасында, № %2$s › + Ойын аяқталмаған күйде «%1$s» базасына жазылды + өзі жазылады + Maia-мен ойындарды ойыншы базасына жазу + Ойындар «%1$s» базасына жазылады + Ойындар жаңа «%1$s» базасына жазылады. + Атсыз ойындар «%1$s» базасына түседі. Өз базаңыз болуы үшін атыңызды жазыңыз. + Ойындар өзі жазылмайды (Баптаулар). + ✓ Жаңа база «%1$s», № %2$s › + «%1$s» базасына жазу мүмкін болмады: %2$s + Жаңа ойын оның орнын басады. diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 0ef5259..f03ddbb 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -489,7 +489,7 @@ Pretas Aleatório Adversário — Maia %1$s - A força medida dela, na escala de blitz do Lichess. + 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 Jogar @@ -506,7 +506,7 @@ A partir daqui, uma partida contra Maia %1$s. Abortar Jogar com a Maia - Seu nome (para a partida) + O seu nome A Maia foi baixada Tentar de novo A posição dela está perdida. Aceitar a vitória ou continuar? @@ -535,10 +535,23 @@ Há uma partida adiada contra a Maia %1$s Continuá-la Começar uma nova - Uma nova partida a substitui. + Uma nova partida a substitui; o que foi jogado vai, inacabado, para a base do jogador. Empate por acordo A Maia recusa o empate A Maia recusou; ofereça de novo após dois lances dela A Maia responde ao empate com o Stockfish: baixe-o com «Motor» + %1$s — partidas contra o computador + Partidas contra o computador + ✓ Em «%1$s», n.º %2$s › + Partida gravada inacabada em «%1$s» + gravadas sozinhas + Gravar as partidas contra a Maia 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. + As partidas não são gravadas sozinhas (Definições). + ✓ Nova base «%1$s», n.º %2$s › + Não foi possível gravar em «%1$s»: %2$s + Uma nova partida a substitui. diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index eef2e1a..09fac43 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -496,7 +496,7 @@ Чёрные Случайно Соперник — Maia %1$s - Её измеренная сила, по шкале блица Lichess. + Собственный рейтинг Maia: он не равен Эло человека. Maia скачивается один раз (%1$s МБ, с huggingface.co — файл самих авторов). Скачать и играть Играть @@ -513,7 +513,7 @@ Дальше — игра с Maia %1$s. Прервать Играть с Maia - Ваше имя (для записи партии) + Ваше имя Maia скачана Повторить Её позиция проиграна. Принять победу или доиграть? @@ -542,10 +542,23 @@ Есть отложенная партия с Maia %1$s Продолжить её Начать новую - Новая партия заменит её. + Новая партия заменит её; сыгранное запишется в базу игрока неоконченным. Ничья по соглашению Maia отказывается от ничьей Maia отказалась; снова можно предложить через два её хода Maia отвечает на ничью с помощью Stockfish: скачайте его кнопкой «Движок» + %1$s — партии с компьютером + Партии с компьютером + ✓ В «%1$s», № %2$s › + Партия записана в «%1$s» неоконченной + пишутся сами + Записывать партии с Maia в базу игрока + Партии записываются в «%1$s» + Партии будут записываться в новую базу «%1$s». + Без имени партии идут в «%1$s». Впишите имя — заведём вашу базу. + Партии сами не записываются (Настройки). + ✓ Создана база «%1$s», № %2$s › + Не удалось записать в «%1$s»: %2$s + Новая партия заменит её. diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index 5ae4d99..d0ec4f0 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -479,7 +479,7 @@ Qoralar Tasodifiy Raqib — Maia %1$s - Uning o‘lchangan kuchi, Lichess blits shkalasi bo‘yicha. + 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 O‘ynash @@ -496,7 +496,7 @@ Bundan keyin — Maia %1$s bilan o‘yin. To‘xtatish Maia bilan o‘ynash - Ismingiz (o‘yin yozuvi uchun) + Ismingiz Maia yuklab olindi Qayta urinish Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki davom etasizmi? @@ -525,10 +525,23 @@ Maia %1$s bilan to‘xtatilgan o‘yin bor Davom ettirish Yangisini boshlash - Yangi o‘yin uning o‘rnini oladi. + Yangi o‘yin uning o‘rnini oladi; o‘ynalgani tugallanmagan holda o‘yinchi bazasiga yoziladi. Durang kelishuv bo‘yicha Maia durangdan bosh tortadi Maia rad etdi; uning ikki yurishidan keyin yana taklif qiling Maia durangga Stockfish bilan javob beradi: uni «Dvigatel» tugmasi bilan yuklab oling + %1$s — kompyuter bilan o‘yinlar + Kompyuter bilan o‘yinlar + ✓ «%1$s» da, № %2$s › + O‘yin tugallanmagan holda «%1$s» ga yozildi + o‘zi yoziladi + Maia 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. + O‘yinlar o‘zi yozilmaydi (Sozlamalar). + ✓ Yangi baza «%1$s», № %2$s › + «%1$s» ga yozib bo‘lmadi: %2$s + Yangi o‘yin uning o‘rnini oladi. diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index 7d167bc..19c13cc 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -484,7 +484,7 @@ Black Random Opponent — Maia %1$s - Her measured strength, on the Lichess blitz scale. + 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 Play @@ -501,7 +501,7 @@ From here on, a game against Maia %1$s. Abort Play with Maia - Your name (for the game’s record) + Your name Maia is downloaded Try again Her position is lost. Accept the win or play on? @@ -530,10 +530,23 @@ There is a game put aside against Maia %1$s Continue it Start a new one - A new game replaces it. + A new game replaces it; what was played goes into the player’s database, unfinished. Draw 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») + %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 + 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. + Games are not written by themselves (Settings). + ✓ New database “%1$s”, No. %2$s › + Could not write to “%1$s”: %2$s + A new game replaces it. diff --git a/crates/mobile-api/src/play.rs b/crates/mobile-api/src/play.rs index 3d627f8..07114f1 100644 --- a/crates/mobile-api/src/play.rs +++ b/crates/mobile-api/src/play.rs @@ -4,7 +4,7 @@ use std::sync::Arc; -use maia::strength::{Model, choose, rating_input, temperature}; +use maia::strength::choose; use shakmaty::{CastlingMode, Chess}; use std::sync::Mutex; @@ -179,9 +179,10 @@ impl ResignJudge { } } -/// The weakest and strongest Maia on the phone (the small model's measured range). -pub const PHONE_MIN: u32 = 1100; -pub const PHONE_MAX: u32 = maia::strength::SMALL_MAX; +/// 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). #[uniffi::export] @@ -228,12 +229,8 @@ impl MaiaPlayer { ) })?; let strength = strength.clamp(PHONE_MIN, PHONE_MAX); - let p = self.maia.predict( - &history, - rating_input(Model::Small, strength), - opponent.unwrap_or(strength), - ); - choose(&p, temperature(Model::Small, strength), random) + let p = self.maia.predict(&history, strength, opponent.unwrap_or(strength)); + choose(&p, 1.0, random) .map(|m| m.to_uci(CastlingMode::Standard).to_string()) } } diff --git a/docs/decisions.md b/docs/decisions.md index 5db22a4..250165b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -119,7 +119,7 @@ ## Сила соперника — по шкале самого движка (2026-10-26) -Владелец: «запарился с калибровкой движков» — в диалоге игры два движка, Maia и Rodent V, у каждого **своя шкала, как её заявляют авторы**: Maia 600–2600 (рейтинг, на котором обучена сеть; ходы — выбором по её вероятностям, температура 1), Rodent V 800–3000 (UCI_Elo; у Rodent по-прежнему выбирается стиль). Под ползунком сказано, что это рейтинги самих движков и Эло человека они не соответствуют. Автопереключения Maia → Rodent за 2100 больше нет; при смене движка сила приводится в его диапазон. Пересчёт по замерам (`research/maia-strength.md`, `research/rodent.md`) остаётся исследованием и в программе не используется (на телефоне пока прежняя шкала Maia). +Владелец: «запарился с калибровкой движков» — в диалоге игры два движка, Maia и Rodent V, у каждого **своя шкала, как её заявляют авторы**: Maia 600–2600 (рейтинг, на котором обучена сеть; ходы — выбором по её вероятностям, температура 1), Rodent V 800–3000 (UCI_Elo; у Rodent по-прежнему выбирается стиль). Под ползунком сказано, что это рейтинги самих движков и Эло человека они не соответствуют. Автопереключения Maia → Rodent за 2100 больше нет; при смене движка сила приводится в его диапазон. Пересчёт по замерам (`research/maia-strength.md`, `research/rodent.md`) остаётся исследованием и в программе не используется На телефоне — так же, Maia 600–2600 (владелец, 2026-10-26). ## Партии игрока записываются сами (2026-10-26) diff --git a/docs/design/player-games.md b/docs/design/player-games.md index d9e97f9..9007cad 100644 --- a/docs/design/player-games.md +++ b/docs/design/player-games.md @@ -201,4 +201,21 @@ - клавиатура списка ▾ (↓/Alt+↓, Enter, Esc) и число партий в строке списка («Роман · 1350 · 14 партий»); - таблица базы игрока по умолчанию «новые сверху» (§5) — сейчас по номеру по возрастанию; - «Открыть» с выделенной строкой партии (§4) — проверить: сейчас это переход в библиотеку; -- телефон (§6) целиком. +- ~~телефон (§6) целиком~~ — сделан, см. §11.1. + +### 11.1. Телефон (проверка дизайнера 2026-10-26, снимки эмулятора 1080 × 2400) + +Сделано: поле «Ваше имя» со списком ▾ прежних игроков и строкой под ним (четыре состояния, число партий); запись в конце партии; строка «✓ В «…», № n ›» в карточке результата, открывает базу; снекбар о создании базы; ♞ и вторая строка в «Мои базы»; × на карточке отложенной пишет её неоконченной со снекбаром; флажок «Настройки → Партия», включён. Шкала соперника — 600–2600, собственный рейтинг Maia, под ползунком «Собственный рейтинг Maia: он не равен Эло человека.» + +К исправлению: +1. Снекбар «Создана база…» на 6 с закрывает кнопки карточки результата (Анализ/Реванш/Сохранить) ровно в момент, когда они нужны. Решение: снекбар убрать, а при создании строка карточки говорит это сама: «✓ Создана база «{db}», № 1 ›» (`✓ New database “{db}”, No. 1 ›`); дальше — «✓ В «{db}», № n ›». +2. Третья кнопка карточки при записанной партии — неактивная «✓ Сохранено»: дублирует строку «✓ В…» и занимает место. По §6 — «Новая» (новая партия с теми же настройками); «Сохранить…» остаётся только при выключенном флажке или ошибке записи. +3. Ошибка записи — общий «Не удалось сохранить партию», в карточке нет строки, кнопка «Сохранить…» активна. Нужен текст §8: «Не удалось записать в «{db}»: {reason}» (`Could not write to “{db}”: {reason}`). +4. Вторая строка базы игрока «2 партии · партии с компьютером» повторяет название слово в слово. Вместо — «2 партии · пишутся сами» (`2 games · recorded automatically`). +5. Строка «✓ В «…», № 1 ›» — цветом `onSurfaceVariant`, не похожа на нажимаемую. «›» (или всю строку) — `primary`. +6. Тихие записи неоконченной: «Начать новую» в вопросе об отложенной и «Прервать» при сбое Maia пишут партию без снекбара (§6 требует снекбар «Партия записана в «{db}» неоконченной»). Текст вопроса `play_adjourned_new_text` обещает запись всегда — и при выключенном флажке, и когда ходов меньше двух; показывать его только когда запись действительно будет, иначе прежний текст. +7. Строки под именем: «…в новую базу «…»» и «…в «…» · 2 партии» без точки, «Без имени…» — с точкой. Точки во всех или ни в одной (две фразы — значит во всех). +8. Подпись поля «Ваше имя (для записи партии)» — скобка лишняя, строка под полем объясняет; «Ваше имя» (`Your name`). +9. Список ▾ открывается касанием редактируемого поля и не фильтруется по набранному — при вводе нового имени закрывает строку под полем. Фильтровать по началу имени, не показывать при пустом совпадении; строка `players_menu` не используется — убрать или сделать заголовком списка. + +Отложено: число партий в строке списка («Роман · 14 партий»); таблица базы игрока «новые сверху» и прокрутка к записи по «›»; «Сохранить изменения в «…»?» после правок записанной партии — проверить.