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 b427129..20a4820 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 @@ -35,6 +35,12 @@ class ChessPenguinApp : Application() { /// The app's own updates (android-ui.md §25). val updates by lazy { AppUpdates(this, scope, engineFiles) } + override fun onCreate() { + super.onCreate() + // The opening trainer's runs (android-play.md §32.3). + uniffi.mobile_api.trainerSetFile(java.io.File(filesDir, "training.json").path) + } + /// The games shown on the list of each database (after a search), for paging /// games from the game screen: database id → game numbers. val shown = HashMap>() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt index 4e61adc..dee2309 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt @@ -188,6 +188,8 @@ fun Board( check: Boolean = false, animated: Boolean = true, input: BoardInput? = null, + /// Two squares lit red: a wrong move of the trainer, shown for a moment (§32.2). + alert: Pair? = null, ) { val colors = LocalChessColors.current val context = LocalContext.current @@ -303,6 +305,9 @@ fun Board( if (image == null) drawRect(if (light) theme.light else theme.dark, cell(i), Size(sq, sq)) if (i == from || i == to) drawRect(colors.lastMove, cell(i), Size(sq, sq)) } + alert?.let { (a, b) -> + for (sqName in listOf(a, b)) squareIndex(sqName)?.let { drawRect(Color(220, 40, 40, 115), cell(it), Size(sq, sq)) } + } val chosen = selected if (chosen != null) drawRect(colors.lastMove.copy(alpha = 0.5f), cell(chosen), Size(sq, sq)) for (m in marks) { 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 b8d159d..f7437a1 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 @@ -39,6 +39,7 @@ import androidx.compose.material.icons.outlined.Memory 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.VerticalAlignTop import androidx.compose.material.icons.rounded.ChevronRight import androidx.compose.material.icons.rounded.Download @@ -90,6 +91,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription @@ -148,6 +150,14 @@ 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 + // 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 = { + held.trainer.value = null + t.close() + }) + return + } var failed by remember { mutableStateOf(false) } var current by rememberSaveable(place) { mutableIntStateOf(0) } var flipped by rememberSaveable { mutableStateOf(false) } @@ -927,6 +937,17 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o MoveSheet( label = AnnotatedString(if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san), inVariation = g.nodes[n.parent!!.toInt()].children.firstOrNull()?.toInt() != sheetMove, + runs = remember(sheetMove) { edit?.trainingRuns(sheetMove.toUInt())?.toInt() }, + canTrain = !n.nullMove, + onTrain = { + moveSheet = null + edit?.trainer(sheetMove.toUInt())?.let { t -> + preview = null + held.trainPly = 0 + held.trainFlipped = flipped + held.trainer.value = t + } + }, onMakeMain = { moveSheet = null runCatching { edit?.makeMain(sheetMove.toUInt()) }.getOrNull()?.let { apply(it) } @@ -1202,23 +1223,42 @@ private fun Live(content: @Composable () -> Unit) = content() /// one (in a variation), remove it with what follows. @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun MoveSheet(label: AnnotatedString, inVariation: Boolean, onMakeMain: () -> Unit, onDelete: () -> Unit, onDismiss: () -> Unit) { +private fun MoveSheet( + label: AnnotatedString, + inVariation: Boolean, + runs: Int?, + canTrain: Boolean, + onMakeMain: () -> Unit, + onDelete: () -> Unit, + onTrain: () -> Unit, + onDismiss: () -> Unit, +) { androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss) { Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { Text(label, style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) - if (inVariation) SheetAction(Icons.Rounded.VerticalAlignTop, stringResource(R.string.make_main), onMakeMain) - SheetAction(Icons.Rounded.Close, stringResource(R.string.delete_move), onDelete) + 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.School, + stringResource(R.string.train_learn), + trailing = runs?.takeIf { it > 0 }?.let { pluralStringResource(R.plurals.train_runs, it, it) }, + enabled = canTrain, + onClick = onTrain, + ) } } } @Composable -private fun SheetAction(icon: ImageVector, text: String, onClick: () -> Unit) { +private fun SheetAction(icon: ImageVector, text: String, trailing: String? = null, enabled: Boolean = true, onClick: () -> Unit) { + val alpha = if (enabled) 1f else 0.38f Row( - Modifier.fillMaxWidth().height(56.dp).clickable(onClick = onClick).padding(horizontal = 24.dp), + Modifier.fillMaxWidth().height(56.dp).clickable(enabled = enabled, onClick = onClick).padding(horizontal = 24.dp), verticalAlignment = Alignment.CenterVertically, ) { - Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant) - Text(text, Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge) + Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)) + Text(text, Modifier.weight(1f).padding(start = 16.dp), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface.copy(alpha = alpha)) + trailing?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } } } 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 14dcce4..a3a9b23 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,8 +50,13 @@ 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 + /// An opening being learned over the game (android-play.md §32), how far, the board's side. + val trainer = mutableStateOf(null) + var trainPly = 0 + var trainFlipped = false override fun onCleared() { + trainer.value?.close() session.value?.close() } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/TrainScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/TrainScreen.kt new file mode 100644 index 0000000..e8edad2 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/TrainScreen.kt @@ -0,0 +1,268 @@ +package io.github.vrubelroman.chesspenguin.ui + +import android.view.HapticFeedbackConstants +import androidx.activity.compose.BackHandler +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.Spacer +import androidx.compose.foundation.layout.fillMaxSize +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.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.rounded.Replay +import androidx.compose.material.icons.rounded.SwapVert +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +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.platform.LocalView +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 kotlinx.coroutines.delay +import uniffi.mobile_api.TrainVerdict +import uniffi.mobile_api.Trainer + +/// A wrong move of the trainer, on the board for a moment (§32.2). +private data class Wrong(val fen: String, val from: String, val to: String) + +/// Learning an opening (android-play.md §32): the user plays the moves of both sides +/// of the line from memory; a wrong move shows for 400 ms and is taken back. +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TrainScreen(trainer: Trainer, ply0: Int, startFlipped: Boolean, onPly: (Int) -> Unit, onExit: () -> Unit) { + val app = app() + val prefs by app.settings.prefs.collectAsState() + val context = androidx.compose.ui.platform.LocalContext.current + val pieces = remember { Pieces(context) } + val view = LocalView.current + val lang = uiLanguage() + val san = remember(prefs.notation, lang) { { s: String -> displaySan(s, prefs.notation, lang) } } + var ply by remember { mutableIntStateOf(ply0) } + var flipped by remember { mutableStateOf(startFlipped) } + var wrong by remember { mutableStateOf(null) } + // Said after a wrong move until the right one. + var missed by remember { mutableStateOf(false) } + var changes by remember { mutableIntStateOf(0) } + val st = remember(ply, changes) { trainer.state(ply.toUInt()) } + BackHandler(onBack = onExit) + LaunchedEffect(wrong) { + if (wrong != null) { + delay(400) + wrong = null + } + } + fun buzz(reject: Boolean) { + if (prefs.vibration) view.performHapticFeedback(if (reject) HapticFeedbackConstants.REJECT else HapticFeedbackConstants.CLOCK_TICK) + } + fun move(uci: String) { + when (trainer.judge(ply.toUInt(), uci)) { + TrainVerdict.RIGHT, TrainVerdict.FINISHED -> { + missed = false + ply += 1 + onPly(ply) + buzz(false) + } + TrainVerdict.WRONG -> { + trainer.fenAfter(ply.toUInt(), uci)?.let { wrong = Wrong(it, uci.substring(0, 2), uci.substring(2, 4)) } + missed = true + changes++ + buzz(true) + } + TrainVerdict.DONE -> {} + } + } + val sub = listOfNotNull(trainer.game(), stringResource(R.string.train_up_to, san(trainer.upTo()).text)).joinToString(" · ") + Scaffold( + topBar = { + TopAppBar( + navigationIcon = { IconButton(onClick = onExit) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } }, + title = { + Column { + Text(stringResource(R.string.train_title), style = MaterialTheme.typography.titleMedium) + Text(sub, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + ) + }, + bottomBar = { + Column { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly) { + IconButton(onClick = { flipped = !flipped }) { Icon(Icons.Rounded.SwapVert, stringResource(R.string.flip)) } + TextButton(enabled = ply > 0 || st.done, onClick = { + trainer.again() + ply = 0 + onPly(0) + missed = false + wrong = null + changes++ + }) { + Icon(Icons.Rounded.Replay, null) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.train_restart)) + } + } + } + } + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding)) { + if (!st.done) { + // The task: which move, whose turn, how far. + val whiteToMove = st.fen.substringAfter(' ').startsWith("w") + Column(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalArrangement = Arrangement.Center) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.train_move_of, (ply + 1).toString(), st.length.toString()), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + Text(stringResource(if (whiteToMove) R.string.train_white else R.string.train_black), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium) + } + LinearProgressIndicator(progress = { ply.toFloat() / st.length.toInt().coerceAtLeast(1) }, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) + } + } + val w = wrong + Board( + fen = w?.fen ?: st.fen, + flipped = flipped, + lastFrom = w?.from ?: st.fromSquare, + lastTo = w?.to ?: st.toSquare, + pieces = pieces, + theme = prefs.board, + set = prefs.pieces, + description = stringResource(R.string.train_title), + arrows = st.hint?.let { listOf(BoardArrow(it[0], it[1], EngineArrow)) } ?: emptyList(), + animated = prefs.animation, + modifier = Modifier.fillMaxWidth(), + input = if (st.done || w != null) null else BoardInput( + remember(ply, changes) { trainer.legalMoves(ply.toUInt()) }, + onMove = ::move, + // The line's own piece where it promotes; a queen otherwise (§29.4). + promotion = { pair -> trainer.promotionAt(ply.toUInt())?.takeIf { it.startsWith(pair) }?.last() }, + ), + alert = w?.let { it.from to it.to }, + ) + if (!st.done) { + // You: the mistakes of this run, or before the first move what was before. + Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { + val text = when { + st.hint != null -> stringResource(R.string.train_arrow) + missed -> stringResource(R.string.train_wrong) + ply == 0 && st.mistakes == 0u -> history(st.before) + else -> stringResource(R.string.train_mistakes, st.mistakes.toString()) + } + Text( + text, + Modifier.weight(1f), + color = if (missed && st.hint == null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (st.mayShow && st.hint == null) { + TextButton(onClick = { + trainer.show(ply.toUInt()) + changes++ + }) { Text(stringResource(R.string.train_show)) } + } else if (ply > 0 || st.mistakes > 0u) { + Text( + stringResource(R.string.train_run, (st.before.runs + 1u).toString()), + Modifier.padding(end = 12.dp), + color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } + Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) { + if (st.done) Result(st, onAgain = { + trainer.again() + ply = 0 + onPly(0) + missed = false + changes++ + }, onExit = onExit) + // The moves played so far, two to a row. + st.played.chunked(2).forEachIndexed { i, pair -> + Row(Modifier.fillMaxWidth().height(40.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text("${i + 1}", Modifier.width(32.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(san(pair[0]), Modifier.weight(1f), fontWeight = FontWeight.Medium) + Text(pair.getOrNull(1)?.let { san(it) } ?: androidx.compose.ui.text.AnnotatedString(""), Modifier.weight(1f), fontWeight = FontWeight.Medium) + } + } + } + } + } +} + +/// «Last time: 2 · best: 0», «Not done before». +@Composable +private fun history(s: uniffi.mobile_api.TrainStats): String = when { + s.runs == 0u -> stringResource(R.string.train_not_done) + s.cleanStreak >= 2u -> stringResource(R.string.train_last_streak, (s.last ?: 0u).toString(), s.cleanStreak.toString()) + else -> stringResource(R.string.train_last_best, (s.last ?: 0u).toString(), s.best?.toString() ?: "–") +} + +/// The end of a run (§32.3): how it went, the line's runs, again or back to the game. +@Composable +private fun Result(st: uniffi.mobile_api.TrainState, onAgain: () -> Unit, onExit: () -> Unit) { + val after = st.after ?: st.before + Column( + Modifier + .fillMaxWidth() + .padding(16.dp) + .background(MaterialTheme.colorScheme.surfaceContainerHigh, RoundedCornerShape(16.dp)) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text( + when { + st.hinted -> stringResource(R.string.train_done_hint, st.mistakes.toString()) + st.mistakes == 0u -> stringResource(R.string.train_done_clean) + else -> stringResource(R.string.train_done, st.mistakes.toString()) + }, + style = MaterialTheme.typography.titleMedium, + ) + val line = buildList { + add(stringResource(R.string.train_run_best, after.runs.toString(), after.best?.toString() ?: "–")) + if (after.cleanStreak >= 2u) add(stringResource(R.string.train_streak, after.cleanStreak.toString())) + }.joinToString(" · ") + Text(line, style = MaterialTheme.typography.bodyMedium) + if (after.recentMistakes.size > 1) { + val runs = after.recentMistakes.zip(after.recentHinted).joinToString(" · ") { (m, h) -> if (h) "$m*" else "$m" } + Text(stringResource(R.string.train_recent, runs), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = onAgain, modifier = Modifier.weight(1f).height(48.dp)) { Text(stringResource(R.string.train_again)) } + OutlinedButton(onClick = onExit, modifier = Modifier.weight(1f).height(48.dp)) { Text(stringResource(R.string.train_back)) } + } + } +} diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index e2d4aff..88833cf 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -433,4 +433,31 @@ Weiter bearbeiten Bearbeiten Weiter + Eröffnung lernen + bis %1$s + Eröffnung bis zu diesem Zug lernen + Zug %1$s von %2$s + ♔ Weiß am Zug + ♚ Schwarz am Zug + Fehler: %1$s + Durchgang %1$s + × In der Partie folgt hier ein anderer Zug + Zug zeigen + Diese Linie noch nicht geübt + Zuletzt: %1$s · fehlerfrei in Folge: %2$s + Zuletzt: %1$s · Bestwert: %2$s + Fehlerfrei geschafft + Mit Hinweis geschafft · Fehler: %1$s + Geschafft · Fehler: %1$s + Durchgang %1$s · Bestwert: %2$s + fehlerfrei in Folge: %1$s + Letzte: %1$s + Spielen Sie den Zug des Pfeils + ↻ Noch einmal + ⬅ Zurück zur Partie + Von vorn + + %1$d Durchgang + %1$d Durchgänge + diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 8369a52..7145a46 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -440,4 +440,32 @@ Seguir editando Editar Siguiente + Aprendiendo la apertura + hasta %1$s + Aprender la apertura hasta esta jugada + Jugada %1$s de %2$s + ♔ Juegan blancas + ♚ Juegan negras + Errores: %1$s + Repaso %1$s + × En la partida hay otra jugada aquí + Mostrar la jugada + Línea aún no repasada + La última vez: %1$s · sin errores seguidos: %2$s + La última vez: %1$s · mejor: %2$s + Completado sin errores + Completado con pista · errores: %1$s + Completado · errores: %1$s + Repaso %1$s · mejor: %2$s + sin errores seguidos: %1$s + Recientes: %1$s + Juega la jugada de la flecha + ↻ Otra vez + ⬅ Volver a la partida + Desde el principio + + %1$d repaso + %1$d repasos + %1$d repasos + diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 66b69db..95fd11a 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -440,4 +440,32 @@ Continuer Modifier Suivant + Apprentissage de l\'ouverture + jusqu\'à %1$s + Apprendre l\'ouverture jusqu\'à ce coup + Coup %1$s sur %2$s + ♔ Trait aux Blancs + ♚ Trait aux Noirs + Erreurs : %1$s + Passage %1$s + × La partie a un autre coup ici + Montrer le coup + Ligne jamais parcourue + La dernière fois : %1$s · sans erreur d\'affilée : %2$s + La dernière fois : %1$s · meilleur : %2$s + Terminé sans erreur + Terminé avec un indice · erreurs : %1$s + Terminé · erreurs : %1$s + Passage %1$s · meilleur : %2$s + sans erreur d\'affilée : %1$s + Récents : %1$s + Jouez le coup indiqué par la flèche + ↻ Encore + ⬅ Retour à la partie + Recommencer + + %1$d passage + %1$d passages + %1$d passages + diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index a65f4ba..412f0ca 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -440,4 +440,32 @@ Continua a modificare Modifica Avanti + Studio dell\'apertura + fino a %1$s + Studia l\'apertura fino a questa mossa + Mossa %1$s di %2$s + ♔ Muove il Bianco + ♚ Muove il Nero + Errori: %1$s + Giro %1$s + × Nella partita qui c\'è un\'altra mossa + Mostra la mossa + Linea mai ripassata + L\'ultima volta: %1$s · senza errori di fila: %2$s + L\'ultima volta: %1$s · migliore: %2$s + Completato senza errori + Completato con un aiuto · errori: %1$s + Completato · errori: %1$s + Giro %1$s · migliore: %2$s + senza errori di fila: %1$s + Recenti: %1$s + Gioca la mossa indicata dalla freccia + ↻ Ancora + ⬅ Torna alla partita + Da capo + + %1$d ripasso + %1$d ripassi + %1$d ripassi + diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index f594a15..dfd426e 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -434,4 +434,31 @@ Өңдеуді жалғастыру Өзгерту Келесі + Дебютті үйрену + %1$s дейін + Дебютті осы жүріске дейін үйрену + Жүріс %1$s / %2$s + ♔ Ақтар жүреді + ♚ Қаралар жүреді + Қателер: %1$s + Әрекет %1$s + × Партияда мұнда басқа жүріс + Жүрісті көрсету + Бұл линия әлі өтілмеген + Соңғы рет: %1$s · қатарынан қатесіз: %2$s + Соңғы рет: %1$s · ең үздігі: %2$s + Қатесіз өтілді + Көмекпен өтілді · қателер: %1$s + Өтілді · қателер: %1$s + Әрекет %1$s · ең үздігі: %2$s + қатарынан қатесіз: %1$s + Соңғылары: %1$s + Көрсеткідегі жүрісті жасаңыз + ↻ Қайталау + ⬅ Партияға оралу + Басынан + + %1$d рет + %1$d рет + diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 7009880..1db920e 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -441,4 +441,32 @@ Continuar editando Editar Avançar + Aprendendo a abertura + até %1$s + Aprender a abertura até este lance + Lance %1$s de %2$s + ♔ Brancas jogam + ♚ Pretas jogam + Erros: %1$s + Rodada %1$s + × Na partida há outro lance aqui + Mostrar o lance + Linha ainda não treinada + Última vez: %1$s · sem erros seguidos: %2$s + Última vez: %1$s · melhor: %2$s + Concluído sem erros + Concluído com dica · erros: %1$s + Concluído · erros: %1$s + Rodada %1$s · melhor: %2$s + sem erros seguidos: %1$s + Recentes: %1$s + Jogue o lance da seta + ↻ De novo + ⬅ Voltar à partida + Do início + + %1$d passagem + %1$d passagens + %1$d passagens + diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 22d7710..084641a 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -447,4 +447,33 @@ Продолжить правку Изменить Далее + Учим дебют + до %1$s + Учить дебют до этого хода + Ход %1$s из %2$s + ♔ ход белых + ♚ ход чёрных + Ошибок: %1$s + Прохождение %1$s + × В партии — другой ход + Показать ход + Эту линию ещё не проходили + Прошлое: %1$s · без ошибок подряд: %2$s + Прошлое: %1$s · лучшее: %2$s + Пройдено без ошибок + Пройдено с подсказкой · ошибок: %1$s + Пройдено · ошибок: %1$s + Прохождение %1$s · лучшее: %2$s + без ошибок подряд: %1$s + Последние: %1$s + Сделайте ход со стрелки + ↻ Повторить + ⬅ К партии + Сначала + + прохождений: %1$d + прохождений: %1$d + прохождений: %1$d + прохождений: %1$d + diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index 25981eb..c412b35 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -432,4 +432,31 @@ Tahrirlashni davom ettirish Tahrirlash Keyingi + Debyutni o‘rganish + %1$s gacha + Debyutni shu yurishgacha o‘rganish + Yurish %1$s / %2$s + ♔ Oqlar yuradi + ♚ Qoralar yuradi + Xatolar: %1$s + Urinish %1$s + × Partiyada bu yerda boshqa yurish + Yurishni ko‘rsatish + Bu liniya hali o‘tilmagan + Oxirgi marta: %1$s · ketma-ket xatosiz: %2$s + Oxirgi marta: %1$s · eng yaxshi: %2$s + Xatosiz o‘tildi + Yordam bilan o‘tildi · xatolar: %1$s + O‘tildi · xatolar: %1$s + Urinish %1$s · eng yaxshi: %2$s + ketma-ket xatosiz: %1$s + So‘nggilari: %1$s + Strelkadagi yurishni qiling + ↻ Yana + ⬅ Partiyaga qaytish + Boshidan + + %1$d marta + %1$d marta + diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index 6010b52..528b828 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -437,4 +437,31 @@ Keep editing Edit Next + Learning the opening + up to %1$s + Learn the opening up to this move + Move %1$s of %2$s + ♔ White to move + ♚ Black to move + Mistakes: %1$s + Run %1$s + × The game has another move here + Show the move + Not done before + Last time: %1$s · clean in a row: %2$s + Last time: %1$s · best: %2$s + Done without mistakes + Done with a hint · mistakes: %1$s + Done · mistakes: %1$s + Run %1$s · best: %2$s + clean in a row: %1$s + Recent: %1$s + Play the move on the arrow + ↻ Again + ⬅ Back to the game + From the start + + %1$d run + %1$d runs + diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs index 9349ceb..390d5cf 100644 --- a/apps/desktop/src/maia_download.rs +++ b/apps/desktop/src/maia_download.rs @@ -11,16 +11,18 @@ use std::sync::{Arc, Mutex}; use sha2::{Digest, Sha256}; -/// The published models. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Model { - /// 5M parameters: plays up to about 1800. - Small, - /// 79M parameters: stronger and closer to people, several times slower. - Large, +pub use maia::strength::Model; + +/// Where each model is published. +pub trait Published { + fn repo(self) -> &'static str; + fn revision(self) -> &'static str; + fn file(self) -> &'static str; + fn sha256(self) -> &'static str; + fn size(self) -> u64; } -impl Model { +impl Published for Model { fn repo(self) -> &'static str { match self { Model::Small => "Maia3-5M", @@ -49,7 +51,7 @@ impl Model { } } - pub fn size(self) -> u64 { + fn size(self) -> u64 { match self { Model::Small => 20_968_049, Model::Large => 315_651_851, diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 3a0ea42..1b19439 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -11,7 +11,8 @@ use chess_core::shakmaty::{Chess, Color, EnPassantMode, Move, Position}; use serde::{Deserialize, Serialize}; use crate::i18n::tr; -use crate::maia_download::Model; +use crate::maia_download::Published; +use maia::strength::Model; // ----- time controls -------------------------------------------------------------------- @@ -157,82 +158,7 @@ pub const STRENGTH_MAX: u32 = 2100; // ----- Maia's strength ---------------------------------------------------------------- -/// The strongest the small model plays (with the large one missing). -pub const SMALL_MAX: u32 = 1800; - -/// Measured (docs/research/maia-strength.md): Maia's rating input → her strength on -/// the Lichess blitz scale, as she plays here (temperature 1, rare moves dropped). -const SMALL: &[(u32, u32)] = &[ - (600, 1043), - (800, 1154), - (1100, 1333), - (1300, 1426), - (1500, 1485), - (1700, 1563), - (1900, 1632), - (2100, 1683), - (2300, 1737), - (2600, 1767), -]; -const LARGE: &[(u32, u32)] = &[ - (600, 1078), - (1100, 1375), - (1500, 1605), - (1900, 1794), - (2300, 1964), - (2600, 2000), -]; - -/// Above what a model plays choosing among the likely moves (temperature 1), it is made -/// stronger by choosing more surely: measured strength at its top rating input → the -/// temperature (0: always the most likely move). -const SMALL_SURE: &[(u32, f32)] = &[(1767, 1.0), (1854, 0.5)]; -const LARGE_SURE: &[(u32, f32)] = &[(1976, 1.0), (2053, 0.5), (2126, 0.0)]; - -/// How surely `model` chooses its move to play at `strength` (1 below its top). -pub fn temperature(model: Model, strength: u32) -> f32 { - let table = match model { - Model::Small => SMALL_SURE, - Model::Large => LARGE_SURE, - }; - let (first, last) = (table[0], table[table.len() - 1]); - if strength <= first.0 { - return first.1; - } - if strength >= last.0 { - return last.1; - } - let i = table - .iter() - .position(|p| p.0 >= strength) - .unwrap_or(table.len() - 1); - let ((a_s, a_t), (b_s, b_t)) = (table[i - 1], table[i]); - let k = (strength - a_s) as f32 / (b_s - a_s) as f32; - a_t + k * (b_t - a_t) -} - -/// The rating to give `model` for it to play at `strength` (between the measured -/// points, in proportion; outside them, the nearest). -pub fn rating_input(model: Model, strength: u32) -> u32 { - let table = match model { - Model::Small => SMALL, - Model::Large => LARGE, - }; - let (first, last) = (table[0], table[table.len() - 1]); - if strength <= first.1 { - return first.0; - } - if strength >= last.1 { - return last.0; - } - let i = table - .iter() - .position(|p| p.1 >= strength) - .unwrap_or(table.len() - 1); - let ((a_in, a_out), (b_in, b_out)) = (table[i - 1], table[i]); - let t = f64::from(strength - a_out) / f64::from(b_out - a_out); - (f64::from(a_in) + t * f64::from(b_in - a_in)).round() as u32 -} +pub use maia::strength::{SMALL_MAX, rating_input, temperature}; /// The model to play at `strength`, with its file: the large one when it is there, /// else the small one up to its ceiling. `Err`: the model to download. @@ -493,13 +419,8 @@ impl Opponent { r = newer; } let started = Instant::now(); - let mut p = maia.predict(&r.positions, r.self_elo, r.oppo_elo); - // Human mistakes, not accidents: a move less than a tenth as likely as - // the most likely one is not played (a 2600 does not hang the queen - // one time in five thousand). - let top = p.moves.first().map_or(0.0, |(_, pr)| *pr); - p.moves.retain(|(_, pr)| *pr >= 0.1 * top); - let m = maia::pick(&p, r.temperature, random_unit()); + let p = maia.predict(&r.positions, r.self_elo, r.oppo_elo); + let m = maia::strength::choose(&p, r.temperature, random_unit()); let rest = r.pause.saturating_sub(started.elapsed()); std::thread::sleep(rest); // Her clock: the pause, or the computing when it took longer (a slow @@ -606,7 +527,7 @@ pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Dur mod tests { #[test] fn strength_to_rating_input() { - use crate::maia_download::Model; + use maia::strength::Model; // The measured points themselves, in proportion between them, the ends held. assert_eq!(rating_input(Model::Large, 1605), 1500); assert_eq!(rating_input(Model::Large, 2000), 2600); diff --git a/crates/maia/src/lib.rs b/crates/maia/src/lib.rs index 16e1f12..6776d3d 100644 --- a/crates/maia/src/lib.rs +++ b/crates/maia/src/lib.rs @@ -11,6 +11,7 @@ mod checkpoint; mod net; +pub mod strength; mod weights; pub use net::Prediction; diff --git a/crates/maia/src/strength.rs b/crates/maia/src/strength.rs new file mode 100644 index 0000000..d565e5d --- /dev/null +++ b/crates/maia/src/strength.rs @@ -0,0 +1,147 @@ +//! How strong Maia plays (docs/research/maia-strength.md): the measured tables of the +//! published models, from a strength on the Lichess blitz scale to the rating to give +//! the network and how surely to choose, and the choice of the move itself. The desktop +//! and the Android apps play by these. + +use shakmaty::Move; + +use crate::{Prediction, pick}; + +/// The published models. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Model { + /// 5M parameters: plays up to about 1800. + Small, + /// 79M parameters: stronger and closer to people, several times slower. + Large, +} + +/// The strongest the small model plays (with the large one missing). +pub const SMALL_MAX: u32 = 1800; + +/// Measured (docs/research/maia-strength.md): Maia's rating input → her strength on +/// the Lichess blitz scale, as she plays here (temperature 1, rare moves dropped). +const SMALL: &[(u32, u32)] = &[ + (600, 1043), + (800, 1154), + (1100, 1333), + (1300, 1426), + (1500, 1485), + (1700, 1563), + (1900, 1632), + (2100, 1683), + (2300, 1737), + (2600, 1767), +]; +const LARGE: &[(u32, u32)] = &[ + (600, 1078), + (1100, 1375), + (1500, 1605), + (1900, 1794), + (2300, 1964), + (2600, 2000), +]; + +/// Above what a model plays choosing among the likely moves (temperature 1), it is made +/// stronger by choosing more surely: measured strength at its top rating input → the +/// temperature (0: always the most likely move). +const SMALL_SURE: &[(u32, f32)] = &[(1767, 1.0), (1854, 0.5)]; +const LARGE_SURE: &[(u32, f32)] = &[(1976, 1.0), (2053, 0.5), (2126, 0.0)]; + +/// How surely `model` chooses its move to play at `strength` (1 below its top). +pub fn temperature(model: Model, strength: u32) -> f32 { + let table = match model { + Model::Small => SMALL_SURE, + Model::Large => LARGE_SURE, + }; + let (first, last) = (table[0], table[table.len() - 1]); + if strength <= first.0 { + return first.1; + } + if strength >= last.0 { + return last.1; + } + let i = table + .iter() + .position(|p| p.0 >= strength) + .unwrap_or(table.len() - 1); + let ((a_s, a_t), (b_s, b_t)) = (table[i - 1], table[i]); + let k = (strength - a_s) as f32 / (b_s - a_s) as f32; + a_t + k * (b_t - a_t) +} + +/// The rating to give `model` for it to play at `strength` (between the measured +/// points, in proportion; outside them, the nearest). +pub fn rating_input(model: Model, strength: u32) -> u32 { + let table = match model { + Model::Small => SMALL, + Model::Large => LARGE, + }; + let (first, last) = (table[0], table[table.len() - 1]); + if strength <= first.1 { + return first.0; + } + if strength >= last.1 { + return last.0; + } + let i = table + .iter() + .position(|p| p.1 >= strength) + .unwrap_or(table.len() - 1); + let ((a_in, a_out), (b_in, b_out)) = (table[i - 1], table[i]); + let t = f64::from(strength - a_out) / f64::from(b_out - a_out); + (f64::from(a_in) + t * f64::from(b_in - a_in)).round() as u32 +} + +/// The move to play from a prediction: a move less than a tenth as likely as the most +/// likely one is not played (human mistakes, not accidents: a 2600 does not hang the +/// queen one time in five thousand), the rest drawn at `temperature`. `random` is in +/// [0, 1). +pub fn choose(prediction: &Prediction, temperature: f32, random: f32) -> Option { + let top = prediction.moves.first().map_or(0.0, |(_, p)| *p); + let likely = Prediction { + moves: prediction + .moves + .iter() + .filter(|(_, p)| *p >= 0.1 * top) + .cloned() + .collect(), + wdl: prediction.wdl, + }; + pick(&likely, temperature, random) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strength_turns_into_the_rating_to_give() { + // The measured points themselves, in proportion between them, the ends held. + assert_eq!(rating_input(Model::Large, 1605), 1500); + assert_eq!(rating_input(Model::Large, 2000), 2600); + assert_eq!(rating_input(Model::Small, 1485), 1500); + assert_eq!(rating_input(Model::Small, SMALL_MAX), 2600); + assert_eq!(rating_input(Model::Small, 900), 600); + // Above the top input: surer choices, down to the most likely move. + assert_eq!(temperature(Model::Large, 1900), 1.0); + assert!((temperature(Model::Large, 2053) - 0.5).abs() < 1e-6); + assert_eq!(temperature(Model::Large, 2200), 0.0); + assert!(temperature(Model::Small, SMALL_MAX) < 1.0); + } + + #[test] + fn rare_moves_are_not_chosen() { + use shakmaty::{Chess, Position}; + let pos = Chess::default(); + let moves = pos.legal_moves(); + let p = Prediction { + moves: vec![(moves[0], 0.9), (moves[1], 0.05)], + wdl: [0.0; 3], + }; + // Whatever the draw: under a tenth of the best is never played. + for r in [0.0, 0.5, 0.99] { + assert_eq!(choose(&p, 5.0, r), Some(moves[0])); + } + } +}