From 66f86ae3e563282472a8be5e195a26810812697c Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 26 Oct 2026 01:21:47 +0300 Subject: [PATCH] Android: games against Maia (small model, no clocks) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «Play with Maia» on the Databases screen and «Play on from here with Maia…» in the move sheet: the strength (1100–1800), colour and name; Maia's 21 MB downloaded there. The game is a mode of the game screen: Maia answers after a person's pause (shared rules), take back, resign or abort, Maia's offer to resign judged by Stockfish when it is there; the end card offers analysis, rematch and saving. The game is written after each move: «back» puts it aside, the Databases screen offers to go on with it. Co-Authored-By: Claude Opus 5.5 --- .../chesspenguin/ChessPenguinApp.kt | 3 + .../vrubelroman/chesspenguin/Navigation.kt | 15 +- .../chesspenguin/data/CheckedDownload.kt | 1 + .../chesspenguin/data/MaiaGames.kt | 79 +++++ .../chesspenguin/data/ReviewSession.kt | 14 +- .../vrubelroman/chesspenguin/data/Settings.kt | 15 + .../chesspenguin/ui/DatabasesScreen.kt | 51 ++- .../vrubelroman/chesspenguin/ui/GameScreen.kt | 310 +++++++++++++++++- .../vrubelroman/chesspenguin/ui/PlayMode.kt | 217 ++++++++++++ .../vrubelroman/chesspenguin/ui/PlaySheet.kt | 210 ++++++++++++ .../vrubelroman/chesspenguin/ui/SaveGame.kt | 5 + .../app/src/main/res/values-de/strings.xml | 52 +++ .../app/src/main/res/values-es/strings.xml | 52 +++ .../app/src/main/res/values-fr/strings.xml | 52 +++ .../app/src/main/res/values-it/strings.xml | 52 +++ .../app/src/main/res/values-kk/strings.xml | 52 +++ .../app/src/main/res/values-pt/strings.xml | 52 +++ .../app/src/main/res/values-ru/strings.xml | 52 +++ .../app/src/main/res/values-uz/strings.xml | 52 +++ .../app/src/main/res/values/strings.xml | 52 +++ crates/mobile-api/src/session.rs | 13 + 21 files changed, 1377 insertions(+), 24 deletions(-) create mode 100644 androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt create mode 100644 androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt create mode 100644 androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt 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 b20f813..7eae00a 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 @@ -10,6 +10,7 @@ import io.github.vrubelroman.chesspenguin.data.AppUpdates 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.Library import io.github.vrubelroman.chesspenguin.data.OnlineDownloads import io.github.vrubelroman.chesspenguin.data.Settings @@ -33,6 +34,8 @@ 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). + val maiaGames by lazy { MaiaGames(this) } /// Games from Lichess and Chess.com being downloaded (android-ui.md §23). val downloads by lazy { OnlineDownloads(library, scope) } /// The app's own updates (android-ui.md §25). 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 e7b208c..3121775 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 @@ -40,6 +40,7 @@ import io.github.vrubelroman.chesspenguin.ui.DatabasesScreen import io.github.vrubelroman.chesspenguin.ui.SettingsScreen import io.github.vrubelroman.chesspenguin.ui.GameScreen import io.github.vrubelroman.chesspenguin.ui.NEW_GAME +import io.github.vrubelroman.chesspenguin.ui.PLAY_GAME import io.github.vrubelroman.chesspenguin.ui.GamesScreen import io.github.vrubelroman.chesspenguin.ui.OnlineScreen import kotlinx.serialization.Serializable @@ -55,6 +56,9 @@ import kotlinx.serialization.Serializable /// A new game from the start position (android-play.md §30.4). @Serializable data object NewGameKey : NavKey +/// The game against Maia in hand (android-play.md §31). +@Serializable data object PlayKey : NavKey + @Serializable data object SettingsKey : NavKey @Serializable data object AboutKey : NavKey @@ -119,16 +123,23 @@ fun MainNavigation() { onSettings = { backStack.add(SettingsKey) }, onOnline = { backStack.add(OnlineKey) }, onNewGame = { backStack.add(NewGameKey) }, + onPlay = { backStack.add(PlayKey) }, ) } entry { - GameScreen(NEW_GAME, 0, "", onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }) + GameScreen(NEW_GAME, 0, "", onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) }) + } + entry { + GameScreen(PLAY_GAME, 0, "", onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { + backStack.removeLastOrNull() + backStack.add(PlayKey) + }) } entry { key -> GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }) } entry { key -> - GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }) + GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) }) } entry { SettingsScreen( 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 b112163..62028be 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 @@ -54,6 +54,7 @@ data class FileSpec( class CheckedDownload(private val context: Context, private val scope: CoroutineScope, private val spec: FileSpec) { private val dir = File(context.filesDir, spec.dir) val file = File(dir, spec.name) + val size: Long get() = spec.size private val part = File(dir, spec.name + ".part") private val prefs = context.getSharedPreferences(spec.prefs, Context.MODE_PRIVATE) private val downloads get() = context.getSystemService(DownloadManager::class.java) 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 new file mode 100644 index 0000000..9b180db --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/MaiaGames.kt @@ -0,0 +1,79 @@ +package io.github.vrubelroman.chesspenguin.data + +import android.content.Context +import kotlinx.coroutines.flow.MutableStateFlow +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) + +/// 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. +class MaiaGames(context: Context) { + private val file = File(context.filesDir, "play/current.pgn") + private val prefs = context.getSharedPreferences("play", Context.MODE_PRIVATE) + private val _current = MutableStateFlow(read()) + /// The game in hand, if any. + val current: StateFlow = _current.asStateFlow() + + private fun read(): PlayMeta? { + if (!file.isFile || !prefs.contains("strength")) return null + return PlayMeta( + strength = prefs.getInt("strength", 1500), + userWhite = prefs.getBoolean("white", true), + name = prefs.getString("name", "") ?: "", + floor = prefs.getInt("floor", 0), + over = prefs.getBoolean("over", false), + ) + } + + /// The PGN of the game in hand. + fun pgn(): String? = runCatching { file.readText() }.getOrNull() + + /// A new game: it replaces the one in hand. + fun begin(pgn: String, meta: PlayMeta) { + write(pgn) + prefs.edit() + .putInt("strength", meta.strength) + .putBoolean("white", meta.userWhite) + .putString("name", meta.name) + .putInt("floor", meta.floor) + .putBoolean("over", meta.over) + .apply() + _current.value = meta + } + + /// The game after a move. + fun save(pgn: String) { + if (_current.value != null) write(pgn) + } + + /// 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() + _current.value = _current.value?.copy(over = true) + } + + /// The game is gone (left after its end, removed by the user). + fun clear() { + file.delete() + prefs.edit().clear().apply() + _current.value = null + } + + /// Written beside and moved in: a cut-off write leaves the last move's game whole. + private fun write(pgn: String) { + file.parentFile?.mkdirs() + val tmp = File(file.path + ".tmp") + tmp.writeText(pgn) + if (!tmp.renameTo(file)) { + file.writeText(pgn) + tmp.delete() + } + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt index e006fa7..aac92d9 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt @@ -39,19 +39,25 @@ class ReviewSession(private val cacheDir: String, private val scope: CoroutineSc /// Shows the analysis of game `index` of database `db` (from the cache or its /// `[%eval]` comments); the analysis of the game before is stopped and kept. - suspend fun open(db: String, database: Database, index: UInt) { - if (game == db to index) return + suspend fun open(db: String, database: Database, index: UInt) = openWith(db to index) { database.review(index, cacheDir) } + + /// The analysis of a game being changed or played (no file of its own), as it is + /// now; `stamp` names this state of it (a new stamp: the game changed). + suspend fun openSession(stamp: String, session: uniffi.mobile_api.GameSession) = openWith("session" to stamp.hashCode().toUInt()) { session.review(cacheDir) } + + private suspend fun openWith(key: Pair, make: () -> GameReview) { + if (game == key) return val gen = ++generation _state.value = null lock.withLock { closeLocked() - val r = withContext(Dispatchers.IO) { runCatching { database.review(index, cacheDir) }.getOrNull() } ?: return + val r = withContext(Dispatchers.IO) { runCatching { make() }.getOrNull() } ?: return if (gen != generation) { withContext(Dispatchers.IO) { r.close() } return } review = r - game = db to index + game = key _state.value = withContext(Dispatchers.IO) { r.state() } } } 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 121cc41..1ddd1b3 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 @@ -29,6 +29,13 @@ 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. + val maiaStrength: Int = 1500, + val maiaColor: Int = 0, + val yourName: String = "", + /// Sounds of moves and of the end of a game (§33). + val sound: Boolean = true, ) /// Half the cores, at most 2: the engine leaves the phone's interface room (§9). @@ -65,6 +72,10 @@ 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), + maiaStrength = store.getInt("maiaStrength", d.maiaStrength), + maiaColor = store.getInt("maiaColor", d.maiaColor).coerceIn(-1, 1), + yourName = store.getString("yourName", d.yourName) ?: d.yourName, + sound = store.getBoolean("sound", d.sound), ) } @@ -85,6 +96,10 @@ class Settings(context: Context) { .putInt("engineHashMb", p.engineHashMb) .putInt("reviewQuality", p.reviewQuality) .putLong("reviewNps", p.reviewNps) + .putInt("maiaStrength", p.maiaStrength) + .putInt("maiaColor", p.maiaColor) + .putString("yourName", p.yourName) + .putBoolean("sound", p.sound) .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 cdfb7d2..3b994b9 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 @@ -30,6 +30,8 @@ import kotlinx.coroutines.withContext import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.EditNote +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.SmartToy import androidx.compose.material.icons.rounded.MoreVert import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.AlertDialog @@ -89,7 +91,7 @@ import kotlinx.coroutines.launch /// The first screen: the databases on the list (android-ui.md §3). @OptIn(ExperimentalMaterial3Api::class) @Composable -fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit, onOnline: () -> Unit, onNewGame: () -> Unit) { +fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit, onOnline: () -> Unit, onNewGame: () -> Unit, onPlay: () -> Unit) { val library = app().library val downloads = app().downloads val views by downloads.views.collectAsState() @@ -171,6 +173,20 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett } } val own = entries.filter { it.source == Source.Own } + val theApp = app() + val adjourned by theApp.maiaGames.current.collectAsState() + val playRemovedText = stringResource(R.string.play_removed) + var playing by remember { mutableStateOf(false) } + val eventText = stringResource(R.string.play_event) + if (playing) { + PlaySheet(null, onPlay = { strength, white, name -> + playing = false + val s = uniffi.mobile_api.GameSession.newGame("") + beginMaiaGame(theApp, s, strength, white, name, 0, eventText, null) + s.close() + onPlay() + }, onDismiss = { playing = false }) + } val files = entries.filter { it.source != Source.Own } val list = rememberLazyListState() // The card comes when GitHub answers, after the list is drawn: a list at its top then @@ -229,8 +245,41 @@ 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. + adjourned?.takeIf { !it.over }?.let { m -> + item(key = "adjourned") { + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp) + .background(MaterialTheme.colorScheme.secondaryContainer, RoundedCornerShape(12.dp)) + .padding(start = 16.dp, end = 4.dp, top = 4.dp, bottom = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + stringResource(R.string.play_adjourned, m.strength.toString(), stringResource(if (m.userWhite) R.string.play_as_white else R.string.play_as_black)), + Modifier.weight(1f), + style = MaterialTheme.typography.bodyMedium, + ) + TextButton(onClick = onPlay) { Text(stringResource(R.string.play_continue)) } + IconButton(onClick = { + val pgn = theApp.maiaGames.pgn() + theApp.maiaGames.clear() + scope.launch { + snackbar.currentSnackbarData?.dismiss() + if (snackbar.showSnackbar(playRemovedText, undoText, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed && pgn != null) { + theApp.maiaGames.begin(pgn, m) + } + } + }) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } + } + } + } item(key = "actions") { Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FilledTonalButton(onClick = { playing = true }, modifier = Modifier.height(48.dp)) { + Icon(Icons.Rounded.SmartToy, null) + Spacer(Modifier.size(8.dp)) + Text(stringResource(R.string.play_with_maia)) + } FilledTonalButton(onClick = onNewGame, modifier = Modifier.height(48.dp)) { Icon(Icons.Rounded.Add, null) Spacer(Modifier.size(8.dp)) 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 f7437a1..e773dbf 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 @@ -40,6 +40,7 @@ import androidx.compose.material.icons.rounded.ChevronLeft import androidx.compose.material.icons.rounded.Close import androidx.compose.material.icons.rounded.Save import androidx.compose.material.icons.rounded.School +import androidx.compose.material.icons.rounded.SmartToy import androidx.compose.material.icons.rounded.VerticalAlignTop import androidx.compose.material.icons.rounded.ChevronRight import androidx.compose.material.icons.rounded.Download @@ -136,7 +137,7 @@ 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) { +fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, onSettings: () -> Unit, onPlayGame: () -> Unit = {}) { val app = app() val context = LocalContext.current val prefs by app.settings.prefs.collectAsState() @@ -150,6 +151,9 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o var game by held.data var edit by held.session val newGame = db == NEW_GAME + // The game against Maia in hand (android-play.md §31). + val playGame = db == PLAY_GAME + val run = held.play.value // Learning the opening of this game: its own screen over the game (§32). held.trainer.value?.let { t -> TrainScreen(t, held.trainPly, held.trainFlipped, onPly = { held.trainPly = it }, onExit = { @@ -164,8 +168,32 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o var preview by remember { mutableStateOf(null) } // The game report (§21): its own engine job; the live engine rests while it runs. val review = remember { ReviewSession(java.io.File(context.cacheDir, "analysis").path, app.scope) } - LaunchedEffect(db, place) { + LaunchedEffect(db, place, held.reloads.intValue) { preview = null + if (playGame) { + if (held.key != PLAY_GAME) { + val meta = app.maiaGames.current.value + val pgn = app.maiaGames.pgn() + if (meta == null || pgn == null) { + failed = true + return@LaunchedEffect + } + held.key = PLAY_GAME + held.savedTo = null + val s = GameSession.fromPgn(pgn) + edit = s + val d = s.data() + game = d + held.play.value?.close() + held.play.value = PlayRun(meta).also { r -> + // A game that ended before the app was closed: its end as it was. + if (meta.over) r.over.value = PlayOver(d.result, if (d.result == "1/2-1/2") R.string.play_draw else if ((d.result == "1-0") == meta.userWhite) R.string.play_won else R.string.play_lost, null) + } + flipped = !meta.userWhite + current = lineEnd(d) + } + return@LaunchedEffect + } if (newGame) { if (held.key != NEW_GAME) { held.key = NEW_GAME @@ -391,12 +419,123 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o } // The move sheet of a long press on a move (§29.6): which move. var moveSheet by remember { mutableStateOf(null) } + // «Play on from here» asked for at this move. + var playFrom by remember { mutableStateOf(null) } val deletedText = stringResource(R.string.moves_deleted) val undoText = stringResource(R.string.undo_action) fun undo() { edit?.undo()?.let { apply(it) } } + // ----- a game against Maia (§31) ----- + val runOver = run?.over?.value + val runOffer = run?.offer?.value == true + val runThinking = run?.thinking?.value == true + val runFailure = run?.failure?.value + val gameOn = run != null && runOver == null + fun persist() { + if (run != null) edit?.let { app.maiaGames.save(it.pgn()) } + } + fun finishGame(over: PlayOver) { + val r = run ?: return + val e = edit ?: return + r.generation++ + r.thinking.value = false + r.offer.value = false + 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()) + } + // After a move of either side: kept, and the end of the game if it came. + fun afterMove(e: Edited) { + val r = run ?: return + 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. + LaunchedEffect(run, g, runOver, runOffer, runFailure) { + val r = run ?: return@LaunchedEffect + val gg = g ?: return@LaunchedEffect + val e = edit ?: return@LaunchedEffect + if (runOver != null || runOffer || runFailure != null) return@LaunchedEffect + val end = lineEnd(gg) + if (whiteToMove(gg.nodes[end].fen) == r.meta.userWhite) return@LaunchedEffect + 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. + 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) + if (wait > 0) delay(wait) + if (gen != r.generation) return@LaunchedEffect + r.judge?.hopeless()?.let { if (it) r.hopeless++ else r.hopeless = 0u } + if (!r.playOn && r.hopeless >= uniffi.mobile_api.hopelessTurns()) { + r.offer.value = true + return@LaunchedEffect + } + runCatching { e.play(end.toUInt(), uci) }.getOrNull()?.let { ed -> + apply(ed) + afterMove(ed) + } + } finally { + if (gen == r.generation) r.thinking.value = false + } + } + var resigning by remember { mutableStateOf(false) } + // The result card closed with ×: until the next game. + var resultClosed by remember(run) { mutableStateOf(false) } + 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. + fun rematch() { + val r = run ?: return + val e = edit ?: return + val gg = g ?: return + val m = r.meta + val base = if (m.floor > 0) { + var n = 0 + repeat(m.floor) { n = gg.nodes[n].children.firstOrNull()?.toInt() ?: n } + runCatching { e.playFrom(n.toUInt()) }.getOrNull() ?: return + } else { + GameSession.newGame("") + } + beginMaiaGame(app, base, m.strength, if (m.floor > 0) m.userWhite else !m.userWhite, m.name, m.floor, eventText, noteText) + base.close() + held.key = null + held.reloads.intValue++ + } + fun takeBack() { + val r = run ?: return + val gg = g ?: return + val e = edit ?: return + val end = lineEnd(gg) + // While Maia thinks the last move is the user's; else hers, and the user's before. + val from = if (r.thinking.value) end else gg.nodes[end].parent?.toInt() ?: return + if (depth(gg, from) <= r.meta.floor) return + r.generation++ + r.thinking.value = false + r.judge?.forget() + r.hopeless = 0u + runCatching { e.deleteFrom(from.toUInt()) }.getOrNull()?.let { + apply(it) + persist() + } + } + // Saving (android-play.md §30.4): an own database's game in its place; a new game or // a copy of someone else's into an own database chosen once, then in its place there. val ownGame = dbEntry?.source == Source.Own && !newGame @@ -438,7 +577,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o ownGame -> games?.getOrNull(place)?.let { saveInto(db, it) } to != null -> saveInto(to.first, to.second) // A new game's names and result first, as the desktop asks when adding. - newGame -> { + newGame && !playGame -> { firstSave = true editingData = true } @@ -447,9 +586,22 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o } // Leaving with changes asks only where they are the user's to keep (an own game, a // new one); moves in someone else's game are for trying out (owner's decision). - val asksOnLeave = modified && (ownGame || newGame) + // A game against Maia: put aside while it goes on (no question); after its end like + // a new game, and gone from hand once left. + val asksOnLeave = modified && (ownGame || newGame || (playGame && runOver != null)) + val exit: () -> Unit = { + if (playGame && held.play.value?.over?.value != null) app.maiaGames.clear() + onBack() + } + // What leaving's question leads to (back, or a rematch). + var leaveTo by remember { mutableStateOf<(() -> Unit)?>(null) } fun leave() { - if (asksOnLeave) leaving = true else onBack() + if (asksOnLeave) { + leaveTo = exit + leaving = true + } else { + exit() + } } fun go(to: Int) { preview = null @@ -506,7 +658,27 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE val controls: @Composable (Modifier) -> Unit = { modifier -> - Column(modifier) { + if (gameOn && run != null && g != null) { + val end = lineEnd(g) + val endDepth = depth(g, end) + val floor = run.meta.floor + PlayControls( + // While Maia thinks the last move is the user's; else hers and the user's before. + canTakeBack = if (runThinking) endDepth > floor else endDepth - 1 > floor, + started = endDepth - floor >= 2, + canBack = canBack, + canForward = canForward, + onTakeBack = ::takeBack, + onResign = { resigning = true }, + onAbort = { + app.maiaGames.clear() + onBack() + }, + onFlip = { flipped = !flipped }, + onBack = ::back, + onForward = ::forward, + ) + } else Column(modifier) { val p = preview if (p == null && node != null && nodes != null && node.children.size > 1) { Forks(node.children.map { nodes[it.toInt()] }, san, onMove = ::go) @@ -584,10 +756,16 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o animated = prefs.animation, // A touch during a preview of an engine line closes it; no move is made (§29.5). modifier = if (p != null) boardModifier.pointerInput(Unit) { detectTapGestures { preview = null } } else boardModifier, - input = edit?.takeIf { p == null && g != null }?.let { e -> + input = edit?.takeIf { + // In a game: only the user's side, in their turn, at the game's last move. + p == null && g != null && (!gameOn || (current == lineEnd(g) && !runThinking && !runOffer && whiteToMove(g.nodes[current].fen) == run!!.meta.userWhite)) + }?.let { e -> val legal = remember(g, current) { e.legalMoves(current.toUInt()) } BoardInput(legal, onMove = { uci -> - runCatching { e.play(current.toUInt(), uci) }.getOrNull()?.let { apply(it) } + runCatching { e.play(current.toUInt(), uci) }.getOrNull()?.let { + apply(it) + if (gameOn) afterMove(it) + } }) }, ) @@ -643,6 +821,45 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o ) } if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null }, best = p.best) + 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)) }, + onPlayOn = { + run.playOn = true + run.offer.value = false + }, + ) + runFailure != null -> Text( + stringResource(R.string.play_maia_failed, runFailure), + Modifier.padding(16.dp), + color = MaterialTheme.colorScheme.error, + ) + runOver != null && !resultClosed -> ResultCard( + runOver, + saved = held.savedTo != null && !modified, + onAnalyse = { + val e = edit + if (e != null) scope.launch { + review.openSession("${held.key}/${System.nanoTime()}", e) + reviewHidden = false + reviewStart = true + } + }, + onRematch = { + val go = { rematch() } + if (modified) { + leaveTo = go + leaving = true + } else { + go() + } + }, + onSave = { save() }, + onClose = { resultClosed = true }, + ) + } + } Box(Modifier.weight(1f).fillMaxWidth()) { when { g != null -> Notation( @@ -677,14 +894,18 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o // 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. - val event = if (newGame && held.savedTo == null) { + val event = if (playGame && run != null) { + stringResource(R.string.play_with_maia) + " " + run.meta.strength + } else if (newGame && held.savedTo == null) { stringResource(R.string.new_game) } else { joinKnown(tag("Event"), year(tag("Date"))).ifEmpty { joinKnown(tag("Site")) } .ifEmpty { dbEntry?.let { displayName(it) } ?: "" } } val round = tag("Round").trim().takeIf { it.isNotEmpty() && it != "?" && it != "-" } - val placeLine = joinKnown( + 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)) + } else joinKnown( if (total > 0) stringResource(R.string.game_of, place + 1, total) else "", round?.let { stringResource(R.string.tag_round).lowercase() + " " + it } ?: "", ) @@ -714,13 +935,13 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o }, actions = { // Changes not saved: "Save" in place of ‹ › (they would need a decision). - if (modified) { + if (modified && !gameOn) { val where = when { ownGame -> dbEntry?.let { stringResource(R.string.save_in, displayName(it)) } else -> held.savedTo?.first?.let { app.library.entry(it) }?.let { stringResource(R.string.save_in, displayName(it)) } } ?: stringResource(R.string.save_to_mine) IconButton(onClick = { save() }) { Icon(Icons.Rounded.Save, where) } - } else if (!newGame) { + } else if (!newGame && !playGame) { IconButton(onClick = { place -= 1 }, enabled = place > 0) { Icon(Icons.Rounded.ChevronLeft, stringResource(R.string.previous_game)) } @@ -741,10 +962,18 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o DropdownMenuItem( text = { Text(stringResource(if (rs?.hasData == true) R.string.review_report_menu else R.string.review_menu)) }, // During the first analysis the panel already shows its progress (§21.1). - enabled = hasMoves && rs != null && (rs.hasData || !rs.running), + enabled = hasMoves && !gameOn && ((newGame || playGame) || (rs != null && (rs.hasData || !rs.running))), onClick = { menu = false reviewHidden = false + val e = edit + if ((newGame || playGame) && e != null && rs == null) { + scope.launch { + review.openSession("${held.key}/${System.nanoTime()}", e) + reviewStart = true + } + return@DropdownMenuItem + } when { rs?.hasData == true -> reviewReport = true rs?.running == true -> {} @@ -800,11 +1029,14 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o // 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). + val thinkingText = stringResource(R.string.play_thinking) + val maiaThinks = { white: Boolean -> if (gameOn && runThinking && run?.meta?.userWhite != white) thinkingText else null } val whiteBar: @Composable () -> Unit = { - PlayerBar(whiteName ?: whiteLabel, elo(tag("WhiteElo")), true, sideResult(result, true), known = whiteName != null, abbreviate = !study) + PlayerBar(whiteName ?: whiteLabel, elo(tag("WhiteElo")), true, maiaThinks(true) ?: sideResult(result, true), known = whiteName != null, abbreviate = !study) } val blackBar: @Composable () -> Unit = { - PlayerBar(blackName ?: blackLabel, elo(tag("BlackElo")), false, sideResult(result, false), known = blackName != null) + PlayerBar(blackName ?: blackLabel, elo(tag("BlackElo")), false, maiaThinks(false) ?: sideResult(result, false), known = blackName != null) } val topBar = if (flipped) whiteBar else blackBar val bottomBar = if (flipped) blackBar else whiteBar @@ -914,20 +1146,55 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o confirmButton = { TextButton(onClick = { leaving = false - save(then = onBack) + save(then = leaveTo ?: exit) }) { Text(stringResource(if (ownGame || held.savedTo != null) R.string.save else R.string.save_to_db_ellipsis)) } }, dismissButton = { Row { TextButton(onClick = { leaving = false - onBack() + (leaveTo ?: exit)() }) { Text(stringResource(R.string.dont_save)) } TextButton(onClick = { leaving = false }) { Text(stringResource(R.string.cancel)) } } }, ) } + // «Play on from here» (§31.6): the moves up to the move, then a game against Maia. + val fromMove = playFrom + if (fromMove != null && g != null && edit != null) { + val n = g.nodes.getOrNull(fromMove) + if (n == null) { + playFrom = null + } else { + val moveLabel = (if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san).text + val origin = listOfNotNull(whiteName, blackName).joinToString(" — ").takeIf { it.isNotEmpty() } + PlaySheet( + PlayFrom(n.fen, listOfNotNull(stringResource(R.string.play_from_label, moveLabel), origin).joinToString("\n"), whiteToMove(n.fen)), + 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())) + s.close() + onPlayGame() + }, + onDismiss = { playFrom = null }, + ) + } + } + if (resigning) { + AlertDialog( + onDismissRequest = { resigning = false }, + title = { Text(stringResource(R.string.play_resign_q)) }, + confirmButton = { + TextButton(onClick = { + resigning = false + run?.let { finishGame(PlayOver(if (it.meta.userWhite) "0-1" else "1-0", R.string.play_you_resigned, null)) } + }) { Text(stringResource(R.string.play_resign).removePrefix("⚑ "), color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { TextButton(onClick = { resigning = false }) { Text(stringResource(R.string.cancel)) } }, + ) + } val sheetMove = moveSheet if (sheetMove != null && g != null && edit != null) { val n = g.nodes.getOrNull(sheetMove) @@ -939,6 +1206,12 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o inVariation = g.nodes[n.parent!!.toInt()].children.firstOrNull()?.toInt() != sheetMove, runs = remember(sheetMove) { edit?.trainingRuns(sheetMove.toUInt())?.toInt() }, canTrain = !n.nullMove, + // Not at mate or stalemate, nor after a null move; not inside a game being played. + canPlay = !n.nullMove && n.end.isEmpty() && !gameOn, + onPlay = { + moveSheet = null + playFrom = sheetMove + }, onTrain = { moveSheet = null edit?.trainer(sheetMove.toUInt())?.let { t -> @@ -1231,6 +1504,8 @@ private fun MoveSheet( onMakeMain: () -> Unit, onDelete: () -> Unit, onTrain: () -> Unit, + canPlay: Boolean, + onPlay: () -> Unit, onDismiss: () -> Unit, ) { androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss) { @@ -1239,6 +1514,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.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 new file mode 100644 index 0000000..445c1b1 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayMode.kt @@ -0,0 +1,217 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.Undo +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Flag +import androidx.compose.material.icons.rounded.PlayArrow +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.Button +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale +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.PlayMeta +import uniffi.mobile_api.GameData +import uniffi.mobile_api.GameEnding +import uniffi.mobile_api.MaiaPlayer +import uniffi.mobile_api.ResignJudge + +/// The key of the game against Maia 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. +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. +class PlayRun(val meta: PlayMeta) { + var player: MaiaPlayer? = null + var judge: ResignJudge? = null + val thinking = mutableStateOf(false) + /// Maia offers to resign (her position hopeless two turns in a row). + val offer = mutableStateOf(false) + val over = mutableStateOf(null) + /// Maia failed to start: 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. + var generation = 0 + + fun close() { + player?.close() + judge?.close() + player = null + judge = null + } +} + +/// The last node of the main line. +fun lineEnd(g: GameData): Int { + var n = 0 + while (true) n = g.nodes[n].children.firstOrNull()?.toInt() ?: return n +} + +/// Half-moves from the start to node `id`. +fun depth(g: GameData, id: Int): Int { + var d = 0 + var n = g.nodes.getOrNull(id) ?: return 0 + while (true) { + n = g.nodes.getOrNull(n.parent?.toInt() ?: return d) ?: return d + d++ + } +} + +fun whiteToMove(fen: String) = fen.substringAfter(' ').startsWith("w") + +/// The end of a game by the rules, from the user's side. +fun overBy(ending: GameEnding, userWhite: Boolean): PlayOver = when (ending) { + is GameEnding.Checkmate -> PlayOver( + if (ending.whiteWon) "1-0" else "0-1", + if (ending.whiteWon == userWhite) R.string.play_won else R.string.play_lost, + R.string.end_mate, + ) + GameEnding.Stalemate -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_stalemate) + GameEnding.InsufficientMaterial -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_material) + GameEnding.Threefold -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_threefold) + GameEnding.FiftyMoves -> PlayOver("1/2-1/2", R.string.play_draw, R.string.end_fifty) +} + +/// The bottom bar during a game (§31.3): take back, resign (abort before the first +/// moves), flip, a move back and forward. +@Composable +fun PlayControls( + canTakeBack: Boolean, + started: Boolean, + canBack: Boolean, + canForward: Boolean, + onTakeBack: () -> Unit, + onResign: () -> Unit, + onAbort: () -> Unit, + onFlip: () -> Unit, + onBack: () -> Unit, + onForward: () -> Unit, +) { + Column { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), verticalAlignment = Alignment.CenterVertically) { + LabeledButton(Icons.AutoMirrored.Rounded.Undo, stringResource(R.string.play_take_back).removePrefix("↶ "), canTakeBack, Modifier.weight(1f), onTakeBack) + if (started) { + LabeledButton(Icons.Rounded.Flag, stringResource(R.string.play_resign).removePrefix("⚑ "), true, Modifier.weight(1f), onResign) + } else { + LabeledButton(Icons.Rounded.Close, stringResource(R.string.play_abort), true, Modifier.weight(1f), onAbort) + } + IconButton(onClick = onFlip, modifier = Modifier.weight(0.8f)) { Icon(Icons.Rounded.SwapVert, stringResource(R.string.flip)) } + IconButton(onClick = onBack, enabled = canBack, modifier = Modifier.weight(1f)) { + // The forward arrow turned round, as the game screen's. + Icon(Icons.Rounded.PlayArrow, stringResource(R.string.move_back), Modifier.scale(-1f, 1f)) + } + IconButton(onClick = onForward, enabled = canForward, modifier = Modifier.weight(1f)) { Icon(Icons.Rounded.PlayArrow, stringResource(R.string.move_forward)) } + } + } + } +} + +@Composable +private fun LabeledButton(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, enabled: Boolean, modifier: Modifier, onClick: () -> Unit) { + androidx.compose.material3.TextButton(onClick = onClick, enabled = enabled, modifier = modifier.height(64.dp)) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon(icon, null) + Text(label, style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +/// Maia offers to resign (§31.3): accept the win, or play on. +@Composable +fun OfferCard(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) + 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_to_end)) } + } + } +} + +/// 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) { + Card { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + (if (over.result == "1/2-1/2") "½-½" else over.result) + " " + stringResource(over.heading) + (over.detail?.let { " · " + stringResource(it) } ?: ""), + Modifier.weight(1f), + style = MaterialTheme.typography.titleMedium, + ) + IconButton(onClick = onClose) { Icon(Icons.Rounded.Close, stringResource(R.string.close)) } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = onAnalyse, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_analyse), maxLines = 1) } + OutlinedButton(onClick = onRematch, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.play_rematch).removePrefix("↻ "), maxLines = 1) } + OutlinedButton(onClick = onSave, enabled = !saved, modifier = Modifier.weight(1f)) { + Text(stringResource(if (saved) R.string.play_saved else R.string.play_save), maxLines = 1) + } + } + } +} + +@Composable +private fun Card(content: @Composable () -> Unit) { + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp) + .background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(12.dp)) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { 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( + app: io.github.vrubelroman.chesspenguin.ChessPenguinApp, + session: uniffi.mobile_api.GameSession, + strength: Int, + userWhite: Boolean, + name: String, + floor: Int, + 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) + session.setData(tags, "*") + if (floor > 0 && note != null) { + val data = session.data() + runCatching { session.addComment(lineEnd(data).toUInt(), note) } + } + session.markSaved() + app.maiaGames.begin(session.pgn(), PlayMeta(strength, userWhite, name, floor)) +} 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 new file mode 100644 index 0000000..56329ff --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlaySheet.kt @@ -0,0 +1,210 @@ +package io.github.vrubelroman.chesspenguin.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +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.ExperimentalMaterial3Api +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.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.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +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.NetProblem +import io.github.vrubelroman.chesspenguin.data.NetState +import io.github.vrubelroman.chesspenguin.theme.Tabular +import uniffi.mobile_api.maiaRange + +/// 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. +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. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PlaySheet(from: PlayFrom?, onPlay: (Int, Boolean, String) -> 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()) } + // 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 name by remember { mutableStateOf(prefs.yourName) } + // «Download and play»: the game starts once the file is checked. + var playAfter by remember { mutableStateOf(false) } + val level = (strength / 50f).toInt() * 50 + fun play() { + val white = when (color) { + 1 -> true + -1 -> false + else -> kotlin.random.Random.nextBoolean() + } + app.settings.update { p -> + p.copy(maiaStrength = level, yourName = name.trim(), maiaColor = if (from != null) p.maiaColor else color) + } + onPlay(level, white, name.trim()) + } + LaunchedEffect(state) { + 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)) + } + } + } + Spacer(Modifier.height(12.dp)) + OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.play_your_name)) }, singleLine = true) + 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, + 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, + ) + } + } + Spacer(Modifier.height(8.dp)) + val loading = state is NetState.Loading + Button( + onClick = { + if (state == NetState.Ready) { + play() + } else { + playAfter = true + files.download() + } + }, + 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 + }, + ), + ) + } + } + } +} + +/// A small board of a position (no touches, no coordinates). +@Composable +fun MiniBoard(fen: String, flipped: Boolean, size: androidx.compose.ui.unit.Dp) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val context = androidx.compose.ui.platform.LocalContext.current + val pieces = remember { Pieces(context) } + Board( + fen = fen, + flipped = flipped, + lastFrom = null, + lastTo = null, + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = "", + animated = false, + modifier = Modifier.width(size), + ) +} + +private fun megabytes(bytes: Long) = ((bytes + 999_999) / 1_000_000).toInt() 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 a3a9b23..55d2e71 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 @@ -52,11 +52,16 @@ class GameEdit : ViewModel() { var savedTo: Pair? = 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). + val play = mutableStateOf(null) + /// Bumped to read the game in hand again (a rematch). + val reloads = androidx.compose.runtime.mutableIntStateOf(0) var trainPly = 0 var trainFlipped = false override fun onCleared() { trainer.value?.close() + play.value?.close() session.value?.close() } } diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index ae428a8..28ce771 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -461,4 +461,56 @@ %1$d Durchgänge Maia für ChessPenguin + Sie haben gewonnen + Sie haben verloren + Sie haben aufgegeben + Remis + Schachmatt + Patt + die Stellung ist dreimal aufgetreten + 50 Züge ohne Schlagen oder Bauernzug + keine Seite kann mattsetzen + Maia hat aufgegeben + Aufgeben? + ⚑ Aufgeben + ↶ Zurücknehmen + Gegen den Computer spielen + Ihre Farbe + Weiß + Schwarz + Zufällig + Gegner — Maia %1$s + Ihre gemessene Spielstärke, auf der Lichess-Blitz-Skala. + Maia wird einmalig heruntergeladen (%1$s MB, von huggingface.co, die Datei der Autoren selbst). + Herunterladen und spielen + Spielen + denkt nach… + Partie gegen den Computer + Analysieren + ↻ Revanche + Von hier aus spielen… + Wird geprüft… + Maia ist nicht gestartet: %1$s + Sieg annehmen + Zu Ende spielen + Maia gibt auf + Ab hier eine Partie gegen Maia %1$s. + Abbrechen + Gegen Maia spielen + Ihr Name (für die Partie) + Maia ist heruntergeladen + Erneut versuchen + Ihre Stellung ist verloren. Sieg annehmen oder weiterspielen? + Fortsetzen + Partie gegen Maia %1$s · Sie spielen %2$s + Weiß + Schwarz + Partie entfernt + ohne Uhr + Sie + ✓ Gespeichert + Speichern… + Sie spielen %1$s · %2$s + Von hier gegen Maia weiterspielen… + Nach %1$s diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 27d45f1..ba1bf18 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -469,4 +469,56 @@ %1$d repasos Maia para ChessPenguin + Has ganado + Has perdido + Has abandonado + Tablas + jaque mate + rey ahogado + la posición se repitió tres veces + 50 jugadas sin capturas ni movimientos de peón + ningún bando puede dar mate + Maia se rindió + ¿Abandonar? + ⚑ Abandonar + ↶ Deshacer jugada + Jugar contra el ordenador + Tu color + Blancas + Negras + Al azar + Rival — Maia %1$s + Su fuerza medida, en la escala de blitz de Lichess. + Maia se descarga una sola vez (%1$s MB, desde huggingface.co, el archivo de los propios autores). + Descargar y jugar + Jugar + pensando… + Partida contra el ordenador + Analizar + ↻ Revancha + Jugar desde aquí… + Comprobando… + Maia no se inició: %1$s + Aceptar la victoria + Jugar hasta el final + Maia se rinde + A partir de aquí, una partida contra Maia %1$s. + Abortar + Jugar con Maia + Tu nombre (para la partida) + Maia está descargada + Reintentar + Su posición está perdida. ¿Aceptar la victoria o seguir? + Continuar + Partida contra Maia %1$s · juegas con %2$s + blancas + negras + Partida eliminada + sin reloj + Tú + ✓ Guardada + Guardar… + juegas con %1$s · %2$s + Seguir desde aquí contra Maia… + Tras %1$s diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 2d50bcd..bfaa795 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -469,4 +469,56 @@ %1$d passages Maia pour ChessPenguin + Vous avez gagné + Vous avez perdu + Vous avez abandonné + Nulle + échec et mat + pat + la position s’est répétée trois fois + 50 coups sans prise ni coup de pion + aucun camp ne peut mater + Maia a abandonné + Abandonner ? + ⚑ Abandonner + ↶ Reprendre + Jouer contre l’ordinateur + Votre couleur + Blancs + Noirs + Au hasard + Adversaire — Maia %1$s + Sa force mesurée, sur l’échelle du blitz Lichess. + 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 + réfléchit… + Partie contre l’ordinateur + Analyser + ↻ Revanche + Jouer à partir d’ici… + Vérification… + Maia n’a pas démarré : %1$s + Accepter la victoire + Jouer jusqu’au bout + Maia abandonne + À partir d’ici, une partie contre Maia %1$s. + Abandonner + Jouer contre Maia + Votre nom (pour la partie) + Maia est téléchargée + Réessayer + Sa position est perdue. Accepter la victoire ou continuer ? + Continuer + Partie contre Maia %1$s · vous jouez %2$s + les Blancs + les Noirs + Partie supprimée + sans pendule + Vous + ✓ Enregistrée + Enregistrer… + vous jouez %1$s · %2$s + Continuer d’ici contre Maia… + Après %1$s diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 112e9bd..0f3cfb0 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -469,4 +469,56 @@ %1$d ripassi Maia per ChessPenguin + Hai vinto + Hai perso + Hai abbandonato + Patta + scacco matto + stallo + la posizione si è ripetuta tre volte + 50 mosse senza catture né mosse di pedone + nessuno dei due può dare matto + Maia ha abbandonato + Abbandonare? + ⚑ Abbandona + ↶ Ritira mossa + Gioca contro il computer + Il tuo colore + Bianco + Nero + Casuale + Avversario — Maia %1$s + La sua forza misurata, sulla scala del blitz di Lichess. + Maia si scarica una sola volta (%1$s MB, da huggingface.co, il file degli autori stessi). + Scarica e gioca + Gioca + sta pensando… + Partita contro il computer + Analizza + ↻ Rivincita + Gioca da qui… + Controllo… + Maia non si è avviata: %1$s + Accetta la vittoria + Gioca fino alla fine + Maia abbandona + Da qui, una partita contro Maia %1$s. + Annulla + Gioca con Maia + Il tuo nome (per la partita) + Maia è scaricata + Riprova + La sua posizione è persa. Accettare la vittoria o continuare? + Continua + Partita contro Maia %1$s · giochi con %2$s + il Bianco + il Nero + Partita rimossa + senza orologio + Tu + ✓ Salvata + Salva… + giochi con %1$s · %2$s + Continua da qui contro Maia… + Dopo %1$s diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 0b40d63..db7e88d 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -462,4 +462,56 @@ %1$d рет ChessPenguin үшін Maia + Сіз жеңдіңіз + Сіз жеңілдіңіз + Сіз берілдіңіз + Тең ойын + мат + пат + позиция үш рет қайталанды + 50 жүріс бойы алу да, пешка жүрісі де жоқ + ешбір жақ мат қоя алмайды + Maia берілді + Берілесіз бе? + ⚑ Берілу + ↶ Жүрісті қайтару + Компьютермен ойнау + Түсіңіз + Ақтар + Қаралар + Кездейсоқ + Қарсылас — Maia %1$s + Оның өлшенген күші, Lichess блиц шкаласы бойынша. + Maia бір рет жүктеледі (%1$s МБ, huggingface.co сайтынан — авторлардың өз файлы). + Жүктеп алып ойнау + Ойнау + ойлануда… + Компьютермен партия + Талдау + ↻ Реванш + Осы жерден ойнау… + Тексерілуде… + Maia іске қосылмады: %1$s + Жеңісті қабылдау + Соңына дейін ойнау + Maia беріледі + Бұдан әрі — Maia %1$s-мен ойын. + Тоқтату + Maia-мен ойнау + Атыңыз (ойын жазбасы үшін) + Maia жүктелді + Қайталау + Оның позициясы ұтылды. Жеңісті қабылдайсыз ба, әлде жалғастырасыз ба? + Жалғастыру + Maia %1$s-мен ойын · сіз %2$s + ақпен + қарамен + Ойын жойылды + сағатсыз + Сіз + ✓ Сақталды + Сақтау… + сіз %1$s · %2$s + Осы жерден Maia-мен жалғастыру… + %1$s кейін diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 7fc38f9..c1c49aa 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -470,4 +470,56 @@ %1$d passagens Maia para o ChessPenguin + Você venceu + Você perdeu + Você abandonou + Empate + xeque-mate + afogamento + a posição se repetiu três vezes + 50 lances sem captura nem lance de peão + nenhum lado consegue dar mate + Maia desistiu + Abandonar? + ⚑ Abandonar + ↶ Voltar lance + Jogar contra o computador + Sua cor + Brancas + Pretas + Aleatório + Adversário — Maia %1$s + A força medida dela, na escala de blitz do Lichess. + A Maia é baixada uma única vez (%1$s MB, de huggingface.co, o arquivo dos próprios autores). + Baixar e jogar + Jogar + pensando… + Partida contra o computador + Analisar + ↻ Revanche + Jogar a partir daqui… + Verificando… + A Maia não iniciou: %1$s + Aceitar a vitória + Jogar até o fim + Maia desiste + A partir daqui, uma partida contra Maia %1$s. + Abortar + Jogar com a Maia + Seu nome (para a partida) + A Maia foi baixada + Tentar de novo + A posição dela está perdida. Aceitar a vitória ou continuar? + Continuar + Partida contra a Maia %1$s · você joga de %2$s + brancas + pretas + Partida removida + sem relógio + Você + ✓ Salva + Salvar… + você joga de %1$s · %2$s + Continuar daqui contra a Maia… + Depois de %1$s diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 9533ec1..85517f1 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -477,4 +477,56 @@ прохождений: %1$d Maia для ChessPenguin + Вы выиграли + Вы проиграли + Вы сдались + Ничья + мат + пат + позиция повторилась трижды + 50 ходов без взятий и ходов пешек + ни у кого нет материала для мата + Maia сдалась + Сдаться? + ⚑ Сдаться + ↶ Ход назад + Игра с компьютером + Цвет + Белые + Чёрные + Случайно + Соперник — Maia %1$s + Её измеренная сила, по шкале блица Lichess. + Maia скачивается один раз (%1$s МБ, с huggingface.co — файл самих авторов). + Скачать и играть + Играть + думает… + Партия с компьютером + Анализировать + ↻ Реванш + Играть отсюда… + Проверяю… + Maia не запустилась: %1$s + Принять победу + Играть до конца + Maia сдаётся + Дальше — игра с Maia %1$s. + Прервать + Играть с Maia + Ваше имя (для записи партии) + Maia скачана + Повторить + Её позиция проиграна. Принять победу или доиграть? + Продолжить + Партия с Maia %1$s · вы %2$s + белыми + чёрными + Партия удалена + без часов + Вы + ✓ Сохранено + Сохранить… + вы %1$s · %2$s + Играть отсюда с Maia… + После %1$s diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index 17c5683..e1825da 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -460,4 +460,56 @@ %1$d marta ChessPenguin uchun Maia + Siz yutdingiz + Siz yutqazdingiz + Siz taslim bo‘ldingiz + Durang + mat + pat + pozitsiya uch marta takrorlandi + 50 yurish davomida olish ham, piyoda yurishi ham yo‘q + hech bir tomon mat qila olmaydi + Maia taslim bo‘ldi + Taslim bo‘lasizmi? + ⚑ Taslim bo‘lish + ↶ Yurishni qaytarish + Kompyuter bilan o‘ynash + Rangingiz + Oqlar + Qoralar + Tasodifiy + Raqib — Maia %1$s + Uning o‘lchangan kuchi, Lichess blits shkalasi bo‘yicha. + Maia bir marta yuklab olinadi (%1$s MB, huggingface.co dan — mualliflarning o‘z fayli). + Yuklab olish va o‘ynash + O‘ynash + o‘ylamoqda… + Kompyuter bilan partiya + Tahlil qilish + ↻ Revansh + Shu yerdan o‘ynash… + Tekshirilmoqda… + Maia ishga tushmadi: %1$s + G‘alabani qabul qilish + Oxirigacha o‘ynash + Maia taslim bo‘lmoqda + Bundan keyin — Maia %1$s bilan o‘yin. + To‘xtatish + Maia bilan o‘ynash + Ismingiz (o‘yin yozuvi uchun) + Maia yuklab olindi + Qayta urinish + Uning pozitsiyasi yutqazilgan. G‘alabani qabul qilasizmi yoki davom etasizmi? + Davom ettirish + Maia %1$s bilan o‘yin · siz %2$s + oqlar bilan + qoralar bilan + O‘yin o‘chirildi + soatsiz + Siz + ✓ Saqlandi + Saqlash… + siz %1$s · %2$s + Shu yerdan Maia bilan davom ettirish… + %1$s dan keyin diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index e6a43ca..8e004c6 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -465,4 +465,56 @@ %1$d runs Maia for ChessPenguin + You won + You lost + You resigned + Draw + checkmate + stalemate + the position occurred three times + 50 moves without a capture or a pawn move + neither side can checkmate + Maia resigned + Resign? + ⚑ Resign + ↶ Take back + Play against the computer + Your colour + White + Black + Random + Opponent — Maia %1$s + Her measured strength, on the Lichess blitz scale. + Maia is downloaded once (%1$s MB, from huggingface.co, the authors\' own file). + Download and play + Play + thinking… + Game vs computer + Analyse + ↻ Rematch + Play on from here… + Checking… + Maia did not start: %1$s + Accept the win + Play to the end + Maia resigns + From here on, a game against Maia %1$s. + Abort + Play with Maia + Your name (for the game’s record) + Maia is downloaded + Try again + Her position is lost. Accept the win or play on? + Continue + Game against Maia %1$s · you play %2$s + White + Black + Game removed + no clock + You + ✓ Saved + Save… + you play %1$s · %2$s + Play on from here with Maia… + After %1$s diff --git a/crates/mobile-api/src/session.rs b/crates/mobile-api/src/session.rs index a7c768d..8555821 100644 --- a/crates/mobile-api/src/session.rs +++ b/crates/mobile-api/src/session.rs @@ -197,6 +197,19 @@ impl GameSession { }) } + /// Adds `text` to the comments after the move at place `at` (its symbols kept). + pub fn add_comment(&self, at: u32, text: String) -> Result { + self.with(|g| { + let id = node(g, at)?; + let n = g.node(id).ok_or(ApiError::NoNode { place: at })?; + let nags = n.nags().to_vec(); + let mut comments = n.comments_after().to_vec(); + comments.push(text); + g.annotate(id, nags, comments)?; + Ok(edited(g, id)) + }) + } + /// Changed since it was opened or last saved. pub fn is_modified(&self) -> bool { self.with(|g| g.is_modified())