From 08aac5d83b71b91ff3e909f5f22eec0fd82380fa Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 26 Oct 2026 00:39:08 +0300 Subject: [PATCH] Android: moves on the board (tap-tap, drag, legal dots, queen), variations, move sheet, undo A game of a database is changed in memory (never saved into someone else's file): a move extends the line, follows an existing one or becomes a variation; a long press on a move offers make-main and delete (with Undo); the menu's Undo takes any change back. Research: Maia's strength against people, reviewed from the literature. Co-Authored-By: Claude Opus 5.5 --- .../vrubelroman/chesspenguin/ui/Board.kt | 129 +++++++++++++++++- .../vrubelroman/chesspenguin/ui/GameScreen.kt | 117 ++++++++++++++-- .../vrubelroman/chesspenguin/ui/Notation.kt | 69 +++++++++- .../app/src/main/res/values-de/strings.xml | 6 +- .../app/src/main/res/values-es/strings.xml | 6 +- .../app/src/main/res/values-fr/strings.xml | 6 +- .../app/src/main/res/values-it/strings.xml | 6 +- .../app/src/main/res/values-kk/strings.xml | 6 +- .../app/src/main/res/values-pt/strings.xml | 6 +- .../app/src/main/res/values-ru/strings.xml | 6 +- .../app/src/main/res/values-uz/strings.xml | 6 +- .../app/src/main/res/values/strings.xml | 6 +- docs/research/maia-strength.md | 78 +++++++++++ 13 files changed, 416 insertions(+), 31 deletions(-) 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 d31e6de..4e61adc 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 @@ -10,6 +10,8 @@ import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.layout.aspectRatio import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -29,6 +31,8 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity @@ -40,6 +44,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.caverock.androidsvg.SVG import io.github.vrubelroman.chesspenguin.data.BoardTheme @@ -119,6 +124,32 @@ fun boardCorner(context: Context, file: String, size: Int): ImageBitmap? = runCa } }.getOrNull() +/// "e4" of the square with index `i` of [placement] (a8 = 0). +fun squareName(i: Int): String = "${'a' + i % 8}${'8' - i / 8}" + +/// Moves on the board (android-play.md §29): the legal moves of the position in UCI and +/// what to do with the one made. A pawn on the last rank becomes a queen (owner's +/// decision §29.4); `promotion` may name another piece for a from–to pair (the trainer +/// takes the line's own piece). +class BoardInput( + val legal: List, + val onMove: (String) -> Unit, + val promotion: (String) -> Char? = { null }, +) { + /// The squares a piece on `from` can go to. + fun targets(from: String): Set = legal.filter { it.startsWith(from) }.map { it.substring(2, 4) }.toSet() + + /// The move from `from` to `to`, or null when there is none. + fun move(from: String, to: String): String? { + val pair = from + to + val all = legal.filter { it.startsWith(pair) } + if (all.isEmpty()) return null + if (all.size == 1) return all[0] + val piece = promotion(pair) ?: 'q' + return all.firstOrNull { it == pair + piece } ?: all.firstOrNull { it == pair + 'q' } ?: all[0] + } +} + /// An arrow on the board: a comment's `[%cal]` or the engine's best move. data class BoardArrow(val from: String, val to: String, val color: Color, val weight: Float = 1f) @@ -138,8 +169,9 @@ fun markColor(letter: String): Color = when (letter) { val EngineArrow = Color(0, 48, 136, 160) /// The board: full width, the chosen board and pieces, the last move lit, the -/// coordinates inside the edge squares (as on Lichess). It takes no touches in the first -/// version (docs/design/android-ui.md §7.2). A move slides into place (250 ms). +/// coordinates inside the edge squares (as on Lichess). With `input` a move is made by +/// tapping a piece and then a square, or by dragging it (android-play.md §29.2–29.3); +/// without it the board takes no touches. A move slides into place (250 ms). @Composable fun Board( fen: String, @@ -155,6 +187,7 @@ fun Board( marks: List = emptyList(), check: Boolean = false, animated: Boolean = true, + input: BoardInput? = null, ) { val colors = LocalChessColors.current val context = LocalContext.current @@ -185,10 +218,71 @@ fun Board( } val coordStyle = TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Medium) val density = LocalDensity.current + // A move being made: the piece chosen, and while dragged, where the finger is. + var selected by remember(fen) { mutableStateOf(null) } + var dragAt by remember(fen) { mutableStateOf(null) } + val slop = LocalViewConfiguration.current.touchSlop + val currentInput = androidx.compose.runtime.rememberUpdatedState(input) + val lift = with(density) { 22.dp.toPx() } + fun indexAt(p: Offset, sq: Float): Int? { + val col = (p.x / sq).toInt() + val row = (p.y / sq).toInt() + if (p.x < 0 || p.y < 0 || col !in 0..7 || row !in 0..7) return null + return if (flipped) (7 - row) * 8 + (7 - col) else row * 8 + col + } + val touch = if (input == null) Modifier else Modifier.pointerInput(fen, flipped) { + awaitEachGesture { + val down = awaitFirstDown() + val inp = currentInput.value ?: return@awaitEachGesture + val sq = size.width / 8f + val start = indexAt(down.position, sq) ?: return@awaitEachGesture + val startName = squareName(start) + val movable = inp.targets(startName).isNotEmpty() + val was = selected + // A tap on a target of the piece chosen makes the move. + if (was != null && start != was) { + inp.move(squareName(was), startName)?.let { m -> + selected = null + inp.onMove(m) + return@awaitEachGesture + } + } + if (movable) selected = start + var dragging = false + while (true) { + val e = awaitPointerEvent() + val c = e.changes.firstOrNull { it.id == down.id } ?: break + if (!c.pressed) { + if (dragging) { + val end = indexAt(c.position, sq) + dragAt = null + val m = end?.let { inp.move(startName, squareName(it)) } + if (m != null) { + selected = null + inp.onMove(m) + } + // A drop elsewhere: the piece goes back, still chosen. + } else if (!movable || start == was) { + // A tap on the same piece, an empty square or the other side's + // piece: nothing chosen any more. + selected = null + } + c.consume() + break + } + if (movable && !dragging && (c.position - down.position).getDistance() > slop) dragging = true + if (dragging) { + dragAt = c.position + c.consume() + } + } + } + } Canvas( modifier .aspectRatio(1f) .onSizeChanged { side = it.width } + .then(touch) .semantics { contentDescription = description }, ) { val sq = size.width / 8f @@ -209,6 +303,8 @@ 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)) } + val chosen = selected + if (chosen != null) drawRect(colors.lastMove.copy(alpha = 0.5f), cell(chosen), Size(sq, sq)) for (m in marks) { val i = squareIndex(m.square) ?: continue val c = cell(i) @@ -239,12 +335,30 @@ fun Board( if (p == ' ') continue val bmp = pieces.bitmap(set, p, px) ?: continue var at = cell(i) + // The piece being dragged: faint on its square, drawn under the finger below. + if (i == chosen && dragAt != null) { + drawImage(bmp, dstOffset = IntOffset(at.x.toInt(), at.y.toInt()), dstSize = IntSize(px, px), alpha = 0.3f) + continue + } if (animate && i == to && from != null && slide.value < 1f) { val start = cell(from) at = Offset(start.x + (at.x - start.x) * slide.value, start.y + (at.y - start.y) * slide.value) } drawImage(bmp, dstOffset = IntOffset(at.x.toInt(), at.y.toInt()), dstSize = IntSize(px, px)) } + // Where the piece chosen can go: a dot, a ring round a capture (as on Lichess). + if (chosen != null && input != null) { + val shade = Color(0, 0, 0, 64) + for (t in input.targets(squareName(chosen))) { + val i = squareIndex(t) ?: continue + val c = cell(i) + Offset(sq / 2, sq / 2) + if (squares[i] != ' ') { + drawCircle(shade, radius = sq / 2 - sq * 0.045f, center = c, style = Stroke(width = sq * 0.09f)) + } else { + drawCircle(shade, radius = sq * 0.155f, center = c) + } + } + } // Over the pieces, so that b, c, f, g stay readable (as on Lichess). // Coordinates: files along the bottom edge, ranks along the left edge. for (k in 0 until 8) { @@ -262,6 +376,17 @@ fun Board( val t = squareIndex(a.to) ?: continue drawArrow(cell(f) + Offset(sq / 2, sq / 2), cell(t) + Offset(sq / 2, sq / 2), sq, a) } + // The dragged piece: bigger and lifted above the finger, a shade on the square + // under it so that one sees where it goes. + val held = dragAt + if (held != null && chosen != null) { + val under = indexAt(held, sq) + if (under != null) drawCircle(Color(0, 0, 0, 31), radius = sq, center = cell(under) + Offset(sq / 2, sq / 2)) + val big = (px * 1.5f).toInt() + pieces.bitmap(set, squares[chosen], big)?.let { + drawImage(it, dstOffset = IntOffset((held.x - big / 2f).toInt(), (held.y - lift - big / 2f).toInt()), dstSize = IntSize(big, big)) + } + } } } 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 5ab6fea..65bc561 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 @@ -37,6 +37,8 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack 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.VerticalAlignTop import androidx.compose.material.icons.rounded.ChevronRight import androidx.compose.material.icons.rounded.Download import androidx.compose.material.icons.rounded.FirstPage @@ -58,7 +60,9 @@ import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -113,7 +117,9 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uniffi.mobile_api.EngineLine +import uniffi.mobile_api.Edited import uniffi.mobile_api.GameData +import uniffi.mobile_api.GameSession import uniffi.mobile_api.MoveJudgement import uniffi.mobile_api.MoveNode @@ -134,6 +140,11 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o var games by remember { mutableStateOf(app.shown[db]) } var place by rememberSaveable { mutableIntStateOf(startPlace) } var game by remember { mutableStateOf(null) } + // The game as changed on the board (android-play.md §29): moves for analysis; a game + // of someone else's file is not saved (owner's decision), its file never changes. + var edit by remember { mutableStateOf(null) } + // What reading the game noticed: kept when the game is changed. + var notes by remember { mutableStateOf>(emptyList()) } var failed by remember { mutableStateOf(false) } var current by rememberSaveable(place) { mutableIntStateOf(0) } var flipped by rememberSaveable { mutableStateOf(false) } @@ -154,9 +165,12 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o } val index = list.getOrNull(place) ?: return@LaunchedEffect game = null - val loaded = withContext(Dispatchers.Default) { runCatching { database.game(index) } } + edit = null + val loaded = withContext(Dispatchers.Default) { runCatching { database.game(index) to database.session(index) } } failed = loaded.isFailure - game = loaded.getOrNull() + game = loaded.getOrNull()?.first + edit = loaded.getOrNull()?.second + notes = game?.notes ?: emptyList() if (game != null) review.open(db, database, index) } val pieces = remember { Pieces(context) } @@ -164,7 +178,6 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o UpdateMessages(snackbar) val scope = rememberCoroutineScope() val view = LocalView.current - val hint = stringResource(R.string.board_hint) val readyText = stringResource(R.string.engine_ready) val cancelledText = stringResource(R.string.download_cancelled) val total = games?.size ?: 0 @@ -209,6 +222,8 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o val pgnCopied = stringResource(R.string.pgn_copied) val fenCopied = stringResource(R.string.fen_copied) suspend fun pgnText(): String? { + // Moves added on the board go along (the file is as it was). + edit?.takeIf { it.isModified() }?.let { e -> return withContext(Dispatchers.Default) { e.pgn() } } val index = games?.getOrNull(place) ?: return null val database = app.library.database(db).getOrNull() ?: return null return withContext(Dispatchers.Default) { database.pgn(index) } @@ -341,6 +356,19 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o fun buzz(edge: Boolean) { if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK) } + // A change of the game: shown at once, the cursor where the change says. + fun apply(e: Edited) { + preview = null + game = e.data.copy(notes = notes) + current = e.cursor.toInt() + } + // The move sheet of a long press on a move (§29.6): which move. + var moveSheet 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) } + } fun go(to: Int) { preview = null if (nodes == null || to == current || to !in nodes.indices) return @@ -471,10 +499,13 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o marks = marks, check = check, animated = prefs.animation, - modifier = boardModifier.pointerInput(Unit) { - detectTapGestures { - if (firstBoardTouch(context)) scope.launch { snackbar.showSnackbar(hint) } - } + // 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 -> + val legal = remember(g, current) { e.legalMoves(current.toUInt()) } + BoardInput(legal, onMove = { uci -> + runCatching { e.play(current.toUInt(), uci) }.getOrNull()?.let { apply(it) } + }) }, ) } @@ -534,6 +565,13 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o g != null -> Notation( g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize(), marks = if (reviewShown) reviewMarks else emptyMap(), + onLongMove = edit?.let { + { id -> + go(id) + buzz(true) + moveSheet = id + } + }, ) failed -> Text( stringResource(R.string.game_failed), @@ -597,6 +635,13 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o Box { IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) } DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + // First, and only when there is something to take back (§29.6). + if (g != null && edit?.canUndo() == true) { + DropdownMenuItem(text = { Text(stringResource(R.string.undo)) }, onClick = { + menu = false + undo() + }) + } 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). @@ -709,6 +754,32 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o confirmButton = { TextButton(onClick = { info = false }) { Text(stringResource(R.string.close)) } }, ) } + val sheetMove = moveSheet + if (sheetMove != null && g != null && edit != null) { + val n = g.nodes.getOrNull(sheetMove) + if (n == null || n.parent == null) { + moveSheet = null + } else { + MoveSheet( + label = AnnotatedString(if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + san(n.san), + inVariation = g.nodes[n.parent!!.toInt()].children.firstOrNull()?.toInt() != sheetMove, + onMakeMain = { + moveSheet = null + runCatching { edit?.makeMain(sheetMove.toUInt()) }.getOrNull()?.let { apply(it) } + }, + onDelete = { + moveSheet = null + runCatching { edit?.deleteFrom(sheetMove.toUInt()) }.getOrNull()?.let { e -> + apply(e) + scope.launch { + if (snackbar.showSnackbar(deletedText, undoText, duration = SnackbarDuration.Short) == SnackbarResult.ActionPerformed) undo() + } + } + }, + onDismiss = { moveSheet = null }, + ) + } + } if (sheet) { EngineSheet( state = netState, @@ -959,13 +1030,31 @@ private fun resultLine(context: Context, result: String): String = when (result) } /// True only the very first time the board is touched (then the hint is shown). -private fun firstBoardTouch(context: Context): Boolean { - val prefs = context.getSharedPreferences("hints", Context.MODE_PRIVATE) - if (prefs.getBoolean("board", false)) return false - prefs.edit().putBoolean("board", true).apply() - return true -} - /// A scope of its own: what is read in it is drawn again without its surroundings. @Composable private fun Live(content: @Composable () -> Unit) = content() + +/// What a long press on a move offers (android-play.md §29.6): make its line the main +/// 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) { + 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) + } + } +} + +@Composable +private fun SheetAction(icon: ImageVector, text: String, onClick: () -> Unit) { + Row( + Modifier.fillMaxWidth().height(56.dp).clickable(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) + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt index 7e79fe2..fcea838 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt @@ -1,7 +1,13 @@ package io.github.vrubelroman.chesspenguin.ui import androidx.compose.foundation.background +import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.ui.input.pointer.PointerEventPass +import kotlinx.coroutines.withTimeoutOrNull import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues @@ -19,7 +25,10 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +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.draw.clip @@ -27,6 +36,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontStyle @@ -38,6 +48,8 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.onLongClick +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.stateDescription @@ -215,6 +227,7 @@ fun Notation( onMove: (Int) -> Unit, modifier: Modifier = Modifier, marks: Map = emptyMap(), + onLongMove: ((Int) -> Unit)? = null, ) { val chess = LocalChessColors.current LaunchedEffect(current) { @@ -241,7 +254,7 @@ fun Notation( .background(MaterialTheme.colorScheme.surfaceContainerLow) .padding(horizontal = 12.dp, vertical = 8.dp), ) - is Item.Moves -> MovesRow(game, item, current, chess, san, onMove, marks) + is Item.Moves -> MovesRow(game, item, current, chess, san, onMove, marks, onLongMove) is Item.Variation -> Box( Modifier .fillMaxWidth() @@ -249,11 +262,45 @@ fun Notation( ) { Row(Modifier.height(androidx.compose.foundation.layout.IntrinsicSize.Min)) { Box(Modifier.width(2.dp).fillMaxHeight().background(MaterialTheme.colorScheme.outlineVariant)) + val text = variationText(game, item.start, current, chess, san, onMove) + var layout by remember { mutableStateOf(null) } Text( - variationText(game, item.start, current, chess, san, onMove), + text, fontSize = 15.sp, lineHeight = 28.sp, - modifier = Modifier.padding(start = 12.dp, end = 4.dp), + onTextLayout = { layout = it }, + modifier = Modifier + .padding(start = 12.dp, end = 4.dp) + .then( + if (onLongMove == null) Modifier else Modifier.pointerInput(text) { + // A long press on a move of the variation: the move it is + // on. Seen before the links (the first pass), and the rest + // of the press is taken, so that the link does not also + // take it as a tap; a short tap stays the link's. + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + val released = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) { + while (true) { + val e = awaitPointerEvent(PointerEventPass.Initial) + val c = e.changes.firstOrNull { it.id == down.id } ?: return@withTimeoutOrNull true + if (!c.pressed || (c.position - down.position).getDistance() > viewConfiguration.touchSlop) return@withTimeoutOrNull true + } + @Suppress("UNREACHABLE_CODE") true + } + if (released != null) return@awaitEachGesture + val offset = layout?.getOffsetForPosition(down.position) ?: return@awaitEachGesture + val id = text.getLinkAnnotations(offset, offset + 1).firstOrNull() + ?.let { (it.item as? LinkAnnotation.Clickable)?.tag?.removePrefix("m")?.toIntOrNull() } + ?: return@awaitEachGesture + onLongMove(id) + while (true) { + val e = awaitPointerEvent(PointerEventPass.Initial) + e.changes.forEach { it.consume() } + if (e.changes.none { it.pressed }) break + } + } + }, + ), ) } } @@ -281,6 +328,7 @@ private fun MovesRow( san: (String) -> AnnotatedString, onMove: (Int) -> Unit, marks: Map, + onLongMove: ((Int) -> Unit)?, ) { Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically) { Text( @@ -290,8 +338,8 @@ private fun MovesRow( modifier = Modifier.width(40.dp).padding(end = 8.dp), textAlign = androidx.compose.ui.text.style.TextAlign.End, ) - MoveCell(game, row.white, true, current, chess, san, onMove, Modifier.weight(1f), row.white?.let { marks[it] }) - MoveCell(game, row.black, false, current, chess, san, onMove, Modifier.weight(1f), row.black?.let { marks[it] }) + MoveCell(game, row.white, true, current, chess, san, onMove, Modifier.weight(1f), row.white?.let { marks[it] }, onLongMove) + MoveCell(game, row.black, false, current, chess, san, onMove, Modifier.weight(1f), row.black?.let { marks[it] }, onLongMove) } } @@ -306,6 +354,7 @@ private fun MoveCell( onMove: (Int) -> Unit, modifier: Modifier, mark: MoveJudgement?, + onLongMove: ((Int) -> Unit)?, ) { val selected = id != null && id == current // The engine's mark is left out where the author already put the same sign ("Nf6? ?" @@ -320,11 +369,18 @@ private fun MoveCell( (markName?.let { m -> ", $m" } ?: "") } val currentLabel = stringResource(R.string.current_move) + val actionsLabel = stringResource(R.string.move_actions) // The whole cell takes the tap; the fill only hugs the move. Box( modifier .fillMaxHeight() - .then(if (id != null) Modifier.clickable { onMove(id) } else Modifier) + .then( + when { + id == null -> Modifier + onLongMove != null -> Modifier.combinedClickable(onLongClick = { onLongMove(id) }) { onMove(id) } + else -> Modifier.clickable { onMove(id) } + }, + ) .then( if (spoken != null) { Modifier.clearAndSetSemantics { @@ -333,6 +389,7 @@ private fun MoveCell( this.selected = selected if (selected) stateDescription = currentLabel onClick { onMove(id); true } + if (onLongMove != null) onLongClick(actionsLabel) { onLongMove(id); true } } } else { Modifier diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index bfe6e28..c8081a1 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -38,7 +38,6 @@ Zug vor Zum Ende der Variante Weiter: - Dies ist ein Partiebetrachter. Blättern Sie mit ◀ ▶ unten durch die Züge. Brett, Stellung nach %1$s Brett, Ausgangsstellung Weiß hat gewonnen @@ -389,4 +388,9 @@ Version %1$s ist heruntergeladen Update auf %1$s, %2$d von %3$d Megabyte heruntergeladen Datei lässt sich nicht prüfen + Rückgängig + Züge gelöscht + Zur Hauptvariante machen + Zug und Fortsetzung löschen + Aktionen zum Zug diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 7084812..2b9b2c1 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -39,7 +39,6 @@ Jugada adelante Al final de la línea Siguiente: - Es un visor de partidas. Recorre las jugadas con ◀ ▶ abajo. Tablero, posición tras %1$s Tablero, posición inicial Ganaron las blancas @@ -395,4 +394,9 @@ La versión %1$s está descargada Actualización a %1$s, %2$d de %3$d megabytes descargados No se puede comprobar el archivo + Deshacer + Jugadas eliminadas + Convertir en línea principal + Eliminar la jugada y lo que sigue + Acciones de la jugada diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 041fa36..37cb7da 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -39,7 +39,6 @@ Coup suivant À la fin de la ligne Suite : - Ceci est une visionneuse de parties. Parcourez les coups avec ◀ ▶ en bas. Échiquier, position après %1$s Échiquier, position initiale Les Blancs ont gagné @@ -395,4 +394,9 @@ La version %1$s est téléchargée Mise à jour vers %1$s, %2$d sur %3$d mégaoctets téléchargés Fichier impossible à vérifier + Annuler + Coups supprimés + En faire la ligne principale + Supprimer le coup et la suite + Actions sur le coup diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 1d1fea1..27356d6 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -39,7 +39,6 @@ Mossa avanti Alla fine della linea Seguito: - Questo è un visualizzatore di partite. Scorri le mosse con ◀ ▶ in basso. Scacchiera, posizione dopo %1$s Scacchiera, posizione iniziale Hanno vinto i bianchi @@ -395,4 +394,9 @@ La versione %1$s è scaricata Aggiornamento a %1$s, %2$d di %3$d megabyte scaricati File non verificabile + Annulla + Mosse eliminate + Rendi linea principale + Elimina la mossa e il seguito + Azioni sulla mossa diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 5c935f7..c508c60 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -38,7 +38,6 @@ Бір жүріс алға Варианттың соңына Келесі: - Бұл партияларды қарау құралы. Жүрістерді төмендегі ◀ ▶ арқылы ауыстырыңыз. Тақта, %1$s кейінгі позиция Тақта, бастапқы позиция Ақтар жеңді @@ -390,4 +389,9 @@ %1$s нұсқасына жаңарту, %3$d мегабайттың %2$d жүктелді Файлды тексеру мүмкін емес + Қайтару + Жүрістер жойылды + Негізгі ету + Жүрісті және жалғасын жою + Жүріспен әрекеттер diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 007a0d9..304f884 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -39,7 +39,6 @@ Avançar um lance Ao fim da linha Próximo: - Este é um visualizador de partidas. Percorra os lances com ◀ ▶ abaixo. Tabuleiro, posição após %1$s Tabuleiro, posição inicial Brancas venceram @@ -396,4 +395,9 @@ Atualização para %1$s, %2$d de %3$d megabytes baixados O arquivo não pode ser verificado + Desfazer + Lances excluídos + Tornar linha principal + Excluir o lance e a continuação + Ações do lance diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index c1f4637..6b9119b 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -40,7 +40,6 @@ Ход вперёд В конец линии Дальше: - Это просмотр партии. Ходы листаются кнопками ◀ ▶ внизу. Доска, позиция после %1$s Доска, начальная позиция Победили белые @@ -401,4 +400,9 @@ Версия %1$s скачана Обновление до %1$s, скачано %2$d из %3$d мегабайт Файл нельзя проверить + Вернуть + Ходы удалены + Сделать основным + Удалить ход и продолжение + Действия с ходом diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index 017699c..0d84079 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -39,7 +39,6 @@ Bir yurish oldinga Liniya oxiriga Keyin: - Bu partiyalarni koʻrish vositasi. Yurishlarni pastdagi ◀ ▶ bilan oʻtkazing. Taxta, %1$sdan keyingi pozitsiya Taxta, boshlangʻich pozitsiya Oqlar yutdi @@ -388,4 +387,9 @@ %1$s versiyasi yuklab olindi %1$sga yangilash, %3$d megabaytdan %2$d tasi yuklab olindi Faylni tekshirib boʻlmaydi + Qaytarish + Yurishlar o‘chirildi + Asosiy qilish + Yurish va davomini o‘chirish + Yurish amallari diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index 714fdae..3a28de3 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -39,7 +39,6 @@ Move forward To the end of the line Next: - This is a game viewer. Step through the moves with ◀ ▶ below. Board, position after %1$s Board, starting position White won @@ -393,4 +392,9 @@ Update to %1$s, %2$d of %3$d megabytes downloaded The file cannot be checked + Undo + Moves deleted + Make it the main line + Delete the move and what follows + Move actions diff --git a/docs/research/maia-strength.md b/docs/research/maia-strength.md index 44e293f..1b1ac2b 100644 --- a/docs/research/maia-strength.md +++ b/docs/research/maia-strength.md @@ -264,3 +264,81 @@ - Режим «лучший ход» малой модели — ≈1910, а не ≈2000 (прежняя цифра — следствие повторяющихся партий). - **Потолок Maia-3 без поиска — ≈2125** (79M, всегда самый вероятный ход): сильный I разряд; КМС и выше недостижимы. - В программе (`play.rs`, `temperature`): выше потолка модели при T=1 (5M ≈1767, 79M ≈1976) температура снижается по таблице до нужной силы; ползунок 1100–2100. + +## Пересмотр: насколько сильна Maia на самом деле (2026-10-26) + +Вопрос владельца: «не может движок так слабо играть… не 2100 же, как на Личесе». Только чтение и источники, новых партий не было. **Факт** — со ссылкой, **Оценка** — мой вывод. + +### Коротко + +1. **Оценка.** Maia-3 79M «всегда лучший ход» играет против **людей** в блиц Lichess примерно на **2150–2350**, центр ≈ 2250. Наша цифра 2126 занижена, вероятно, на 50–200. Но «2600» на ползунке — это не сила, и до 2400+ без перебора она не дотянет. +2. **Факт (главный довод).** Единственный опубликованный замер «модель-имитатор человека без перебора против живых людей Lichess» — статья Allie (ICLR 2025). Там такие модели набирают против игроков 2400+ лишь **11–25 %**, это перформанс ≈ **2140–2260**. Наш результат с ним согласуется. +3. **Оценка.** Maia — не движок. Это «первое впечатление» человека заданного рейтинга, без расчёта. Даже «движковая» политика Lc0 без перебора на Lichess против ботов — около 2200–2300. + +### 1. Что сообщают авторы Maia и другие (факты) + +- **Maia-1** ([CSSLab/maia-chess](https://github.com/CSSLab/maia-chess)): боты `maia1/5/9`, Lc0 `nodes=1` плюс дебютная книга. Снято сегодня через [API Lichess](https://lichess.org/api/user/maia9): maia9 — блиц **1591**, пуля 1634, рапид 1753, классика 1761. Всё при RD 45 и сотнях тысяч партий. +- **Maia-2** ([arXiv 2409.20553](https://arxiv.org/abs/2409.20553)): силу игры не измеряли. В опыте с ботами на Lichess смотрели только на вовлечённость игроков: «we randomize whether players play against Maia-1 or Maia-2». +- **Maia-3 / Chessformer** ([arXiv 2605.19091](https://arxiv.org/html/2605.19091)): силу Maia-3 не измеряли, только угадывание хода (79M — 57,1 %). Авторы пишут, что 79M «shines… at modeling highly skilled play». Это про точность угадывания, а не про силу. +- **Тот же Chessformer, обученный на партиях Lc0** (Leela-CF-policy, без перебора): **2374 ± 37** турнирного Эло. Шкала BayesElo привязана к AC-270M из статьи DeepMind (2299). Это рейтинг движков между собой, а не против людей. Свёрточная политика Lc0 — 2096. +- **Ботов Maia-2/3 на Lichess нет** (§3.2). Публичных замеров «Maia-3 на 2600 против людей» я не нашёл ни у авторов, ни на форумах. На форумах есть только впечатления: «боты Maia играют на 1400–1700 независимо от уровня обучения» ([обзор на форуме Lichess](https://lichess.org/forum/general-chess-discussion/what-is-the-strongest-neural-network-only-chess-engine)). Это не замер. + +### 2. Сила политики без перебора вообще (факты) + +**DeepMind, «Grandmaster-Level Chess Without Search»** ([arXiv 2402.04494](https://arxiv.org/html/2402.04494), табл. 1). Блиц Lichess: + +| Агент | Турнир (между собой) | Lichess против ботов | Lichess против людей | +|---|---|---|---| +| Трансформер 270M (учили оценке хода по Stockfish) | 2299 | 2299 | **2895** | +| Трансформер 9M | 2025 | 2054 | — | +| Политика Lc0 без перебора | 2292 | 2224 | — | +| Политика AlphaZero без перебора | 1777 | — | — | + +- Разрыв **600 пунктов** у одной и той же модели: против людей 2895, против ботов 2299. Авторы называют три возможные причины. Люди сдаются в проигранных позициях, а боты нет. Пулы игроков несравнимы. «our models make the occasional tactical mistake which may be penalized more severely by bots than humans». +- Обучение подражанию (behavioral cloning, BC) при том же числе партий на **≈ 490** слабее, чем обучение на оценках Stockfish (табл. A4). Maia — как раз подражание, причём не лучшим ходам, а ходам людей заданного уровня. + +**Allie** ([«Human-aligned chess with a bit of search», ICLR 2025, arXiv 2410.03893](https://arxiv.org/html/2410.03893)). Трансформер 355M, обучен на блице Lichess 2022, корзины рейтинга уравнены — устроен как Maia-3. Сыграно 7483 блиц-партии с 2412 **людьми** на Lichess, перформанс по таблице ФИДЕ (табл. 4, §5.3): + +| Система | Перформанс против игроков 2500 | Против игроков 2400+ | +|---|---|---| +| Maia⋆ (Maia-1 ближайшего уровня, сверху maia-1900) | 2138 | 12,5 % очков | +| Allie-Policy (жребий при T = 1, рейтинг = рейтинг соперника) | 2136 | 11,1 % | +| Allie-Greedy (всегда лучший ход, уровень 2500) | 2260 | проигрывает 75 % | +| Allie с перебором (50 розыгрышей MCTS) | 2318 | — | +| Allie с адаптивным перебором | 2528 | откалибрована, средняя ошибка 49 Эло | + +Цитаты: «Allie-Policy and Maia are more or less evenly matched against players below 2100 Elo, but against players above 2400 Elo, both models perform poorly». Ещё: все системы без перебора «underperform ≥2400 Elo players by at least 200 Elo points». Оговорка авторов: «players all knew they were playing against a bot». + +**Оценка: что отсюда следует для Maia-3 79M** +- Политика, подражающая людям, даже 355M и в режиме «лучший ход на 2500», против сильных людей стоит ≈ **2260**. При жребии — ≈ **2140**. Это прямой замер на людях, и он почти совпадает с нашим (2053 при T = 0,5 и 2126 при T = 0). +- По статье Chessformer, 79M угадывает ходы сильных игроков точнее прежних моделей без перебора («up to 5%»). Но угадывание ≠ сила. Разумный потолок 79M «лучший ход» против людей — **2200–2350**, а не 2600. +- Почему не 2600: модель выдаёт **средний** ход игроков ~2500 по одному взгляду, без проверки тактики. Сила сильного блицора — во многом проверка кандидатов. Её у политики нет, и слабость тем заметнее, чем сильнее соперник (§3.3). + +### 3. Насколько можно верить нашему методу + +| Источник искажения | В какую сторону | Величина (оценка) | +|---|---|---| +| (а) Шкала «бот против бота» вместо «против людей». Против людей модели без перебора выглядят сильнее: у DeepMind +600 с людьми, у Allie maia-1900 почти на равных с людьми до 2100 | наши числа **занижены** относительно людей | 0…+200 | +| (б) Якоря только до 1613, а 79M T = 0 набрала **97,5 %** против maia-1900 (100 партий, `fit_new.jsonl`). Это насыщение: верх держится на цепочке 79M ↔ 5M T = 0 ↔ боты. Ошибка ±23 — только статистика, без ошибки модели Эло | неопределённость | ±100–150 | +| (в) Рейтинги ботов Maia-1 на Lichess. Боты детерминированы (T = 0), игроки повторяют выигрышные линии против книги и одного ответа. Много партий против других ботов. У Allie maia-1900 «на равных» с людьми до 2100, а её рейтинг на Lichess ≈ 1600 | якоря, вероятно, **занижены** вверху → наши числа тоже | +0…+300 на верхнем якоре, но не прямо на результате | +| (г) Отсечение 10 % и температура | при T = 0 отсечение ни на что не влияет; T = 0,5 почти не уступает T = 0 (54,5 % у T = 0 в личной встрече) | мала | +| (д) Ошибки Maia человеческие, но **зевки тактики** без расчёта. Человек 2300 их находит лучше бота Maia-1 и сам не зевает «по-ботовски» | против сильных людей Maia **слабее**, чем против ботов. Компенсирует (а) | −100…0 | +| (е) Без дебютной книги наша копия maia-1900 слабее бота на Lichess | наши числа немного **занижены** | 0…+50 | + +**Оценка.** Поправки тянут вверх, но не до 2600. Внешний замер на людях (Allie: 2140–2260 против 2400+) — независимый потолок. Он сильнее любой нашей поправки, потому что сделан на живых людях. Итоговая оценка для «79M, 2600, лучший ход» против людей в блице Lichess — **2150–2350, центр ≈ 2250**. Для 79M при T = 0,5 — на ~50–75 ниже. Для 5M — на ~200 ниже. + +### 4. Что ждать сыну и как честно проверить + +**Оценка.** Сын: блиц Lichess 2323, рапид 2366. Разница с Maia-3 79M на максимуме ≈ +0…+200 в его пользу. +- **Блиц** (оба на часах, Maia ходит мгновенно): ожидаемо **60–75 %** очков у сына. Отдельные проигрыши нормальны, «все партии легко» — тоже не противоречие. +- **Рапид или без часов:** Maia от времени не сильнее, сын сильнее. Ожидаемо **75–90 %**. +- Режим «всегда лучший ход» (T = 0) **детерминирован**: повтор того же дебюта даёт ту же партию. Выигрыш можно воспроизвести, и это искажает впечатление. Для проверки лучше T = 0,5 (почти та же сила, ходы разнообразнее), если её можно выставить. Иначе сын должен сам менять дебюты. + +**Предложение: честная проверка** (без нашего участия): +1. Модель 79M, максимум ползунка. Записать, какая температура реально выставлена (`play.rs`). +2. Контроль **5+3 для сына** (как блиц Lichess, где у него 2323). Цвета поочерёдно, дебюты разные, играть всерьёз, ходы не переигрывать. +3. **Не меньше 20 партий**, все PGN сохранить. При 20 партиях погрешность ≈ ±70 Эло (1 с.о.). Из 3–5 партий выводов не делать. +4. Перформанс = 2323 − dp(доля очков). Если сын набирает ~65 %, Maia ≈ 2210. Если больше 85 %, Maia < 2025: тогда наши поправки (а)–(в) неверны, и верна исходная цифра 2126 или ниже. +5. Отдельно отметить, *как* он выигрывает: тактические зевки Maia или позиционное переигрывание. Это проверка довода (д). + +**Вывод для подписи в программе (Предложение).** Не обещать «2600». На максимуме честно писать «≈ 2200 Lichess-блиц, I разряд — уровень КМС на грани». Это обоснованно и совпадает с внешним замером на людях. Поднять силу выше ~2300 при сохранении «человечности» можно только перебором (как у Allie: +270 к Allie-Greedy). Это отдельное решение, не v1.