Android: moves on the board (tap-tap, drag, legal dots, queen), variations, move sheet, undo
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

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 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-26 00:39:08 +03:00
parent d9f37f1283
commit 08aac5d83b
13 changed files with 416 additions and 31 deletions

View file

@ -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<String>,
val onMove: (String) -> Unit,
val promotion: (String) -> Char? = { null },
) {
/// The squares a piece on `from` can go to.
fun targets(from: String): Set<String> = 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<BoardMark> = 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<Int?>(null) }
var dragAt by remember(fen) { mutableStateOf<Offset?>(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))
}
}
}
}

View file

@ -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<GameData?>(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<GameSession?>(null) }
// What reading the game noticed: kept when the game is changed.
var notes by remember { mutableStateOf<List<String>>(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<Int?>(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)
}
}

View file

@ -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<Int, MoveJudgement> = 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<TextLayoutResult?>(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<Int, MoveJudgement>,
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

View file

@ -38,7 +38,6 @@
<string name="move_forward">Zug vor</string>
<string name="to_end">Zum Ende der Variante</string>
<string name="next_moves">Weiter:</string>
<string name="board_hint">Dies ist ein Partiebetrachter. Blättern Sie mit ◀ ▶ unten durch die Züge.</string>
<string name="board_description">Brett, Stellung nach %1$s</string>
<string name="board_start">Brett, Ausgangsstellung</string>
<string name="white_won">Weiß hat gewonnen</string>
@ -389,4 +388,9 @@
<string name="s_about_ready">Version %1$s ist heruntergeladen</string>
<string name="upd_card_downloading">Update auf %1$s, %2$d von %3$d Megabyte heruntergeladen</string>
<string name="upd_short_release">Datei lässt sich nicht prüfen</string>
<string name="undo_action">Rückgängig</string>
<string name="moves_deleted">Züge gelöscht</string>
<string name="make_main">Zur Hauptvariante machen</string>
<string name="delete_move">Zug und Fortsetzung löschen</string>
<string name="move_actions">Aktionen zum Zug</string>
</resources>

View file

@ -39,7 +39,6 @@
<string name="move_forward">Jugada adelante</string>
<string name="to_end">Al final de la línea</string>
<string name="next_moves">Siguiente:</string>
<string name="board_hint">Es un visor de partidas. Recorre las jugadas con ◀ ▶ abajo.</string>
<string name="board_description">Tablero, posición tras %1$s</string>
<string name="board_start">Tablero, posición inicial</string>
<string name="white_won">Ganaron las blancas</string>
@ -395,4 +394,9 @@
<string name="s_about_ready">La versión %1$s está descargada</string>
<string name="upd_card_downloading">Actualización a %1$s, %2$d de %3$d megabytes descargados</string>
<string name="upd_short_release">No se puede comprobar el archivo</string>
<string name="undo_action">Deshacer</string>
<string name="moves_deleted">Jugadas eliminadas</string>
<string name="make_main">Convertir en línea principal</string>
<string name="delete_move">Eliminar la jugada y lo que sigue</string>
<string name="move_actions">Acciones de la jugada</string>
</resources>

View file

@ -39,7 +39,6 @@
<string name="move_forward">Coup suivant</string>
<string name="to_end">À la fin de la ligne</string>
<string name="next_moves">Suite :</string>
<string name="board_hint">Ceci est une visionneuse de parties. Parcourez les coups avec ◀ ▶ en bas.</string>
<string name="board_description">Échiquier, position après %1$s</string>
<string name="board_start">Échiquier, position initiale</string>
<string name="white_won">Les Blancs ont gagné</string>
@ -395,4 +394,9 @@
<string name="s_about_ready">La version %1$s est téléchargée</string>
<string name="upd_card_downloading">Mise à jour vers %1$s, %2$d sur %3$d mégaoctets téléchargés</string>
<string name="upd_short_release">Fichier impossible à vérifier</string>
<string name="undo_action">Annuler</string>
<string name="moves_deleted">Coups supprimés</string>
<string name="make_main">En faire la ligne principale</string>
<string name="delete_move">Supprimer le coup et la suite</string>
<string name="move_actions">Actions sur le coup</string>
</resources>

View file

@ -39,7 +39,6 @@
<string name="move_forward">Mossa avanti</string>
<string name="to_end">Alla fine della linea</string>
<string name="next_moves">Seguito:</string>
<string name="board_hint">Questo è un visualizzatore di partite. Scorri le mosse con ◀ ▶ in basso.</string>
<string name="board_description">Scacchiera, posizione dopo %1$s</string>
<string name="board_start">Scacchiera, posizione iniziale</string>
<string name="white_won">Hanno vinto i bianchi</string>
@ -395,4 +394,9 @@
<string name="s_about_ready">La versione %1$s è scaricata</string>
<string name="upd_card_downloading">Aggiornamento a %1$s, %2$d di %3$d megabyte scaricati</string>
<string name="upd_short_release">File non verificabile</string>
<string name="undo_action">Annulla</string>
<string name="moves_deleted">Mosse eliminate</string>
<string name="make_main">Rendi linea principale</string>
<string name="delete_move">Elimina la mossa e il seguito</string>
<string name="move_actions">Azioni sulla mossa</string>
</resources>

View file

@ -38,7 +38,6 @@
<string name="move_forward">Бір жүріс алға</string>
<string name="to_end">Варианттың соңына</string>
<string name="next_moves">Келесі:</string>
<string name="board_hint">Бұл партияларды қарау құралы. Жүрістерді төмендегі ◀ ▶ арқылы ауыстырыңыз.</string>
<string name="board_description">Тақта, %1$s кейінгі позиция</string>
<string name="board_start">Тақта, бастапқы позиция</string>
<string name="white_won">Ақтар жеңді</string>
@ -390,4 +389,9 @@
<string name="upd_card_downloading">%1$s нұсқасына жаңарту, %3$d мегабайттың %2$d жүктелді</string>
<!-- Shown only when the interface is not in English. -->
<string name="upd_short_release">Файлды тексеру мүмкін емес</string>
<string name="undo_action">Қайтару</string>
<string name="moves_deleted">Жүрістер жойылды</string>
<string name="make_main">Негізгі ету</string>
<string name="delete_move">Жүрісті және жалғасын жою</string>
<string name="move_actions">Жүріспен әрекеттер</string>
</resources>

View file

@ -39,7 +39,6 @@
<string name="move_forward">Avançar um lance</string>
<string name="to_end">Ao fim da linha</string>
<string name="next_moves">Próximo:</string>
<string name="board_hint">Este é um visualizador de partidas. Percorra os lances com ◀ ▶ abaixo.</string>
<string name="board_description">Tabuleiro, posição após %1$s</string>
<string name="board_start">Tabuleiro, posição inicial</string>
<string name="white_won">Brancas venceram</string>
@ -396,4 +395,9 @@
<string name="upd_card_downloading">Atualização para %1$s, %2$d de %3$d megabytes baixados</string>
<!-- Shown only when the interface is not in English. -->
<string name="upd_short_release">O arquivo não pode ser verificado</string>
<string name="undo_action">Desfazer</string>
<string name="moves_deleted">Lances excluídos</string>
<string name="make_main">Tornar linha principal</string>
<string name="delete_move">Excluir o lance e a continuação</string>
<string name="move_actions">Ações do lance</string>
</resources>

View file

@ -40,7 +40,6 @@
<string name="move_forward">Ход вперёд</string>
<string name="to_end">В конец линии</string>
<string name="next_moves">Дальше:</string>
<string name="board_hint">Это просмотр партии. Ходы листаются кнопками ◀ ▶ внизу.</string>
<string name="board_description">Доска, позиция после %1$s</string>
<string name="board_start">Доска, начальная позиция</string>
<string name="white_won">Победили белые</string>
@ -401,4 +400,9 @@
<string name="s_about_ready">Версия %1$s скачана</string>
<string name="upd_card_downloading">Обновление до %1$s, скачано %2$d из %3$d мегабайт</string>
<string name="upd_short_release">Файл нельзя проверить</string>
<string name="undo_action">Вернуть</string>
<string name="moves_deleted">Ходы удалены</string>
<string name="make_main">Сделать основным</string>
<string name="delete_move">Удалить ход и продолжение</string>
<string name="move_actions">Действия с ходом</string>
</resources>

View file

@ -39,7 +39,6 @@
<string name="move_forward">Bir yurish oldinga</string>
<string name="to_end">Liniya oxiriga</string>
<string name="next_moves">Keyin:</string>
<string name="board_hint">Bu partiyalarni koʻrish vositasi. Yurishlarni pastdagi ◀ ▶ bilan oʻtkazing.</string>
<string name="board_description">Taxta, %1$sdan keyingi pozitsiya</string>
<string name="board_start">Taxta, boshlangʻich pozitsiya</string>
<string name="white_won">Oqlar yutdi</string>
@ -388,4 +387,9 @@
<string name="s_about_ready">%1$s versiyasi yuklab olindi</string>
<string name="upd_card_downloading">%1$sga yangilash, %3$d megabaytdan %2$d tasi yuklab olindi</string>
<string name="upd_short_release">Faylni tekshirib boʻlmaydi</string>
<string name="undo_action">Qaytarish</string>
<string name="moves_deleted">Yurishlar o‘chirildi</string>
<string name="make_main">Asosiy qilish</string>
<string name="delete_move">Yurish va davomini o‘chirish</string>
<string name="move_actions">Yurish amallari</string>
</resources>

View file

@ -39,7 +39,6 @@
<string name="move_forward">Move forward</string>
<string name="to_end">To the end of the line</string>
<string name="next_moves">Next:</string>
<string name="board_hint">This is a game viewer. Step through the moves with ◀ ▶ below.</string>
<string name="board_description">Board, position after %1$s</string>
<string name="board_start">Board, starting position</string>
<string name="white_won">White won</string>
@ -393,4 +392,9 @@
<string name="upd_card_downloading">Update to %1$s, %2$d of %3$d megabytes downloaded</string>
<!-- Shown only when the interface is not in English. -->
<string name="upd_short_release">The file cannot be checked</string>
<string name="undo_action">Undo</string>
<string name="moves_deleted">Moves deleted</string>
<string name="make_main">Make it the main line</string>
<string name="delete_move">Delete the move and what follows</string>
<string name="move_actions">Move actions</string>
</resources>

View file

@ -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.