android: prepare against a player from the database
This commit is contained in:
parent
a0051859db
commit
1e1684f808
38 changed files with 4922 additions and 46 deletions
|
|
@ -45,12 +45,19 @@ import io.github.vrubelroman.chesspenguin.ui.NEW_GAME
|
|||
import io.github.vrubelroman.chesspenguin.ui.PLAY_GAME
|
||||
import io.github.vrubelroman.chesspenguin.ui.GamesScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.OnlineScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.PlayersScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepStart
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable data object Databases : NavKey
|
||||
|
||||
@Serializable data class Games(val db: String) : NavKey
|
||||
|
||||
@Serializable data class Players(val db: String) : NavKey
|
||||
|
||||
@Serializable data class Preparation(val request: PrepStart) : NavKey
|
||||
|
||||
/// The game at `place` on the list of games found by `query` in the database (kept, so
|
||||
/// the same game comes back after Android restarts the app).
|
||||
@Serializable data class GameAt(val db: String, val place: Int, val query: String = "") : NavKey
|
||||
|
|
@ -188,10 +195,35 @@ fun MainNavigation() {
|
|||
}, onOpenDatabase = { id -> backStack.add(Games(id)) })
|
||||
}
|
||||
entry<Games> { key ->
|
||||
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) })
|
||||
GamesScreen(
|
||||
key.db,
|
||||
onBack = { backStack.removeLastOrNull() },
|
||||
onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) },
|
||||
onPlayers = { backStack.add(Players(key.db)) },
|
||||
)
|
||||
}
|
||||
entry<Players> { key ->
|
||||
PlayersScreen(
|
||||
key.db,
|
||||
onBack = { backStack.removeLastOrNull() },
|
||||
onPrepare = { player, white ->
|
||||
backStack.add(Preparation(PrepStart(db = key.db, player = player.name, white = white)))
|
||||
},
|
||||
)
|
||||
}
|
||||
entry<Preparation> { key ->
|
||||
PrepScreen(key.request, onBack = { backStack.removeLastOrNull() })
|
||||
}
|
||||
entry<GameAt> { key ->
|
||||
GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) })
|
||||
GameScreen(
|
||||
key.db,
|
||||
key.place,
|
||||
key.query,
|
||||
onBack = { backStack.removeLastOrNull() },
|
||||
onSettings = { backStack.add(SettingsKey) },
|
||||
onPlayGame = { backStack.add(PlayKey) },
|
||||
onPrepare = { backStack.add(Preparation(it)) },
|
||||
)
|
||||
}
|
||||
entry<SettingsKey> {
|
||||
SettingsScreen(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,129 @@
|
|||
package io.github.vrubelroman.chesspenguin.data
|
||||
|
||||
import io.github.vrubelroman.chesspenguin.ui.PlayerPage
|
||||
import io.github.vrubelroman.chesspenguin.ui.PlayerSummary
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepContinuation
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepGameMatch
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepOutOfMemory
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepPlayerNotFound
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepPosition
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepSearchFailed
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepStart
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlin.coroutines.coroutineContext
|
||||
import uniffi.mobile_api.Database
|
||||
import uniffi.mobile_api.PrepPhase
|
||||
import uniffi.mobile_api.PrepResult
|
||||
import uniffi.mobile_api.PrepSearch as RustPrepSearch
|
||||
|
||||
internal data class PrepQuery(
|
||||
val player: String,
|
||||
val white: Boolean,
|
||||
val fen: String,
|
||||
)
|
||||
|
||||
internal fun PrepStart.query(fen: String): PrepQuery = PrepQuery(player, white, fen)
|
||||
|
||||
/// The Android side of mobile-api's preparation contract. Database aggregation stays in
|
||||
/// Rust; the object being closed is the search, never the library's shared Database.
|
||||
internal interface PrepBackend {
|
||||
suspend fun players(query: String, offset: Int, limit: Int): PlayerPage
|
||||
suspend fun position(query: PrepQuery): PrepPosition
|
||||
fun cancel()
|
||||
fun close()
|
||||
}
|
||||
|
||||
internal object PrepBackends {
|
||||
fun open(database: Database): PrepBackend = RustPrepBackend(database)
|
||||
}
|
||||
|
||||
private class RustPrepBackend(private val database: Database) : PrepBackend {
|
||||
private val lock = Any()
|
||||
private val playerIds = java.util.concurrent.ConcurrentHashMap<String, UInt>()
|
||||
private var active: RustPrepSearch? = null
|
||||
@Volatile private var closed = false
|
||||
|
||||
override suspend fun players(query: String, offset: Int, limit: Int): PlayerPage {
|
||||
coroutineContext.ensureActive()
|
||||
if (closed) throw CancellationException("The player list is closed")
|
||||
val start = offset.coerceAtLeast(0)
|
||||
val answer = database.suggestPlayers(query, start.toUInt(), limit.coerceIn(0, 200).toUInt())
|
||||
val players = answer.players.map {
|
||||
PlayerSummary(it.id.toInt(), it.name, it.games.toInt(), it.whiteGames.toInt(), it.blackGames.toInt())
|
||||
}
|
||||
val end = start + players.size
|
||||
return PlayerPage(players, answer.total.toInt(), end.takeIf { players.isNotEmpty() && it < answer.total.toInt() })
|
||||
}
|
||||
|
||||
override suspend fun position(query: PrepQuery): PrepPosition {
|
||||
coroutineContext.ensureActive()
|
||||
val id = findPlayer(query.player)
|
||||
coroutineContext.ensureActive()
|
||||
val search = synchronized(lock) {
|
||||
if (closed) throw CancellationException("The position search is closed")
|
||||
active?.cancel()
|
||||
database.preparePosition(id, query.white, query.fen).also { active = it }
|
||||
}
|
||||
try {
|
||||
while (true) {
|
||||
val state = search.state()
|
||||
when (state.phase) {
|
||||
PrepPhase.GAMES, PrepPhase.INDEX, PrepPhase.SEARCH -> delay(25)
|
||||
PrepPhase.READY -> return state.result?.toUi()
|
||||
?: throw PrepSearchFailed(state.failure.ifEmpty { "The position search returned no result" })
|
||||
PrepPhase.CANCELLED -> throw CancellationException("The position search was cancelled")
|
||||
PrepPhase.NO_MEMORY -> throw PrepOutOfMemory()
|
||||
PrepPhase.FAILED -> throw PrepSearchFailed(state.failure.ifEmpty { "The position search failed" })
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
synchronized(lock) {
|
||||
if (active === search) active = null
|
||||
}
|
||||
search.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun findPlayer(name: String): UInt {
|
||||
playerIds[name]?.let { return it }
|
||||
var offset = 0
|
||||
while (true) {
|
||||
val page = database.suggestPlayers(name, offset.toUInt(), 200u)
|
||||
page.players.firstOrNull { it.name == name }?.let {
|
||||
playerIds[name] = it.id
|
||||
return it.id
|
||||
}
|
||||
if (page.players.isEmpty()) break
|
||||
offset += page.players.size
|
||||
if (offset >= page.total.toInt()) break
|
||||
}
|
||||
throw PrepPlayerNotFound(name)
|
||||
}
|
||||
|
||||
override fun cancel() {
|
||||
synchronized(lock) { active?.cancel() }
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
synchronized(lock) {
|
||||
closed = true
|
||||
active?.cancel()
|
||||
active = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun PrepResult.toUi() = PrepPosition(
|
||||
games = games.toInt(),
|
||||
continuations = continuations.map {
|
||||
PrepContinuation(it.uci, it.san, it.count.toInt(), it.wins.toInt(), it.draws.toInt(), it.losses.toInt(), it.unknown.toInt())
|
||||
},
|
||||
endedHere = ended.toInt(),
|
||||
noNormalContinuation = noNormalContinuation.toInt(),
|
||||
unknownResults = unknown.toInt(),
|
||||
playerToMove = playerToMove,
|
||||
matches = matches.map { PrepGameMatch(it.index, it.ply) },
|
||||
matchesTotal = matchesTotal.toInt(),
|
||||
)
|
||||
|
|
@ -36,7 +36,9 @@ import androidx.compose.ui.platform.LocalViewConfiguration
|
|||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.semantics.CustomAccessibilityAction
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.customActions
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.drawText
|
||||
|
|
@ -153,6 +155,15 @@ class BoardInput(
|
|||
/// 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)
|
||||
|
||||
/// A continuation attached to an arrow. Several UCI moves may share one direction
|
||||
/// (promotions); in that case the callback receives all of them for an explicit choice.
|
||||
data class BoardArrowMove(
|
||||
val uci: String,
|
||||
val from: String,
|
||||
val to: String,
|
||||
val actionLabel: String,
|
||||
)
|
||||
|
||||
/// A marked square of a comment (`[%csl]`), drawn as a ring.
|
||||
data class BoardMark(val square: String, val color: Color)
|
||||
|
||||
|
|
@ -172,6 +183,56 @@ fun markColor(letter: String): Color = when (letter) {
|
|||
/// The engine's arrows are blue, as on the desktop.
|
||||
val EngineArrow = Color(0, 48, 136, 160)
|
||||
|
||||
internal fun boardCell(index: Int, square: Float, flipped: Boolean): Offset {
|
||||
val row = index / 8
|
||||
val col = index % 8
|
||||
val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col
|
||||
return Offset(c * square, r * square)
|
||||
}
|
||||
|
||||
private data class ArrowGeometry(val start: Offset, val base: Offset, val tip: Offset)
|
||||
|
||||
private fun arrowGeometry(from: Offset, to: Offset, square: Float, weight: Float): ArrowGeometry? {
|
||||
val delta = to - from
|
||||
val length = delta.getDistance()
|
||||
if (length < 1f) return null
|
||||
val direction = delta / length
|
||||
val headLength = square * 0.42f * kotlin.math.sqrt(weight)
|
||||
val tip = to - direction * (square * 0.12f)
|
||||
return ArrowGeometry(from + direction * (square * 0.2f), tip - direction * headLength, tip)
|
||||
}
|
||||
|
||||
private fun distanceToSegment(point: Offset, start: Offset, end: Offset): Float {
|
||||
val segment = end - start
|
||||
val length2 = segment.x * segment.x + segment.y * segment.y
|
||||
if (length2 < 1f) return (point - start).getDistance()
|
||||
val t = (((point - start).x * segment.x + (point - start).y * segment.y) / length2).coerceIn(0f, 1f)
|
||||
return (point - (start + segment * t)).getDistance()
|
||||
}
|
||||
|
||||
/// Hit testing uses the same square transform and arrow endpoints as drawing. The head
|
||||
/// has at least a 48 dp target; shaft corridors stay narrower so neighbours do not all
|
||||
/// become one arbitrary shortcut.
|
||||
internal fun arrowHits(
|
||||
point: Offset,
|
||||
square: Float,
|
||||
flipped: Boolean,
|
||||
moves: List<BoardArrowMove>,
|
||||
headRadius: Float,
|
||||
): List<BoardArrowMove> {
|
||||
if (square <= 0f || point.x < 0 || point.y < 0 || point.x > square * 8 || point.y > square * 8) return emptyList()
|
||||
val corridor = maxOf(square * 0.16f, headRadius * 0.5f)
|
||||
return moves.filter { move ->
|
||||
val from = squareIndex(move.from) ?: return@filter false
|
||||
val to = squareIndex(move.to) ?: return@filter false
|
||||
val center = Offset(square / 2, square / 2)
|
||||
val geometry = arrowGeometry(boardCell(from, square, flipped) + center, boardCell(to, square, flipped) + center, square, 1f) ?: return@filter false
|
||||
(point - geometry.tip).getDistance() <= headRadius ||
|
||||
distanceToSegment(point, geometry.start, geometry.base) <= corridor ||
|
||||
distanceToSegment(point, geometry.base, geometry.tip) <= corridor
|
||||
}
|
||||
}
|
||||
|
||||
/// The board: full width, the chosen board and pieces, the last move lit, the
|
||||
/// 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);
|
||||
|
|
@ -188,6 +249,8 @@ fun Board(
|
|||
description: String,
|
||||
modifier: Modifier = Modifier,
|
||||
arrows: List<BoardArrow> = emptyList(),
|
||||
arrowMoves: List<BoardArrowMove> = emptyList(),
|
||||
onArrowMoves: (List<String>) -> Unit = {},
|
||||
marks: List<BoardMark> = emptyList(),
|
||||
check: Boolean = false,
|
||||
animated: Boolean = true,
|
||||
|
|
@ -232,6 +295,8 @@ fun Board(
|
|||
var dragAt by remember(fen) { mutableStateOf<Offset?>(null) }
|
||||
val slop = LocalViewConfiguration.current.touchSlop
|
||||
val currentInput = androidx.compose.runtime.rememberUpdatedState(input)
|
||||
val currentArrowMoves = androidx.compose.runtime.rememberUpdatedState(arrowMoves)
|
||||
val currentArrowAction = androidx.compose.runtime.rememberUpdatedState(onArrowMoves)
|
||||
val lift = with(density) { 22.dp.toPx() }
|
||||
fun indexAt(p: Offset, sq: Float): Int? {
|
||||
val col = (p.x / sq).toInt()
|
||||
|
|
@ -248,7 +313,8 @@ fun Board(
|
|||
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.
|
||||
// A tap on a target of the piece chosen makes the move. An already chosen
|
||||
// piece always has priority over continuation arrows.
|
||||
if (was != null && start != was) {
|
||||
inp.move(squareName(was), startName)?.let { m ->
|
||||
selected = null
|
||||
|
|
@ -257,6 +323,7 @@ fun Board(
|
|||
}
|
||||
}
|
||||
if (movable) selected = start
|
||||
val shortcutCandidate = was == null && !movable
|
||||
var dragging = false
|
||||
while (true) {
|
||||
val e = awaitPointerEvent()
|
||||
|
|
@ -271,17 +338,29 @@ fun Board(
|
|||
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
|
||||
} 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
|
||||
}
|
||||
if (shortcutCandidate) {
|
||||
val hits = arrowHits(
|
||||
c.position,
|
||||
sq,
|
||||
flipped,
|
||||
currentArrowMoves.value,
|
||||
with(density) { 24.dp.toPx() },
|
||||
)
|
||||
if (hits.isNotEmpty()) currentArrowAction.value(hits.map { it.uci }.distinct())
|
||||
}
|
||||
}
|
||||
c.consume()
|
||||
break
|
||||
}
|
||||
if (movable && !dragging && (c.position - down.position).getDistance() > slop) dragging = true
|
||||
if (!dragging && (c.position - down.position).getDistance() > slop) dragging = true
|
||||
if (dragging) {
|
||||
dragAt = c.position
|
||||
if (movable) dragAt = c.position
|
||||
c.consume()
|
||||
}
|
||||
}
|
||||
|
|
@ -292,16 +371,21 @@ fun Board(
|
|||
.aspectRatio(1f)
|
||||
.onSizeChanged { side = it.width }
|
||||
.then(touch)
|
||||
.semantics { contentDescription = description },
|
||||
.semantics {
|
||||
contentDescription = description
|
||||
if (arrowMoves.isNotEmpty()) {
|
||||
customActions = arrowMoves.map { move ->
|
||||
CustomAccessibilityAction(move.actionLabel) {
|
||||
onArrowMoves(listOf(move.uci))
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
val sq = size.width / 8f
|
||||
val px = sq.toInt()
|
||||
fun cell(i: Int): Offset {
|
||||
val row = i / 8
|
||||
val col = i % 8
|
||||
val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col
|
||||
return Offset(c * sq, r * sq)
|
||||
}
|
||||
fun cell(i: Int): Offset = boardCell(i, sq, flipped)
|
||||
val image = texture
|
||||
if (image != null) {
|
||||
// The squares of the image are the same seen from either side: it is not turned.
|
||||
|
|
@ -430,22 +514,17 @@ fun Board(
|
|||
/// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops
|
||||
/// short of the square's center.
|
||||
private fun DrawScope.drawArrow(from: Offset, to: Offset, sq: Float, a: BoardArrow) {
|
||||
val geometry = arrowGeometry(from, to, sq, a.weight) ?: return
|
||||
val d = to - from
|
||||
val len = d.getDistance()
|
||||
if (len < 1f) return
|
||||
val dir = d / len
|
||||
val dir = d / d.getDistance()
|
||||
val width = sq * 0.16f * a.weight
|
||||
val headLen = sq * 0.42f * kotlin.math.sqrt(a.weight)
|
||||
val headW = sq * 0.38f * kotlin.math.sqrt(a.weight)
|
||||
val tip = to - dir * (sq * 0.12f)
|
||||
val base = tip - dir * headLen
|
||||
val start = from + dir * (sq * 0.2f)
|
||||
val normal = Offset(-dir.y, dir.x)
|
||||
drawLine(a.color, start, base, strokeWidth = width)
|
||||
drawLine(a.color, geometry.start, geometry.base, strokeWidth = width)
|
||||
val head = Path().apply {
|
||||
moveTo(tip.x, tip.y)
|
||||
lineTo(base.x + normal.x * headW, base.y + normal.y * headW)
|
||||
lineTo(base.x - normal.x * headW, base.y - normal.y * headW)
|
||||
moveTo(geometry.tip.x, geometry.tip.y)
|
||||
lineTo(geometry.base.x + normal.x * headW, geometry.base.y + normal.y * headW)
|
||||
lineTo(geometry.base.x - normal.x * headW, geometry.base.y - normal.y * headW)
|
||||
close()
|
||||
}
|
||||
drawPath(head, a.color)
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.Box
|
|||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
|
|
@ -150,6 +151,7 @@ fun GameScreen(
|
|||
onSettings: () -> Unit,
|
||||
onPlayGame: () -> Unit = {},
|
||||
onOpenDatabase: (String) -> Unit = {},
|
||||
onPrepare: (PrepStart) -> Unit = {},
|
||||
) {
|
||||
val app = app()
|
||||
val context = LocalContext.current
|
||||
|
|
@ -298,6 +300,7 @@ fun GameScreen(
|
|||
val reviewCycle = remember(place) { HashMap<Pair<Boolean, MoveJudgement>, Int>() }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var info by remember { mutableStateOf(false) }
|
||||
var prepSheet by remember(place) { mutableStateOf(false) }
|
||||
@Suppress("DEPRECATION")
|
||||
val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current
|
||||
val pgnCopied = stringResource(R.string.pgn_copied)
|
||||
|
|
@ -334,6 +337,9 @@ fun GameScreen(
|
|||
// The player bars above and below the board (§7.11); the top bar names the event.
|
||||
val whiteName = tag("White").trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
val blackName = tag("Black").trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
val prepPathAvailable = g?.let { data ->
|
||||
prepStartFromGame(data, current, db, whiteName ?: blackName.orEmpty(), whiteName != null) != null
|
||||
} == true
|
||||
val whiteLabel = stringResource(R.string.tag_white)
|
||||
val blackLabel = stringResource(R.string.tag_black)
|
||||
val resultText = g?.let { resultLine(context, it.result) } ?: ""
|
||||
|
|
@ -1247,6 +1253,28 @@ fun GameScreen(
|
|||
menu = false
|
||||
info = true
|
||||
})
|
||||
if (!newGame && !playGame && (whiteName != null || blackName != null)) {
|
||||
val reason = when {
|
||||
preview != null -> stringResource(R.string.prep_close_engine_line)
|
||||
!prepPathAvailable -> stringResource(R.string.prep_null_move_unavailable)
|
||||
else -> null
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Column {
|
||||
Text(stringResource(R.string.prep_opponent))
|
||||
if (reason != null) {
|
||||
Text(reason, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = reason == null,
|
||||
onClick = {
|
||||
menu = false
|
||||
prepSheet = true
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.copy_pgn)) }, enabled = g != null, onClick = {
|
||||
menu = false
|
||||
scope.launch {
|
||||
|
|
@ -1335,6 +1363,42 @@ fun GameScreen(
|
|||
}
|
||||
}
|
||||
}
|
||||
if (prepSheet && g != null) {
|
||||
androidx.compose.material3.ModalBottomSheet(onDismissRequest = { prepSheet = false }) {
|
||||
Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.prep_title),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
)
|
||||
listOfNotNull(
|
||||
whiteName?.let { true to it },
|
||||
blackName?.let { false to it },
|
||||
).forEach { (white, name) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 64.dp).clickable {
|
||||
prepStartFromGame(g, current, db, name, white)?.let {
|
||||
prepSheet = false
|
||||
onPrepare(it)
|
||||
}
|
||||
}.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SideDisc(white)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column {
|
||||
PlayerName(name, MaterialTheme.typography.bodyLarge)
|
||||
Text(
|
||||
stringResource(if (white) R.string.prep_as_white else R.string.prep_as_black),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (info && g != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { info = false },
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ import androidx.compose.material3.SnackbarHostState
|
|||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material.icons.rounded.Download
|
||||
import androidx.compose.material.icons.rounded.Groups
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
|
|
@ -86,7 +87,12 @@ private const val CHUNK = 100
|
|||
/// The games of a database, with a search (android-ui.md §6).
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: String) -> Unit) {
|
||||
fun GamesScreen(
|
||||
db: String,
|
||||
onBack: () -> Unit,
|
||||
onGame: (place: Int, query: String) -> Unit,
|
||||
onPlayers: () -> Unit = {},
|
||||
) {
|
||||
val app = app()
|
||||
val entries by app.library.entries.collectAsState()
|
||||
val entry = entries.firstOrNull { it.id == db }
|
||||
|
|
@ -196,6 +202,7 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
|
|||
if (query.isEmpty()) searching = false else query = ""
|
||||
}) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) }
|
||||
} else if (database != null) {
|
||||
IconButton(onClick = onPlayers) { Icon(Icons.Rounded.Groups, stringResource(R.string.players)) }
|
||||
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
|
||||
// A downloaded database: its new games from here, where they are
|
||||
// looked for (android-ui.md §23.3); ✕ while they come.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,444 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
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.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.disabled
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import io.github.vrubelroman.chesspenguin.R
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepBackends
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.mobile_api.Database
|
||||
import java.text.Collator
|
||||
import java.util.Locale
|
||||
|
||||
private const val PLAYER_PAGE = 100
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlayersScreen(
|
||||
db: String,
|
||||
onBack: () -> Unit,
|
||||
onPrepare: (player: PlayerSummary, white: Boolean) -> Unit,
|
||||
) {
|
||||
val app = app()
|
||||
val entries by app.library.entries.collectAsState()
|
||||
val entry = entries.firstOrNull { it.id == db }
|
||||
var database by remember { mutableStateOf<Database?>(null) }
|
||||
var openFailure by remember { mutableStateOf<Throwable?>(null) }
|
||||
val backend = remember(database) { database?.let(PrepBackends::open) }
|
||||
DisposableEffect(backend) { onDispose { backend?.close() } }
|
||||
|
||||
var searching by rememberSaveable { mutableStateOf(false) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var colorChoice by remember { mutableStateOf<PlayerSummary?>(null) }
|
||||
var players by remember { mutableStateOf<List<PlayerSummary>?>(null) }
|
||||
var nextOffset by remember { mutableStateOf<Int?>(null) }
|
||||
var failure by remember { mutableStateOf<Throwable?>(null) }
|
||||
var loadingMore by remember { mutableStateOf(false) }
|
||||
var generation by remember { mutableIntStateOf(0) }
|
||||
var retry by rememberSaveable { mutableIntStateOf(0) }
|
||||
LaunchedEffect(db, entry?.games, entry?.updated, retry) {
|
||||
database = null
|
||||
openFailure = null
|
||||
app.library.database(db).onSuccess { database = it }.onFailure { openFailure = it }
|
||||
}
|
||||
val list = rememberLazyListState()
|
||||
val focus = remember { FocusRequester() }
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
BackHandler(searching) {
|
||||
searching = false
|
||||
query = ""
|
||||
}
|
||||
|
||||
LaunchedEffect(backend, query, retry) {
|
||||
val source = backend ?: return@LaunchedEffect
|
||||
val expected = ++generation
|
||||
players = null
|
||||
nextOffset = null
|
||||
failure = null
|
||||
loadingMore = false
|
||||
if (query.isNotEmpty()) delay(250)
|
||||
try {
|
||||
val page = withContext(Dispatchers.IO) { source.players(query, 0, PLAYER_PAGE) }
|
||||
if (expected != generation) return@LaunchedEffect
|
||||
players = sortPlayers(page.players)
|
||||
nextOffset = page.nextOffset
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
if (expected == generation) failure = e
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) }
|
||||
},
|
||||
title = {
|
||||
if (searching) {
|
||||
TextField(
|
||||
value = query,
|
||||
onValueChange = { query = it },
|
||||
placeholder = { Text(stringResource(R.string.player_name_hint)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = Color.Transparent,
|
||||
unfocusedContainerColor = Color.Transparent,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth().focusRequester(focus),
|
||||
)
|
||||
LaunchedEffect(Unit) { focus.requestFocus() }
|
||||
} else {
|
||||
Column {
|
||||
Text(stringResource(R.string.players), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
entry?.let { displayName(it) } ?: "",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (searching) {
|
||||
IconButton(onClick = { if (query.isEmpty()) searching = false else query = "" }) {
|
||||
Icon(Icons.Rounded.Close, stringResource(R.string.clear))
|
||||
}
|
||||
} else if (database != null) {
|
||||
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.fillMaxSize().padding(padding)) {
|
||||
val shownPlayers = players
|
||||
when {
|
||||
openFailure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(openFailure!!)) {
|
||||
TextButton(onClick = { database = null; openFailure = null; retry += 1 }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
failure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(failure!!).ifEmpty { failure!!.message ?: "" }) {
|
||||
TextButton(onClick = { retry += 1 }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
shownPlayers == null -> LoadingPlayers()
|
||||
shownPlayers.isEmpty() && query.isEmpty() -> PrepMessage(stringResource(R.string.no_named_players), "") {
|
||||
TextButton(onClick = onBack) { Text(stringResource(R.string.to_games)) }
|
||||
}
|
||||
shownPlayers.isEmpty() -> PrepMessage(stringResource(R.string.player_not_found), "") {
|
||||
TextButton(onClick = { query = "" }) { Text(stringResource(R.string.reset_search)) }
|
||||
}
|
||||
else -> LazyColumn(Modifier.fillMaxSize(), state = list) {
|
||||
val shown = shownPlayers
|
||||
val expectedGeneration = generation
|
||||
items(shown.size, key = { shown[it].id }) { index ->
|
||||
val player = shown[index]
|
||||
PlayerPrepRow(
|
||||
player = player,
|
||||
divider = index < shown.lastIndex || nextOffset != null,
|
||||
onPlayerClick = { chosen ->
|
||||
keyboard?.hide()
|
||||
val onlyColor = solePlayerColor(chosen)
|
||||
when {
|
||||
playerNeedsColorChoice(chosen) -> colorChoice = chosen
|
||||
onlyColor != null -> onPrepare(chosen, onlyColor)
|
||||
}
|
||||
},
|
||||
)
|
||||
if (index == shown.lastIndex && nextOffset != null) {
|
||||
LaunchedEffect(nextOffset, generation) {
|
||||
val source = backend ?: return@LaunchedEffect
|
||||
val offset = nextOffset ?: return@LaunchedEffect
|
||||
loadingMore = true
|
||||
try {
|
||||
val page = withContext(Dispatchers.IO) { source.players(query, offset, PLAYER_PAGE) }
|
||||
if (expectedGeneration == generation) {
|
||||
players = sortPlayers((shown + page.players).distinctBy { it.id })
|
||||
nextOffset = page.nextOffset
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
if (expectedGeneration == generation) failure = e
|
||||
} finally {
|
||||
if (expectedGeneration == generation) loadingMore = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (loadingMore) {
|
||||
items(3, key = { "loading-$it" }) { PlayerPrepPlaceholder() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
colorChoice?.let { player ->
|
||||
PlayerColorSheet(
|
||||
player = player,
|
||||
onDismiss = { colorChoice = null },
|
||||
onPrepare = { chosen, white ->
|
||||
colorChoice = null
|
||||
onPrepare(chosen, white)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sortPlayers(players: List<PlayerSummary>): List<PlayerSummary> {
|
||||
val collator = Collator.getInstance(Locale.getDefault()).apply { strength = Collator.PRIMARY }
|
||||
return players.sortedWith(compareBy(collator) { it.name })
|
||||
}
|
||||
|
||||
internal fun playerNeedsColorChoice(player: PlayerSummary): Boolean = player.whiteGames > 0 && player.blackGames > 0
|
||||
|
||||
internal fun solePlayerColor(player: PlayerSummary): Boolean? = when {
|
||||
player.whiteGames > 0 && player.blackGames == 0 -> true
|
||||
player.blackGames > 0 && player.whiteGames == 0 -> false
|
||||
else -> null
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun PlayerPrepRow(
|
||||
player: PlayerSummary,
|
||||
divider: Boolean = false,
|
||||
onPlayerClick: (PlayerSummary) -> Unit,
|
||||
) {
|
||||
val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total))
|
||||
val whiteSide = stringResource(R.string.prep_as_white)
|
||||
val blackSide = stringResource(R.string.prep_as_black)
|
||||
val chooseColor = stringResource(R.string.prep_choose_color)
|
||||
val prepare = stringResource(R.string.prepare_action)
|
||||
val onlyColor = solePlayerColor(player)
|
||||
val hasAction = playerNeedsColorChoice(player) || onlyColor != null
|
||||
val action = when {
|
||||
playerNeedsColorChoice(player) -> chooseColor
|
||||
onlyColor == true -> "$prepare $whiteSide"
|
||||
onlyColor == false -> "$prepare $blackSide"
|
||||
else -> prepare
|
||||
}
|
||||
val description = "${player.name}, $games. $whiteSide ${groupDigits(player.whiteGames)}, $blackSide ${groupDigits(player.blackGames)}. $action"
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val grows = maxWidth < 320.dp || LocalDensity.current.fontScale > 1f
|
||||
val height = if (grows) Modifier.heightIn(min = 72.dp) else Modifier.height(72.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth().then(height)
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = description
|
||||
role = Role.Button
|
||||
if (hasAction) onClick(action) { onPlayerClick(player); true } else disabled()
|
||||
}
|
||||
.clickable(enabled = hasAction, role = Role.Button, onClickLabel = action) { onPlayerClick(player) },
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PlayerName(player.name, MaterialTheme.typography.bodyLarge, Modifier.weight(1f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(games, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
FlowRow(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
PlayerColorText(true, whiteSide, player.whiteGames)
|
||||
PlayerColorText(false, blackSide, player.blackGames)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.AutoMirrored.Rounded.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
}
|
||||
if (divider) HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayerColorText(white: Boolean, side: String, count: Int) {
|
||||
Row(Modifier.heightIn(min = 20.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
SideDisc(white)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("$side · ${groupDigits(count)}", style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun PlayerColorSheet(player: PlayerSummary, onDismiss: () -> Unit, onPrepare: (PlayerSummary, Boolean) -> Unit) {
|
||||
val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total))
|
||||
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.prep_against_player, player.name),
|
||||
Modifier.fillMaxWidth(),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
games,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
PlayerColorAction(player, true, onPrepare)
|
||||
PlayerColorAction(player, false, onPrepare)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayerColorAction(player: PlayerSummary, white: Boolean, onPrepare: (PlayerSummary, Boolean) -> Unit) {
|
||||
val count = if (white) player.whiteGames else player.blackGames
|
||||
val side = stringResource(if (white) R.string.prep_against_white else R.string.prep_against_black)
|
||||
val games = pluralStringResource(R.plurals.games_count, count, groupDigits(count))
|
||||
val prepare = stringResource(R.string.prepare_action)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 64.dp)
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = "${player.name}, $side, $games. $prepare"
|
||||
role = Role.Button
|
||||
onClick(prepare) { onPrepare(player, white); true }
|
||||
}
|
||||
.clickable(role = Role.Button, onClickLabel = prepare) { onPrepare(player, white) }
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SideDisc(white)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(side, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(groupDigits(count), style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayerPrepPlaceholder() {
|
||||
Box(Modifier.fillMaxWidth().height(72.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Row(Modifier.fillMaxWidth().height(24.dp)) {
|
||||
Box(Modifier.weight(1f).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp)))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Box(Modifier.width(64.dp).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp)))
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth(0.65f).height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp)))
|
||||
}
|
||||
HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadingPlayers() {
|
||||
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(stringResource(R.string.reading_players), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PrepMessage(title: String, detail: String, action: (@Composable () -> Unit)? = null) {
|
||||
Column(Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text(title, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center)
|
||||
if (detail.isNotEmpty()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(detail, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center)
|
||||
}
|
||||
if (action != null) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
action()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepBackend
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepQuery
|
||||
import io.github.vrubelroman.chesspenguin.data.query
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.mobile_api.GameData
|
||||
import uniffi.mobile_api.GameSession
|
||||
|
||||
internal class PrepController(val request: PrepStart) : ViewModel() {
|
||||
var line by mutableStateOf(PrepLineState(request.startFen, request.startFen))
|
||||
private set
|
||||
var data by mutableStateOf<GameData?>(null)
|
||||
private set
|
||||
var position by mutableStateOf<PrepPosition?>(null)
|
||||
private set
|
||||
var failure by mutableStateOf<Throwable?>(null)
|
||||
private set
|
||||
var loading by mutableStateOf(false)
|
||||
private set
|
||||
var initialised by mutableStateOf(false)
|
||||
private set
|
||||
var moveFailed by mutableStateOf(false)
|
||||
var retry by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
private var session: GameSession? = null
|
||||
private var search: Job? = null
|
||||
private var generation = 0L
|
||||
|
||||
suspend fun initialise() {
|
||||
if (session != null) return
|
||||
failure = null
|
||||
val loaded = withContext(Dispatchers.Default) {
|
||||
runCatching {
|
||||
val fen = request.startFen
|
||||
val s = GameSession.fromPgn("[SetUp \"1\"]\n[FEN \"$fen\"]\n\n*")
|
||||
try {
|
||||
var edited = s.data() to 0
|
||||
for (uci in request.moves) {
|
||||
val next = s.play(edited.second.toUInt(), uci)
|
||||
edited = next.data to next.cursor.toInt()
|
||||
}
|
||||
Triple(s, edited.first, edited.second)
|
||||
} catch (e: Throwable) {
|
||||
s.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
if (session != null) {
|
||||
loaded.getOrNull()?.first?.close()
|
||||
return
|
||||
}
|
||||
val (s, game, cursor) = loaded.getOrElse {
|
||||
failure = it
|
||||
initialised = false
|
||||
return
|
||||
}
|
||||
session = s
|
||||
data = game
|
||||
line = prepLine(game, cursor, request.startFen)
|
||||
initialised = true
|
||||
}
|
||||
|
||||
private fun invalidate() {
|
||||
generation += 1
|
||||
search?.cancel()
|
||||
position = null
|
||||
failure = null
|
||||
loading = false
|
||||
}
|
||||
|
||||
fun back() {
|
||||
if (!line.canBack) return
|
||||
line = line.back()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun forward() {
|
||||
if (!line.canForward) return
|
||||
line = line.forward()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (!line.canBack) return
|
||||
line = line.start()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun end() {
|
||||
if (!line.canForward) return
|
||||
line = line.end()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun legalMoves(): List<String> = session?.legalMoves(line.currentNode.toUInt()).orEmpty()
|
||||
|
||||
fun play(uci: String): String? {
|
||||
val s = session ?: return null
|
||||
if (s.legalMoves(line.currentNode.toUInt()).none { it == uci }) return null
|
||||
val edited = runCatching { s.play(line.currentNode.toUInt(), uci) }.getOrElse {
|
||||
moveFailed = true
|
||||
return null
|
||||
}
|
||||
val visible = prepLine(edited.data, edited.cursor.toInt(), request.startFen)
|
||||
line = visible
|
||||
data = edited.data
|
||||
invalidate()
|
||||
return visible.last?.san
|
||||
}
|
||||
|
||||
fun repeat() {
|
||||
retry += 1
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun search(backend: PrepBackend) {
|
||||
if (!initialised || failure != null) return
|
||||
invalidate()
|
||||
backend.cancel()
|
||||
val query: PrepQuery = request.query(line.fen)
|
||||
val expected = generation
|
||||
search = viewModelScope.launch {
|
||||
val delayed = launch {
|
||||
delay(300)
|
||||
if (generation == expected) loading = true
|
||||
}
|
||||
try {
|
||||
val answer = withContext(Dispatchers.IO) { backend.position(query) }
|
||||
if (generation == expected && query == request.query(line.fen)) position = answer
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
if (generation == expected && query == request.query(line.fen)) failure = e
|
||||
} finally {
|
||||
delayed.cancel()
|
||||
if (generation == expected) loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
generation += 1
|
||||
search?.cancel()
|
||||
session?.close()
|
||||
session = null
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import uniffi.mobile_api.GameData
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal const val STANDARD_START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
|
||||
|
||||
/// The position and history of a preparation request. The game document is not part of it.
|
||||
@Serializable
|
||||
data class PrepStart(
|
||||
val db: String,
|
||||
val player: String,
|
||||
val white: Boolean,
|
||||
val startFen: String = STANDARD_START,
|
||||
val moves: List<String> = emptyList(),
|
||||
val fromGame: Boolean = false,
|
||||
)
|
||||
|
||||
/// One move of the temporary line. `node` belongs only to this preparation session.
|
||||
@Serializable
|
||||
data class PrepLineStep(
|
||||
val node: Int,
|
||||
val uci: String,
|
||||
val san: String,
|
||||
val moveNumber: Int,
|
||||
val white: Boolean,
|
||||
val fen: String,
|
||||
val from: String?,
|
||||
val to: String?,
|
||||
) {
|
||||
val label: String get() = "$moveNumber${if (white) "." else "…"}$san"
|
||||
}
|
||||
|
||||
/// A linear, read-only exploration. Going back never chooses a different continuation;
|
||||
/// making a move after going back drops only this temporary future.
|
||||
@Serializable
|
||||
data class PrepLineState(
|
||||
val startFen: String,
|
||||
val rootFen: String,
|
||||
val rootNode: Int = 0,
|
||||
val steps: List<PrepLineStep> = emptyList(),
|
||||
val cursor: Int = 0,
|
||||
) {
|
||||
init {
|
||||
require(cursor in 0..steps.size) { "line cursor is outside the line" }
|
||||
}
|
||||
|
||||
val fen: String get() = steps.getOrNull(cursor - 1)?.fen ?: rootFen
|
||||
val currentNode: Int get() = steps.getOrNull(cursor - 1)?.node ?: rootNode
|
||||
val last: PrepLineStep? get() = steps.getOrNull(cursor - 1)
|
||||
val moves: List<String> get() = steps.map { it.uci }
|
||||
val canBack: Boolean get() = cursor > 0
|
||||
val canForward: Boolean get() = cursor < steps.size
|
||||
|
||||
fun back(): PrepLineState = if (canBack) copy(cursor = cursor - 1) else this
|
||||
fun forward(): PrepLineState = if (canForward) copy(cursor = cursor + 1) else this
|
||||
fun start(): PrepLineState = if (canBack) copy(cursor = 0) else this
|
||||
fun end(): PrepLineState = if (canForward) copy(cursor = steps.size) else this
|
||||
|
||||
fun replaceVisibleLine(visible: List<PrepLineStep>, currentNode: Int): PrepLineState {
|
||||
val at = visible.indexOfLast { it.node == currentNode }
|
||||
require(at >= 0 && at + 1 == visible.size) { "the played move must end the visible line" }
|
||||
return copy(steps = visible, cursor = visible.size)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun prepLine(data: GameData, cursor: Int, startFen: String): PrepLineState {
|
||||
val path = ArrayList<Int>()
|
||||
var at: Int? = cursor
|
||||
while (at != null) {
|
||||
if (at !in data.nodes.indices || at in path) break
|
||||
path += at
|
||||
at = data.nodes[at].parent?.toInt()
|
||||
}
|
||||
path.reverse()
|
||||
val root = path.firstOrNull() ?: 0
|
||||
val steps = path.drop(1).mapNotNull { id ->
|
||||
val n = data.nodes[id]
|
||||
if (n.uci.isEmpty()) return@mapNotNull null
|
||||
PrepLineStep(id, n.uci, n.san, n.moveNumber.toInt(), n.white, n.fen, n.fromSquare, n.toSquare)
|
||||
}
|
||||
return PrepLineState(startFen, data.nodes.getOrNull(root)?.fen ?: startFen, root, steps, steps.size)
|
||||
}
|
||||
|
||||
/// A null move cannot be represented by the normal-move position search.
|
||||
internal fun prepStartFromGame(data: GameData, at: Int, db: String, player: String, white: Boolean): PrepStart? {
|
||||
if (at !in data.nodes.indices) return null
|
||||
val path = ArrayList<Int>()
|
||||
var node: Int? = at
|
||||
while (node != null) {
|
||||
if (node !in data.nodes.indices || node in path) return null
|
||||
path += node
|
||||
node = data.nodes[node].parent?.toInt()
|
||||
}
|
||||
path.reverse()
|
||||
if (path.any { data.nodes[it].nullMove }) return null
|
||||
val moves = path.drop(1).map { data.nodes[it].uci }
|
||||
if (moves.any { it.isEmpty() }) return null
|
||||
return PrepStart(
|
||||
db = db,
|
||||
player = player,
|
||||
white = white,
|
||||
startFen = data.nodes[path.first()].fen,
|
||||
moves = moves,
|
||||
fromGame = true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Preparation shows the user's side at the bottom, opposite to the selected opponent.
|
||||
internal fun prepBoardStartsFlipped(opponentWhite: Boolean): Boolean = opponentWhite
|
||||
|
||||
internal fun prepWhiteToMove(fen: String): Boolean? = fen.split(' ').getOrNull(1)?.let {
|
||||
when (it) {
|
||||
"w" -> true
|
||||
"b" -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
internal fun moveLabel(fen: String, san: String): String {
|
||||
val fields = fen.split(' ')
|
||||
val number = fields.getOrNull(5)?.toIntOrNull()?.coerceAtLeast(0) ?: 1
|
||||
val white = prepWhiteToMove(fen) ?: true
|
||||
return "$number${if (white) "." else "…"}$san"
|
||||
}
|
||||
|
||||
data class PlayerSummary(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val total: Int,
|
||||
val whiteGames: Int,
|
||||
val blackGames: Int,
|
||||
)
|
||||
|
||||
data class PlayerPage(
|
||||
val players: List<PlayerSummary>,
|
||||
val total: Int,
|
||||
val nextOffset: Int?,
|
||||
)
|
||||
|
||||
data class PrepContinuation(
|
||||
val uci: String,
|
||||
val san: String,
|
||||
val games: Int,
|
||||
val wins: Int,
|
||||
val draws: Int,
|
||||
val losses: Int,
|
||||
val unknown: Int = 0,
|
||||
) {
|
||||
val from: String? get() = uci.takeIf { it.length >= 4 }?.substring(0, 2)
|
||||
val to: String? get() = uci.takeIf { it.length >= 4 }?.substring(2, 4)
|
||||
}
|
||||
|
||||
/// A matching game is part of the result contract even though its list is outside this MVP.
|
||||
data class PrepGameMatch(val index: UInt, val ply: UInt)
|
||||
|
||||
data class PrepPosition(
|
||||
val games: Int,
|
||||
val continuations: List<PrepContinuation>,
|
||||
val endedHere: Int = 0,
|
||||
val noNormalContinuation: Int = 0,
|
||||
val unknownResults: Int = 0,
|
||||
val playerToMove: Boolean? = null,
|
||||
val matches: List<PrepGameMatch> = emptyList(),
|
||||
val matchesTotal: Int = 0,
|
||||
)
|
||||
|
||||
internal fun sortedContinuations(position: PrepPosition): List<PrepContinuation> =
|
||||
position.continuations.sortedWith(compareByDescending<PrepContinuation> { it.games }.thenBy { it.san })
|
||||
|
||||
internal fun frequencyPercent(games: Int, total: Int): String = when {
|
||||
games <= 0 || total <= 0 -> "0"
|
||||
games * 100L < total -> "<1"
|
||||
else -> (games * 100.0 / total).roundToInt().toString()
|
||||
}
|
||||
|
||||
internal fun outcomePercents(move: PrepContinuation): Triple<String, String, String> {
|
||||
val known = move.wins + move.draws + move.losses
|
||||
if (known <= 0) return Triple("—", "—", "—")
|
||||
fun percent(n: Int) = (n * 100.0 / known).roundToInt().toString()
|
||||
return Triple(percent(move.wins), percent(move.draws), percent(move.losses))
|
||||
}
|
||||
|
||||
internal class PrepOutOfMemory : IllegalStateException("Not enough memory for the position index")
|
||||
internal class PrepSearchFailed(message: String) : IllegalStateException(message)
|
||||
internal class PrepPlayerNotFound(name: String) : IllegalStateException("Player is not in this database: $name")
|
||||
|
|
@ -0,0 +1,469 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.only
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.rounded.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.SwapVert
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
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.ModalBottomSheet
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
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.DisposableEffect
|
||||
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.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import io.github.vrubelroman.chesspenguin.R
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepBackends
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import uniffi.mobile_api.Database
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PrepScreen(request: PrepStart, onBack: () -> Unit) {
|
||||
val app = app()
|
||||
val context = LocalContext.current
|
||||
val controller: PrepController = viewModel(key = "prep") { PrepController(request) }
|
||||
val entries by app.library.entries.collectAsState()
|
||||
val entry = entries.firstOrNull { it.id == request.db }
|
||||
var database by remember { mutableStateOf<Database?>(null) }
|
||||
var openFailure by remember { mutableStateOf<Throwable?>(null) }
|
||||
var openRetry by rememberSaveable { mutableIntStateOf(0) }
|
||||
LaunchedEffect(request.db, entry?.games, entry?.updated, openRetry) {
|
||||
database = null
|
||||
openFailure = null
|
||||
controller.repeat()
|
||||
app.library.database(request.db).onSuccess { database = it }.onFailure { openFailure = it }
|
||||
}
|
||||
val backend = remember(database) { database?.let(PrepBackends::open) }
|
||||
DisposableEffect(backend) { onDispose { backend?.cancel(); backend?.close() } }
|
||||
LaunchedEffect(controller.retry) { controller.initialise() }
|
||||
LaunchedEffect(backend, controller.initialised, controller.line, controller.retry) {
|
||||
if (backend != null && controller.initialised) controller.search(backend)
|
||||
}
|
||||
|
||||
val prefs by app.settings.prefs.collectAsState()
|
||||
val lang = uiLanguage()
|
||||
val san = remember(prefs.notation, lang) { { value: String -> displaySan(value, prefs.notation, lang) } }
|
||||
val pieces = remember { Pieces(context) }
|
||||
var flipped by rememberSaveable { mutableStateOf(prepBoardStartsFlipped(request.white)) }
|
||||
var conflicts by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
val list = rememberLazyListState()
|
||||
val contextFocus = remember { FocusRequester() }
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
val moveFailed = stringResource(R.string.prep_move_failed)
|
||||
LaunchedEffect(controller.moveFailed) {
|
||||
if (controller.moveFailed) {
|
||||
snackbar.showSnackbar(moveFailed)
|
||||
controller.moveFailed = false
|
||||
}
|
||||
}
|
||||
|
||||
fun play(uci: String) {
|
||||
val played = controller.play(uci) ?: return
|
||||
conflicts = emptyList()
|
||||
app.sounds.move(played)
|
||||
contextFocus.requestFocus()
|
||||
}
|
||||
|
||||
fun arrowsChosen(moves: List<String>) {
|
||||
when (moves.size) {
|
||||
0 -> {}
|
||||
1 -> play(moves[0])
|
||||
else -> conflicts = moves
|
||||
}
|
||||
}
|
||||
|
||||
val position = controller.position
|
||||
val continuations = position?.let(::sortedContinuations).orEmpty()
|
||||
val arrowContinuations = continuations.distinctBy { it.from to it.to }.take(3)
|
||||
val arrows = arrowContinuations.mapIndexedNotNull { index, move ->
|
||||
val from = move.from ?: return@mapIndexedNotNull null
|
||||
val to = move.to ?: return@mapIndexedNotNull null
|
||||
val weight = if (index == 0) 1f else if (index == 1) 0.85f else 0.70f
|
||||
val alpha = if (index == 0) 0.63f else if (index == 1) 0.45f else 0.35f
|
||||
BoardArrow(from, to, EngineArrow.copy(alpha = alpha), weight)
|
||||
}
|
||||
val arrowMoves = continuations.filter { move -> arrowContinuations.any { it.from == move.from && it.to == move.to } }
|
||||
.mapNotNull { move ->
|
||||
val from = move.from ?: return@mapNotNull null
|
||||
val to = move.to ?: return@mapNotNull null
|
||||
val label = moveLabel(controller.line.fen, move.san)
|
||||
val games = pluralStringResource(R.plurals.games_count, move.games, groupDigits(move.games))
|
||||
val action = stringResource(R.string.prep_play_continuation, label, games, frequencyPercent(move.games, position?.games ?: 0))
|
||||
BoardArrowMove(move.uci, from, to, action)
|
||||
}
|
||||
val last = controller.line.last
|
||||
val boardDescription = if (last == null) {
|
||||
stringResource(R.string.prep_board_start, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white))
|
||||
} else {
|
||||
stringResource(R.string.prep_board_after, last.label, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white))
|
||||
}
|
||||
val board: @Composable (Modifier) -> Unit = { modifier ->
|
||||
Board(
|
||||
fen = controller.line.fen,
|
||||
flipped = flipped,
|
||||
lastFrom = last?.from,
|
||||
lastTo = last?.to,
|
||||
pieces = pieces,
|
||||
theme = prefs.board,
|
||||
set = prefs.pieces,
|
||||
description = boardDescription,
|
||||
modifier = modifier,
|
||||
arrows = arrows,
|
||||
arrowMoves = arrowMoves,
|
||||
onArrowMoves = ::arrowsChosen,
|
||||
check = last?.san?.let { it.endsWith("+") || it.endsWith("#") } == true,
|
||||
animated = prefs.animation,
|
||||
input = if (controller.initialised && controller.data != null) {
|
||||
BoardInput(controller.legalMoves(), onMove = ::play)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val turnWhite = prepWhiteToMove(controller.line.fen)
|
||||
val opponentPlays = position?.playerToMove ?: (turnWhite == request.white)
|
||||
val sideToMove = when (turnWhite) {
|
||||
true -> stringResource(R.string.turn_white)
|
||||
false -> stringResource(R.string.turn_black)
|
||||
null -> ""
|
||||
}
|
||||
val who = stringResource(if (opponentPlays) R.string.prep_opponent_plays else R.string.prep_opponents_play)
|
||||
val where = last?.let { stringResource(R.string.prep_after, it.label) } ?: stringResource(R.string.prep_beginning)
|
||||
val gamesCount = position?.games
|
||||
val gamesText = if (gamesCount == null) "…" else pluralStringResource(R.plurals.games_count, gamesCount, groupDigits(gamesCount))
|
||||
val contextDescription = stringResource(R.string.prep_context_description, who, sideToMove, where, gamesText)
|
||||
val contextRow: @Composable () -> Unit = {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 32.dp).focusRequester(contextFocus).focusable()
|
||||
.semantics(mergeDescendants = true) {
|
||||
contentDescription = contextDescription
|
||||
liveRegion = LiveRegionMode.Polite
|
||||
}
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"$who · $where",
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(gamesText, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
val results: @Composable (Modifier) -> Unit = { modifier ->
|
||||
Box(modifier) {
|
||||
when {
|
||||
openFailure != null -> PrepMessage(stringResource(R.string.prep_failed), openProblem(openFailure!!)) {
|
||||
TextButton(onClick = { openRetry += 1 }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
controller.failure != null -> {
|
||||
val memory = controller.failure is PrepOutOfMemory
|
||||
val problem = openProblem(controller.failure!!).ifEmpty { controller.failure!!.message ?: "" }
|
||||
PrepMessage(stringResource(if (memory) R.string.prep_no_memory else R.string.prep_failed), problem) {
|
||||
TextButton(onClick = { controller.repeat() }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
position == null && controller.loading -> {
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart))
|
||||
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(stringResource(R.string.prep_calculating), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
position == null -> PrepPlaceholders()
|
||||
position.games == 0 -> PrepMessage(
|
||||
stringResource(R.string.prep_position_absent, request.player),
|
||||
stringResource(R.string.prep_position_absent_hint),
|
||||
)
|
||||
continuations.isEmpty() && position.endedHere == position.games -> PrepMessage(stringResource(R.string.prep_all_ended), "")
|
||||
else -> LazyColumn(Modifier.fillMaxSize(), state = list) {
|
||||
items(continuations.size, key = { continuations[it].uci }) { index ->
|
||||
ContinuationRow(
|
||||
continuation = continuations[index],
|
||||
total = position.games,
|
||||
fen = controller.line.fen,
|
||||
player = request.player,
|
||||
san = san,
|
||||
divider = index < continuations.lastIndex,
|
||||
onClick = { play(continuations[index].uci) },
|
||||
)
|
||||
}
|
||||
if (position.endedHere > 0 && continuations.isNotEmpty()) {
|
||||
item(key = "ended") { PrepDisabledRow(stringResource(R.string.prep_ended_here, groupDigits(position.endedHere))) }
|
||||
}
|
||||
if (position.noNormalContinuation > 0) {
|
||||
item(key = "no-normal") { PrepDisabledRow(stringResource(R.string.prep_no_normal, groupDigits(position.noNormalContinuation))) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val controls: @Composable () -> Unit = {
|
||||
PrepControls(
|
||||
canBack = controller.line.canBack,
|
||||
canForward = controller.line.canForward,
|
||||
onFlip = { flipped = !flipped },
|
||||
onBack = controller::back,
|
||||
onForward = controller::forward,
|
||||
onStart = controller::start,
|
||||
onEnd = controller::end,
|
||||
)
|
||||
}
|
||||
val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(if (request.fromGame) R.string.to_game else R.string.to_players))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
PlayerName(request.player, MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
stringResource(if (request.white) R.string.prep_as_white else R.string.prep_as_black) + " · " + (entry?.let { displayName(it) } ?: ""),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
bottomBar = { if (!landscape) controls() },
|
||||
) { padding ->
|
||||
val inner = Modifier.fillMaxSize().padding(padding)
|
||||
if (landscape) {
|
||||
Row(inner.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal))) {
|
||||
board(Modifier.fillMaxHeight())
|
||||
Column(Modifier.weight(1f).fillMaxHeight()) {
|
||||
contextRow()
|
||||
results(Modifier.weight(1f).fillMaxWidth())
|
||||
controls()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Column(inner, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
board(Modifier.widthIn(max = 480.dp).fillMaxWidth())
|
||||
Column(Modifier.widthIn(max = 480.dp).fillMaxWidth().weight(1f)) {
|
||||
contextRow()
|
||||
results(Modifier.weight(1f).fillMaxWidth())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicts.isNotEmpty()) {
|
||||
ModalBottomSheet(onDismissRequest = { conflicts = emptyList() }) {
|
||||
Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {
|
||||
Text(stringResource(R.string.prep_choose_move), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp))
|
||||
conflicts.mapNotNull { uci -> continuations.firstOrNull { it.uci == uci } }.forEach { move ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable { play(move.uci) }.padding(horizontal = 24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(san(moveLabel(controller.line.fen, move.san)), style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ContinuationRow(
|
||||
continuation: PrepContinuation,
|
||||
total: Int,
|
||||
fen: String,
|
||||
player: String,
|
||||
san: (String) -> AnnotatedString,
|
||||
divider: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val label = moveLabel(fen, continuation.san)
|
||||
val frequency = frequencyPercent(continuation.games, total)
|
||||
val (wins, draws, losses) = outcomePercents(continuation)
|
||||
val games = pluralStringResource(R.plurals.games_count, total, groupDigits(total))
|
||||
val winsText = pluralStringResource(R.plurals.prep_wins, continuation.wins, groupDigits(continuation.wins))
|
||||
val drawsText = pluralStringResource(R.plurals.prep_draws, continuation.draws, groupDigits(continuation.draws))
|
||||
val lossesText = pluralStringResource(R.plurals.prep_losses, continuation.losses, groupDigits(continuation.losses))
|
||||
val unknown = if (continuation.unknown > 0) stringResource(R.string.prep_unknown_accessibility, continuation.unknown) else ""
|
||||
val description = stringResource(
|
||||
R.string.prep_continuation_description,
|
||||
continuation.san,
|
||||
continuation.games,
|
||||
games,
|
||||
frequency,
|
||||
player,
|
||||
winsText,
|
||||
drawsText,
|
||||
lossesText,
|
||||
wins,
|
||||
draws,
|
||||
losses,
|
||||
unknown,
|
||||
)
|
||||
Column(
|
||||
Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable(onClickLabel = stringResource(R.string.prep_play), role = Role.Button, onClick = onClick)
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = description
|
||||
role = Role.Button
|
||||
onClick { onClick(); true }
|
||||
}
|
||||
.padding(start = 16.dp, top = 5.dp, end = 16.dp, bottom = 5.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(san(label), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge.copy(fontSize = androidx.compose.ui.unit.TextUnit(17f, androidx.compose.ui.unit.TextUnitType.Sp)), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${groupDigits(continuation.games)}/${groupDigits(total)} · $frequency %",
|
||||
style = MaterialTheme.typography.bodyMedium.merge(Tabular),
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
)
|
||||
}
|
||||
val raw = buildString {
|
||||
if (continuation.unknown > 0) append(stringResource(R.string.prep_unknown_short, groupDigits(continuation.unknown))).append(' ')
|
||||
append(stringResource(R.string.prep_wdl_counts, groupDigits(continuation.wins), groupDigits(continuation.draws), groupDigits(continuation.losses), wins, draws, losses))
|
||||
}
|
||||
Text(raw, style = MaterialTheme.typography.labelSmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
if (divider) HorizontalDivider(Modifier.padding(top = 5.dp), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PrepDisabledRow(text: String) {
|
||||
Text(
|
||||
text,
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PrepPlaceholders() {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
repeat(4) {
|
||||
Column(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
Box(Modifier.fillMaxWidth().height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow))
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().height(16.dp).background(MaterialTheme.colorScheme.surfaceContainerLow))
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PrepControls(
|
||||
canBack: Boolean,
|
||||
canForward: Boolean,
|
||||
onFlip: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
onForward: () -> Unit,
|
||||
onStart: () -> Unit,
|
||||
onEnd: () -> Unit,
|
||||
) {
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) {
|
||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.width(72.dp), onClick = onFlip)
|
||||
BarButton(
|
||||
icon = Icons.Rounded.PlayArrow,
|
||||
label = stringResource(R.string.move_back),
|
||||
description = stringResource(R.string.move_back_hint),
|
||||
enabled = canBack,
|
||||
modifier = Modifier.weight(1f),
|
||||
iconSize = 32,
|
||||
mirrored = true,
|
||||
onLongClickLabel = stringResource(R.string.to_start),
|
||||
onLongClick = onStart,
|
||||
onClick = onBack,
|
||||
)
|
||||
BarButton(
|
||||
icon = Icons.Rounded.PlayArrow,
|
||||
label = stringResource(R.string.move_forward),
|
||||
description = stringResource(R.string.move_forward_hint),
|
||||
enabled = canForward,
|
||||
modifier = Modifier.weight(1f),
|
||||
iconSize = 32,
|
||||
onLongClickLabel = stringResource(R.string.to_end),
|
||||
onLongClick = onEnd,
|
||||
onClick = onForward,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -669,4 +669,56 @@
|
|||
<string name="strength_range">%1$s, von %2$s bis %3$s</string>
|
||||
<string name="strength">Spielstärke</string>
|
||||
<string name="books_delete_cd">Eröffnungsbücher löschen</string>
|
||||
|
||||
<!-- Vorbereitung auf den Gegner (Aufgabe 48). -->
|
||||
<string name="players">Spieler</string>
|
||||
<string name="player_name_hint">Spielername</string>
|
||||
<string name="players_read_failed">Spieler konnten nicht gelesen werden</string>
|
||||
<string name="reading_players">Spieler werden gelesen…</string>
|
||||
<string name="no_named_players">Diese Datenbank enthält keine benannten Spieler</string>
|
||||
<string name="player_not_found">Spieler nicht gefunden</string>
|
||||
<string name="to_games">Zu den Partien</string>
|
||||
<string name="reset_search">Suche zurücksetzen</string>
|
||||
<string name="prepare_action">Vorbereiten</string>
|
||||
<string name="prep_choose_color">Farbe wählen</string>
|
||||
<string name="prep_against_player">Vorbereiten gegen %1$s</string>
|
||||
<string name="prep_against_white">Gegen Weiß</string>
|
||||
<string name="prep_against_black">Gegen Schwarz</string>
|
||||
<string name="prep_opponent">Auf Gegner vorbereiten…</string>
|
||||
<string name="prep_title">Vorbereitung auf den Gegner</string>
|
||||
<string name="prep_close_engine_line">Schließen Sie zuerst die Engine-Variante</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Suche nach einem Lehrzug -- ist nicht verfügbar</string>
|
||||
<string name="prep_as_white">Weiß</string>
|
||||
<string name="prep_as_black">Schwarz</string>
|
||||
<string name="prep_move_failed">Dieser Zug konnte nicht ausgeführt werden</string>
|
||||
<string name="prep_play_continuation">%1$s spielen, %2$s, %3$s Prozent</string>
|
||||
<string name="prep_board_start">Brett, Ausgangsstellung. %1$s unten.</string>
|
||||
<string name="prep_board_after">Brett, Stellung nach %1$s. %2$s unten.</string>
|
||||
<string name="turn_white">Weiß am Zug</string>
|
||||
<string name="turn_black">Schwarz am Zug</string>
|
||||
<string name="prep_opponent_plays">Gegner spielt</string>
|
||||
<string name="prep_opponents_play">Seine Gegner spielen</string>
|
||||
<string name="prep_after">nach %1$s</string>
|
||||
<string name="prep_beginning">Anfang</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Fortsetzungen konnten nicht berechnet werden</string>
|
||||
<string name="prep_no_memory">Nicht genügend Speicher für die Suche in dieser Datenbank</string>
|
||||
<string name="prep_calculating">Fortsetzungen werden berechnet…</string>
|
||||
<string name="prep_position_absent">Diese Stellung kommt in Partien von %1$s nicht vor</string>
|
||||
<string name="prep_position_absent_hint">Sie können auf dem Brett fortsetzen oder zurückgehen</string>
|
||||
<string name="prep_all_ended">Alle Partien endeten hier</string>
|
||||
<string name="prep_ended_here">Hier beendet: %1$s</string>
|
||||
<string name="prep_no_normal">Keine normale Fortsetzung: %1$s</string>
|
||||
<string name="to_game">Zur Partie</string>
|
||||
<string name="to_players">Zu den Spielern</string>
|
||||
<string name="prep_choose_move">Zug auswählen</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s Sieg</item><item quantity="other">%1$s Siege</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s Remis</item><item quantity="other">%1$s Remis</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s Niederlage</item><item quantity="other">%1$s Niederlagen</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Unbekannte Ergebnisse: %1$d; nicht in den Prozentwerten enthalten.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d von %3$s, %4$s Prozent. Ergebnisse für %5$s: %6$s, %7$s, %8$s; %9$s, %10$s und %11$s Prozent. %12$s Spielen.</string>
|
||||
<string name="prep_play">Spielen</string>
|
||||
<string name="prep_unknown_short">weitere %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -678,4 +678,56 @@
|
|||
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
||||
<string name="strength">Fuerza</string>
|
||||
<string name="books_delete_cd">Eliminar los libros de aperturas</string>
|
||||
|
||||
<!-- Preparación contra el rival (tarea 48). -->
|
||||
<string name="players">Jugadores</string>
|
||||
<string name="player_name_hint">Nombre del jugador</string>
|
||||
<string name="players_read_failed">No se pudieron leer los jugadores</string>
|
||||
<string name="reading_players">Leyendo jugadores…</string>
|
||||
<string name="no_named_players">No hay jugadores con nombre en esta base</string>
|
||||
<string name="player_not_found">Jugador no encontrado</string>
|
||||
<string name="to_games">Volver a las partidas</string>
|
||||
<string name="reset_search">Borrar búsqueda</string>
|
||||
<string name="prepare_action">Preparar</string>
|
||||
<string name="prep_choose_color">Elige un color</string>
|
||||
<string name="prep_against_player">Prepararse contra %1$s</string>
|
||||
<string name="prep_against_white">Contra las blancas</string>
|
||||
<string name="prep_against_black">Contra las negras</string>
|
||||
<string name="prep_opponent">Prepararse contra el rival…</string>
|
||||
<string name="prep_title">Preparación contra el rival</string>
|
||||
<string name="prep_close_engine_line">Cierra primero la línea del motor</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">La búsqueda después de un -- didáctico no está disponible</string>
|
||||
<string name="prep_as_white">Blancas</string>
|
||||
<string name="prep_as_black">Negras</string>
|
||||
<string name="prep_move_failed">No se pudo jugar este movimiento</string>
|
||||
<string name="prep_play_continuation">Jugar %1$s, %2$s, %3$s por ciento</string>
|
||||
<string name="prep_board_start">Tablero, posición inicial. %1$s abajo.</string>
|
||||
<string name="prep_board_after">Tablero, posición después de %1$s. %2$s abajo.</string>
|
||||
<string name="turn_white">Juegan las blancas</string>
|
||||
<string name="turn_black">Juegan las negras</string>
|
||||
<string name="prep_opponent_plays">Juega el rival</string>
|
||||
<string name="prep_opponents_play">Juegan sus rivales</string>
|
||||
<string name="prep_after">después de %1$s</string>
|
||||
<string name="prep_beginning">inicio</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">No se pudieron calcular las continuaciones</string>
|
||||
<string name="prep_no_memory">No hay memoria suficiente para buscar en esta base</string>
|
||||
<string name="prep_calculating">Calculando continuaciones…</string>
|
||||
<string name="prep_position_absent">Esta posición no aparece en las partidas de %1$s</string>
|
||||
<string name="prep_position_absent_hint">Puedes continuar en el tablero o retroceder</string>
|
||||
<string name="prep_all_ended">Todas las partidas terminaron aquí</string>
|
||||
<string name="prep_ended_here">Terminaron aquí: %1$s</string>
|
||||
<string name="prep_no_normal">Sin continuación normal: %1$s</string>
|
||||
<string name="to_game">Volver a la partida</string>
|
||||
<string name="to_players">Volver a los jugadores</string>
|
||||
<string name="prep_choose_move">Elige un movimiento</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s victoria</item><item quantity="many">%1$s victorias</item><item quantity="other">%1$s victorias</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s tabla</item><item quantity="many">%1$s tablas</item><item quantity="other">%1$s tablas</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s derrota</item><item quantity="many">%1$s derrotas</item><item quantity="other">%1$s derrotas</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Resultados desconocidos: %1$d; excluidos de los porcentajes.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d de %3$s, %4$s por ciento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s y %11$s por ciento. %12$s Jugar.</string>
|
||||
<string name="prep_play">Jugar</string>
|
||||
<string name="prep_unknown_short">%1$s más</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -678,4 +678,56 @@
|
|||
<string name="strength_range">%1$s, de %2$s à %3$s</string>
|
||||
<string name="strength">Force</string>
|
||||
<string name="books_delete_cd">Supprimer les livres d’ouvertures</string>
|
||||
|
||||
<!-- Préparation contre l’adversaire (tâche 48). -->
|
||||
<string name="players">Joueurs</string>
|
||||
<string name="player_name_hint">Nom du joueur</string>
|
||||
<string name="players_read_failed">Impossible de lire les joueurs</string>
|
||||
<string name="reading_players">Lecture des joueurs…</string>
|
||||
<string name="no_named_players">Cette base ne contient aucun joueur nommé</string>
|
||||
<string name="player_not_found">Joueur introuvable</string>
|
||||
<string name="to_games">Retour aux parties</string>
|
||||
<string name="reset_search">Effacer la recherche</string>
|
||||
<string name="prepare_action">Préparer</string>
|
||||
<string name="prep_choose_color">Choisissez la couleur</string>
|
||||
<string name="prep_against_player">Préparer contre %1$s</string>
|
||||
<string name="prep_against_white">Contre les Blancs</string>
|
||||
<string name="prep_against_black">Contre les Noirs</string>
|
||||
<string name="prep_opponent">Préparer contre l’adversaire…</string>
|
||||
<string name="prep_title">Préparation contre l’adversaire</string>
|
||||
<string name="prep_close_engine_line">Fermez d’abord la ligne du moteur</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">La recherche après un -- pédagogique est indisponible</string>
|
||||
<string name="prep_as_white">Blancs</string>
|
||||
<string name="prep_as_black">Noirs</string>
|
||||
<string name="prep_move_failed">Impossible de jouer ce coup</string>
|
||||
<string name="prep_play_continuation">Jouer %1$s, %2$s, %3$s pour cent</string>
|
||||
<string name="prep_board_start">Échiquier, position initiale. %1$s en bas.</string>
|
||||
<string name="prep_board_after">Échiquier, position après %1$s. %2$s en bas.</string>
|
||||
<string name="turn_white">Trait aux blancs</string>
|
||||
<string name="turn_black">Trait aux noirs</string>
|
||||
<string name="prep_opponent_plays">L’adversaire joue</string>
|
||||
<string name="prep_opponents_play">Ses adversaires jouent</string>
|
||||
<string name="prep_after">après %1$s</string>
|
||||
<string name="prep_beginning">début</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Impossible de calculer les continuations</string>
|
||||
<string name="prep_no_memory">Mémoire insuffisante pour rechercher dans cette base</string>
|
||||
<string name="prep_calculating">Calcul des continuations…</string>
|
||||
<string name="prep_position_absent">Cette position n’apparaît pas dans les parties de %1$s</string>
|
||||
<string name="prep_position_absent_hint">Vous pouvez continuer sur l’échiquier ou revenir en arrière</string>
|
||||
<string name="prep_all_ended">Toutes les parties se terminent ici</string>
|
||||
<string name="prep_ended_here">Terminées ici : %1$s</string>
|
||||
<string name="prep_no_normal">Aucune continuation normale : %1$s</string>
|
||||
<string name="to_game">Retour à la partie</string>
|
||||
<string name="to_players">Retour aux joueurs</string>
|
||||
<string name="prep_choose_move">Choisir un coup</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s victoire</item><item quantity="many">%1$s victoires</item><item quantity="other">%1$s victoires</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s nulle</item><item quantity="many">%1$s nulles</item><item quantity="other">%1$s nulles</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s défaite</item><item quantity="many">%1$s défaites</item><item quantity="other">%1$s défaites</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Résultats inconnus : %1$d ; exclus des pourcentages.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d sur %3$s, %4$s pour cent. Résultats de %5$s : %6$s, %7$s, %8$s ; %9$s, %10$s et %11$s pour cent. %12$s Jouer.</string>
|
||||
<string name="prep_play">Jouer</string>
|
||||
<string name="prep_unknown_short">plus %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -678,4 +678,56 @@
|
|||
<string name="strength_range">%1$s, da %2$s a %3$s</string>
|
||||
<string name="strength">Forza</string>
|
||||
<string name="books_delete_cd">Elimina i libri di aperture</string>
|
||||
|
||||
<!-- Preparazione contro l\'avversario (attività 48). -->
|
||||
<string name="players">Giocatori</string>
|
||||
<string name="player_name_hint">Nome del giocatore</string>
|
||||
<string name="players_read_failed">Impossibile leggere i giocatori</string>
|
||||
<string name="reading_players">Lettura dei giocatori…</string>
|
||||
<string name="no_named_players">Questo database non contiene giocatori con nome</string>
|
||||
<string name="player_not_found">Giocatore non trovato</string>
|
||||
<string name="to_games">Torna alle partite</string>
|
||||
<string name="reset_search">Cancella ricerca</string>
|
||||
<string name="prepare_action">Prepara</string>
|
||||
<string name="prep_choose_color">Scegli un colore</string>
|
||||
<string name="prep_against_player">Preparati contro %1$s</string>
|
||||
<string name="prep_against_white">Contro il Bianco</string>
|
||||
<string name="prep_against_black">Contro il Nero</string>
|
||||
<string name="prep_opponent">Preparati contro l\'avversario…</string>
|
||||
<string name="prep_title">Preparazione contro l\'avversario</string>
|
||||
<string name="prep_close_engine_line">Chiudi prima la linea del motore</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">La ricerca dopo un -- didattico non è disponibile</string>
|
||||
<string name="prep_as_white">Bianco</string>
|
||||
<string name="prep_as_black">Nero</string>
|
||||
<string name="prep_move_failed">Impossibile giocare questa mossa</string>
|
||||
<string name="prep_play_continuation">Gioca %1$s, %2$s, %3$s per cento</string>
|
||||
<string name="prep_board_start">Scacchiera, posizione iniziale. %1$s in basso.</string>
|
||||
<string name="prep_board_after">Scacchiera, posizione dopo %1$s. %2$s in basso.</string>
|
||||
<string name="turn_white">Tocca al bianco</string>
|
||||
<string name="turn_black">Tocca al nero</string>
|
||||
<string name="prep_opponent_plays">Gioca l\'avversario</string>
|
||||
<string name="prep_opponents_play">Giocano i suoi avversari</string>
|
||||
<string name="prep_after">dopo %1$s</string>
|
||||
<string name="prep_beginning">inizio</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Impossibile calcolare le continuazioni</string>
|
||||
<string name="prep_no_memory">Memoria insufficiente per cercare in questo database</string>
|
||||
<string name="prep_calculating">Calcolo delle continuazioni…</string>
|
||||
<string name="prep_position_absent">Questa posizione non compare nelle partite di %1$s</string>
|
||||
<string name="prep_position_absent_hint">Puoi continuare sulla scacchiera o tornare indietro</string>
|
||||
<string name="prep_all_ended">Tutte le partite sono terminate qui</string>
|
||||
<string name="prep_ended_here">Terminate qui: %1$s</string>
|
||||
<string name="prep_no_normal">Nessuna continuazione normale: %1$s</string>
|
||||
<string name="to_game">Torna alla partita</string>
|
||||
<string name="to_players">Torna ai giocatori</string>
|
||||
<string name="prep_choose_move">Scegli una mossa</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s vittoria</item><item quantity="many">%1$s vittorie</item><item quantity="other">%1$s vittorie</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s patta</item><item quantity="many">%1$s patte</item><item quantity="other">%1$s patte</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s sconfitta</item><item quantity="many">%1$s sconfitte</item><item quantity="other">%1$s sconfitte</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Risultati sconosciuti: %1$d; esclusi dalle percentuali.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d di %3$s, %4$s per cento. Risultati di %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s per cento. %12$s Gioca.</string>
|
||||
<string name="prep_play">Gioca</string>
|
||||
<string name="prep_unknown_short">altri %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -670,4 +670,56 @@
|
|||
<string name="strength_range">%1$s, %2$s-ден %3$s-ге дейін</string>
|
||||
<string name="strength">Күші</string>
|
||||
<string name="books_delete_cd">Дебют кітаптарын жою</string>
|
||||
|
||||
<!-- Қарсыласқа дайындық (48-тапсырма). -->
|
||||
<string name="players">Ойыншылар</string>
|
||||
<string name="player_name_hint">Ойыншының аты</string>
|
||||
<string name="players_read_failed">Ойыншыларды оқу мүмкін болмады</string>
|
||||
<string name="reading_players">Ойыншылар оқылуда…</string>
|
||||
<string name="no_named_players">Бұл базада аты көрсетілген ойыншылар жоқ</string>
|
||||
<string name="player_not_found">Ойыншы табылмады</string>
|
||||
<string name="to_games">Партияларға оралу</string>
|
||||
<string name="reset_search">Іздеуді тазалау</string>
|
||||
<string name="prepare_action">Дайындалу</string>
|
||||
<string name="prep_choose_color">Түсті таңдаңыз</string>
|
||||
<string name="prep_against_player">Қарсыласқа дайындалу %1$s</string>
|
||||
<string name="prep_against_white">Ақтарға қарсы</string>
|
||||
<string name="prep_against_black">Қараларға қарсы</string>
|
||||
<string name="prep_opponent">Қарсыласқа дайындалу…</string>
|
||||
<string name="prep_title">Қарсыласқа дайындық</string>
|
||||
<string name="prep_close_engine_line">Алдымен қозғалтқыш желісін жабыңыз</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Оқу -- кейін іздеу қолжетімсіз</string>
|
||||
<string name="prep_as_white">Ақтар</string>
|
||||
<string name="prep_as_black">Қаралар</string>
|
||||
<string name="prep_move_failed">Бұл жүрісті жасау мүмкін болмады</string>
|
||||
<string name="prep_play_continuation">%1$s жүру, %2$s, %3$s пайыз</string>
|
||||
<string name="prep_board_start">Тақта, бастапқы позиция. Төменде %1$s.</string>
|
||||
<string name="prep_board_after">Тақта, %1$s кейінгі позиция. Төменде %2$s.</string>
|
||||
<string name="turn_white">Ақтардың жүрісі</string>
|
||||
<string name="turn_black">Қаралардың жүрісі</string>
|
||||
<string name="prep_opponent_plays">Қарсылас жүреді</string>
|
||||
<string name="prep_opponents_play">Оның қарсыластары жүреді</string>
|
||||
<string name="prep_after">%1$s кейін</string>
|
||||
<string name="prep_beginning">басы</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Жалғастарды есептеу мүмкін болмады</string>
|
||||
<string name="prep_no_memory">Бұл базадан іздеуге жад жеткіліксіз</string>
|
||||
<string name="prep_calculating">Жалғастар есептелуде…</string>
|
||||
<string name="prep_position_absent">%1$s партияларында бұл позиция жоқ</string>
|
||||
<string name="prep_position_absent_hint">Тақтада жалғастыруға немесе артқа оралуға болады</string>
|
||||
<string name="prep_all_ended">Барлық партия осы жерде аяқталды</string>
|
||||
<string name="prep_ended_here">Осы жерде аяқталды: %1$s</string>
|
||||
<string name="prep_no_normal">Қалыпты жалғас жоқ: %1$s</string>
|
||||
<string name="to_game">Партияға оралу</string>
|
||||
<string name="to_players">Ойыншыларға оралу</string>
|
||||
<string name="prep_choose_move">Жүрісті таңдаңыз</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s жеңіс</item><item quantity="other">%1$s жеңіс</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s тең ойын</item><item quantity="other">%1$s тең ойын</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s жеңіліс</item><item quantity="other">%1$s жеңіліс</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Белгісіз нәтижелер: %1$d; олар пайызға кірмейді.</string>
|
||||
<string name="prep_continuation_description">%1$s. %3$s ішінен %2$d, %4$s пайыз. %5$s нәтижелері: %6$s, %7$s, %8$s; %9$s, %10$s және %11$s пайыз. %12$s Жүру.</string>
|
||||
<string name="prep_play">Жүру</string>
|
||||
<string name="prep_unknown_short">тағы %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -679,4 +679,56 @@
|
|||
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
||||
<string name="strength">Força</string>
|
||||
<string name="books_delete_cd">Excluir os livros de aberturas</string>
|
||||
|
||||
<!-- Preparação contra o adversário (tarefa 48). -->
|
||||
<string name="players">Jogadores</string>
|
||||
<string name="player_name_hint">Nome do jogador</string>
|
||||
<string name="players_read_failed">Não foi possível ler os jogadores</string>
|
||||
<string name="reading_players">A ler jogadores…</string>
|
||||
<string name="no_named_players">Não há jogadores identificados nesta base</string>
|
||||
<string name="player_not_found">Jogador não encontrado</string>
|
||||
<string name="to_games">Voltar às partidas</string>
|
||||
<string name="reset_search">Limpar pesquisa</string>
|
||||
<string name="prepare_action">Preparar</string>
|
||||
<string name="prep_choose_color">Escolha uma cor</string>
|
||||
<string name="prep_against_player">Preparar contra %1$s</string>
|
||||
<string name="prep_against_white">Contra as brancas</string>
|
||||
<string name="prep_against_black">Contra as pretas</string>
|
||||
<string name="prep_opponent">Preparar contra o adversário…</string>
|
||||
<string name="prep_title">Preparação contra o adversário</string>
|
||||
<string name="prep_close_engine_line">Feche primeiro a linha do motor</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">A pesquisa depois de um -- didático não está disponível</string>
|
||||
<string name="prep_as_white">Brancas</string>
|
||||
<string name="prep_as_black">Pretas</string>
|
||||
<string name="prep_move_failed">Não foi possível jogar este lance</string>
|
||||
<string name="prep_play_continuation">Jogar %1$s, %2$s, %3$s por cento</string>
|
||||
<string name="prep_board_start">Tabuleiro, posição inicial. %1$s em baixo.</string>
|
||||
<string name="prep_board_after">Tabuleiro, posição depois de %1$s. %2$s em baixo.</string>
|
||||
<string name="turn_white">Jogam as brancas</string>
|
||||
<string name="turn_black">Jogam as pretas</string>
|
||||
<string name="prep_opponent_plays">O adversário joga</string>
|
||||
<string name="prep_opponents_play">Os seus adversários jogam</string>
|
||||
<string name="prep_after">depois de %1$s</string>
|
||||
<string name="prep_beginning">início</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Não foi possível calcular as continuações</string>
|
||||
<string name="prep_no_memory">Memória insuficiente para pesquisar nesta base</string>
|
||||
<string name="prep_calculating">A calcular continuações…</string>
|
||||
<string name="prep_position_absent">Esta posição não ocorre nas partidas de %1$s</string>
|
||||
<string name="prep_position_absent_hint">Pode continuar no tabuleiro ou retroceder</string>
|
||||
<string name="prep_all_ended">Todas as partidas terminaram aqui</string>
|
||||
<string name="prep_ended_here">Terminaram aqui: %1$s</string>
|
||||
<string name="prep_no_normal">Sem continuação normal: %1$s</string>
|
||||
<string name="to_game">Voltar à partida</string>
|
||||
<string name="to_players">Voltar aos jogadores</string>
|
||||
<string name="prep_choose_move">Escolha um lance</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s vitória</item><item quantity="many">%1$s vitórias</item><item quantity="other">%1$s vitórias</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s empate</item><item quantity="many">%1$s empates</item><item quantity="other">%1$s empates</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s derrota</item><item quantity="many">%1$s derrotas</item><item quantity="other">%1$s derrotas</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Resultados desconhecidos: %1$d; excluídos das percentagens.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d de %3$s, %4$s por cento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s por cento. %12$s Jogar.</string>
|
||||
<string name="prep_play">Jogar</string>
|
||||
<string name="prep_unknown_short">mais %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -687,4 +687,71 @@
|
|||
<string name="strength_range">%1$s, от %2$s до %3$s</string>
|
||||
<string name="strength">Сила</string>
|
||||
<string name="books_delete_cd">Удалить дебютные книги</string>
|
||||
|
||||
<!-- Подготовка к сопернику (задача 48). -->
|
||||
<string name="players">Игроки</string>
|
||||
<string name="player_name_hint">Имя игрока</string>
|
||||
<string name="players_read_failed">Не удалось прочитать игроков</string>
|
||||
<string name="reading_players">Читаю игроков…</string>
|
||||
<string name="no_named_players">В этой базе нет именованных игроков</string>
|
||||
<string name="player_not_found">Игрок не найден</string>
|
||||
<string name="to_games">К партиям</string>
|
||||
<string name="reset_search">Сбросить поиск</string>
|
||||
<string name="prepare_action">Подготовиться</string>
|
||||
<string name="prep_choose_color">Выберите цвет</string>
|
||||
<string name="prep_against_player">Подготовиться к %1$s</string>
|
||||
<string name="prep_against_white">Против белых</string>
|
||||
<string name="prep_against_black">Против чёрных</string>
|
||||
<string name="prep_opponent">Подготовиться к сопернику…</string>
|
||||
<string name="prep_title">Подготовка к сопернику</string>
|
||||
<string name="prep_close_engine_line">Сначала закройте линию движка</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Поиск после учебного -- недоступен</string>
|
||||
<string name="prep_as_white">Белыми</string>
|
||||
<string name="prep_as_black">Чёрными</string>
|
||||
<string name="prep_move_failed">Не удалось сделать ход</string>
|
||||
<string name="prep_play_continuation">Сыграть %1$s, %2$s, %3$s процентов</string>
|
||||
<string name="prep_board_start">Доска, начальная позиция. Внизу %1$s.</string>
|
||||
<string name="prep_board_after">Доска, позиция после %1$s. Внизу %2$s.</string>
|
||||
<string name="turn_white">ход белых</string>
|
||||
<string name="turn_black">ход чёрных</string>
|
||||
<string name="prep_opponent_plays">Соперник играет</string>
|
||||
<string name="prep_opponents_play">Его оппоненты играют</string>
|
||||
<string name="prep_after">после %1$s</string>
|
||||
<string name="prep_beginning">начало</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Не удалось посчитать продолжения</string>
|
||||
<string name="prep_no_memory">Недостаточно памяти для поиска по этой базе</string>
|
||||
<string name="prep_calculating">Считаю продолжения…</string>
|
||||
<string name="prep_position_absent">В партиях %1$s этой позиции нет</string>
|
||||
<string name="prep_position_absent_hint">Можно продолжить на доске или вернуться назад</string>
|
||||
<string name="prep_all_ended">Все партии здесь закончились</string>
|
||||
<string name="prep_ended_here">Здесь закончились: %1$s</string>
|
||||
<string name="prep_no_normal">Нет обычного продолжения: %1$s</string>
|
||||
<string name="to_game">К партии</string>
|
||||
<string name="to_players">К игрокам</string>
|
||||
<string name="prep_choose_move">Выберите ход</string>
|
||||
<plurals name="prep_wins">
|
||||
<item quantity="one">%1$s победа</item>
|
||||
<item quantity="few">%1$s победы</item>
|
||||
<item quantity="many">%1$s побед</item>
|
||||
<item quantity="other">%1$s победы</item>
|
||||
</plurals>
|
||||
<plurals name="prep_draws">
|
||||
<item quantity="one">%1$s ничья</item>
|
||||
<item quantity="few">%1$s ничьи</item>
|
||||
<item quantity="many">%1$s ничьих</item>
|
||||
<item quantity="other">%1$s ничьи</item>
|
||||
</plurals>
|
||||
<plurals name="prep_losses">
|
||||
<item quantity="one">%1$s поражение</item>
|
||||
<item quantity="few">%1$s поражения</item>
|
||||
<item quantity="many">%1$s поражений</item>
|
||||
<item quantity="other">%1$s поражения</item>
|
||||
</plurals>
|
||||
<string name="prep_unknown_accessibility">Неизвестных исходов: %1$d; они не входят в знаменатель процентов.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d из %3$s, %4$s процентов. Результаты %5$s: %6$s, %7$s, %8$s; %9$s, %10$s и %11$s процентов. %12$s Сыграть.</string>
|
||||
<string name="prep_play">Сыграть</string>
|
||||
<string name="prep_unknown_short">ещё %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -668,4 +668,56 @@
|
|||
<string name="strength_range">%1$s, %2$s dan %3$s gacha</string>
|
||||
<string name="strength">Kuch</string>
|
||||
<string name="books_delete_cd">Debyut kitoblarini o‘chirish</string>
|
||||
|
||||
<!-- Raqibga tayyorgarlik (48-vazifa). -->
|
||||
<string name="players">Oʻyinchilar</string>
|
||||
<string name="player_name_hint">Oʻyinchi ismi</string>
|
||||
<string name="players_read_failed">Oʻyinchilarni oʻqib boʻlmadi</string>
|
||||
<string name="reading_players">Oʻyinchilar oʻqilmoqda…</string>
|
||||
<string name="no_named_players">Bu bazada nomi koʻrsatilgan oʻyinchilar yoʻq</string>
|
||||
<string name="player_not_found">Oʻyinchi topilmadi</string>
|
||||
<string name="to_games">Partiyalarga qaytish</string>
|
||||
<string name="reset_search">Qidiruvni tozalash</string>
|
||||
<string name="prepare_action">Tayyorlanish</string>
|
||||
<string name="prep_choose_color">Rangni tanlang</string>
|
||||
<string name="prep_against_player">Raqibga tayyorlanish %1$s</string>
|
||||
<string name="prep_against_white">Oqlarga qarshi</string>
|
||||
<string name="prep_against_black">Qoralarga qarshi</string>
|
||||
<string name="prep_opponent">Raqibga tayyorlanish…</string>
|
||||
<string name="prep_title">Raqibga tayyorgarlik</string>
|
||||
<string name="prep_close_engine_line">Avval dvigatel chizigʻini yoping</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Oʻquv -- dan keyin qidirish mavjud emas</string>
|
||||
<string name="prep_as_white">Oqlar</string>
|
||||
<string name="prep_as_black">Qoralar</string>
|
||||
<string name="prep_move_failed">Bu yurishni bajarib boʻlmadi</string>
|
||||
<string name="prep_play_continuation">%1$s yurish, %2$s, %3$s foiz</string>
|
||||
<string name="prep_board_start">Doska, boshlangʻich pozitsiya. Pastda %1$s.</string>
|
||||
<string name="prep_board_after">Doska, %1$s dan keyingi pozitsiya. Pastda %2$s.</string>
|
||||
<string name="turn_white">Oqlar yurishi</string>
|
||||
<string name="turn_black">Qoralar yurishi</string>
|
||||
<string name="prep_opponent_plays">Raqib yuradi</string>
|
||||
<string name="prep_opponents_play">Uning raqiblari yuradi</string>
|
||||
<string name="prep_after">%1$s dan keyin</string>
|
||||
<string name="prep_beginning">boshlanishi</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Davomlarni hisoblab boʻlmadi</string>
|
||||
<string name="prep_no_memory">Bu bazadan qidirish uchun xotira yetarli emas</string>
|
||||
<string name="prep_calculating">Davomlar hisoblanmoqda…</string>
|
||||
<string name="prep_position_absent">%1$s partiyalarida bu pozitsiya yoʻq</string>
|
||||
<string name="prep_position_absent_hint">Doskada davom etishingiz yoki orqaga qaytishingiz mumkin</string>
|
||||
<string name="prep_all_ended">Barcha partiyalar shu yerda tugagan</string>
|
||||
<string name="prep_ended_here">Shu yerda tugagan: %1$s</string>
|
||||
<string name="prep_no_normal">Oddiy davom yoʻq: %1$s</string>
|
||||
<string name="to_game">Partiyaga qaytish</string>
|
||||
<string name="to_players">Oʻyinchilarga qaytish</string>
|
||||
<string name="prep_choose_move">Yurishni tanlang</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s gʻalaba</item><item quantity="other">%1$s gʻalaba</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s durang</item><item quantity="other">%1$s durang</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s magʻlubiyat</item><item quantity="other">%1$s magʻlubiyat</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Nomaʼlum natijalar: %1$d; ular foizlarga kiritilmaydi.</string>
|
||||
<string name="prep_continuation_description">%1$s. %3$s dan %2$d tasi, %4$s foiz. %5$s natijalari: %6$s, %7$s, %8$s; %9$s, %10$s va %11$s foiz. %12$s Yurish.</string>
|
||||
<string name="prep_play">Yurish</string>
|
||||
<string name="prep_unknown_short">yana %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -673,4 +673,65 @@
|
|||
<string name="strength_range">%1$s, from %2$s to %3$s</string>
|
||||
<string name="strength">Strength</string>
|
||||
<string name="books_delete_cd">Delete the opening books</string>
|
||||
|
||||
<!-- Opponent preparation (task 48). -->
|
||||
<string name="players">Players</string>
|
||||
<string name="player_name_hint">Player name</string>
|
||||
<string name="players_read_failed">Could not read players</string>
|
||||
<string name="reading_players">Reading players…</string>
|
||||
<string name="no_named_players">There are no named players in this database</string>
|
||||
<string name="player_not_found">Player not found</string>
|
||||
<string name="to_games">Back to games</string>
|
||||
<string name="reset_search">Clear search</string>
|
||||
<string name="prepare_action">Prepare</string>
|
||||
<string name="prep_choose_color">Choose a color</string>
|
||||
<string name="prep_against_player">Prepare against %1$s</string>
|
||||
<string name="prep_against_white">Against White</string>
|
||||
<string name="prep_against_black">Against Black</string>
|
||||
<string name="prep_opponent">Prepare for opponent…</string>
|
||||
<string name="prep_title">Opponent preparation</string>
|
||||
<string name="prep_close_engine_line">Close the engine line first</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Search after a teaching -- is unavailable</string>
|
||||
<string name="prep_as_white">White</string>
|
||||
<string name="prep_as_black">Black</string>
|
||||
<string name="prep_move_failed">Could not play this move</string>
|
||||
<string name="prep_play_continuation">Play %1$s, %2$s, %3$s percent</string>
|
||||
<string name="prep_board_start">Board, starting position. %1$s at the bottom.</string>
|
||||
<string name="prep_board_after">Board, position after %1$s. %2$s at the bottom.</string>
|
||||
<string name="turn_white">White to move</string>
|
||||
<string name="turn_black">Black to move</string>
|
||||
<string name="prep_opponent_plays">Opponent plays</string>
|
||||
<string name="prep_opponents_play">Their opponents play</string>
|
||||
<string name="prep_after">after %1$s</string>
|
||||
<string name="prep_beginning">start</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Could not calculate continuations</string>
|
||||
<string name="prep_no_memory">Not enough memory to search this database</string>
|
||||
<string name="prep_calculating">Calculating continuations…</string>
|
||||
<string name="prep_position_absent">This position does not occur in games by %1$s</string>
|
||||
<string name="prep_position_absent_hint">You can continue on the board or go back</string>
|
||||
<string name="prep_all_ended">All games ended here</string>
|
||||
<string name="prep_ended_here">Ended here: %1$s</string>
|
||||
<string name="prep_no_normal">No normal continuation: %1$s</string>
|
||||
<string name="to_game">Back to game</string>
|
||||
<string name="to_players">Back to players</string>
|
||||
<string name="prep_choose_move">Choose a move</string>
|
||||
<plurals name="prep_wins">
|
||||
<item quantity="one">%1$s win</item>
|
||||
<item quantity="other">%1$s wins</item>
|
||||
</plurals>
|
||||
<plurals name="prep_draws">
|
||||
<item quantity="one">%1$s draw</item>
|
||||
<item quantity="other">%1$s draws</item>
|
||||
</plurals>
|
||||
<plurals name="prep_losses">
|
||||
<item quantity="one">%1$s loss</item>
|
||||
<item quantity="other">%1$s losses</item>
|
||||
</plurals>
|
||||
<string name="prep_unknown_accessibility">Unknown results: %1$d; excluded from the percentages.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d of %3$s, %4$s percent. Results for %5$s: %6$s, %7$s, %8$s; %9$s, %10$s and %11$s percent. %12$s Play.</string>
|
||||
<string name="prep_play">Play</string>
|
||||
<string name="prep_unknown_short">more %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BoardArrowHitTest {
|
||||
@Test
|
||||
fun `flip changes the hit point but not UCI`() {
|
||||
val move = BoardArrowMove("e2e4", "e2", "e4", "e4")
|
||||
val square = 40f
|
||||
val center = Offset(square / 2, square / 2)
|
||||
val target = squareIndex("e4")!!
|
||||
val normal = boardCell(target, square, false) + center
|
||||
val flipped = boardCell(target, square, true) + center
|
||||
|
||||
assertEquals(listOf("e2e4"), arrowHits(normal, square, false, listOf(move), 24f).map { it.uci })
|
||||
assertTrue(arrowHits(normal, square, true, listOf(move), 24f).isEmpty())
|
||||
assertEquals(listOf("e2e4"), arrowHits(flipped, square, true, listOf(move), 24f).map { it.uci })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `overlapping targets return every conflicting UCI`() {
|
||||
val square = 35f
|
||||
val center = Offset(square / 2, square / 2)
|
||||
val target = boardCell(squareIndex("e8")!!, square, false) + center
|
||||
val moves = listOf(
|
||||
BoardArrowMove("e7e8q", "e7", "e8", "queen"),
|
||||
BoardArrowMove("e7e8n", "e7", "e8", "knight"),
|
||||
)
|
||||
|
||||
assertEquals(listOf("e7e8q", "e7e8n"), arrowHits(target, square, false, moves, 24f).map { it.uci })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `points outside the board never activate an arrow`() {
|
||||
val move = BoardArrowMove("e2e4", "e2", "e4", "e4")
|
||||
assertTrue(arrowHits(Offset(-1f, 10f), 40f, false, listOf(move), 24f).isEmpty())
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PlayersStateTest {
|
||||
@Test
|
||||
fun `two available colors always require an explicit choice`() {
|
||||
val blackMoreOften = player(white = 2, black = 3)
|
||||
val whiteMoreOften = player(white = 9, black = 1)
|
||||
|
||||
assertTrue(playerNeedsColorChoice(blackMoreOften))
|
||||
assertTrue(playerNeedsColorChoice(whiteMoreOften))
|
||||
assertNull(solePlayerColor(blackMoreOften))
|
||||
assertNull(solePlayerColor(whiteMoreOften))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exactly one available color is the direct action`() {
|
||||
val whiteOnly = player(white = 2, black = 0)
|
||||
val blackOnly = player(white = 0, black = 1)
|
||||
|
||||
assertTrue(solePlayerColor(whiteOnly) == true)
|
||||
assertTrue(solePlayerColor(blackOnly) == false)
|
||||
assertFalse(playerNeedsColorChoice(whiteOnly))
|
||||
assertFalse(playerNeedsColorChoice(blackOnly))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `zero colors do not become an action`() {
|
||||
val empty = player(white = 0, black = 0)
|
||||
|
||||
assertNull(solePlayerColor(empty))
|
||||
assertFalse(playerNeedsColorChoice(empty))
|
||||
}
|
||||
|
||||
private fun player(white: Int, black: Int) = PlayerSummary(
|
||||
id = 1,
|
||||
name = "Player",
|
||||
total = 100,
|
||||
whiteGames = white,
|
||||
blackGames = black,
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PrepLineStateTest {
|
||||
@Test
|
||||
fun `back and forward follow the same continuation`() {
|
||||
val line = line("e2e4", "e7e5", "g1f3")
|
||||
|
||||
val back = line.back().back()
|
||||
assertEquals(1, back.cursor)
|
||||
assertEquals("e2e4", back.last?.uci)
|
||||
assertTrue(back.canForward)
|
||||
|
||||
val forward = back.forward()
|
||||
assertEquals("e7e5", forward.last?.uci)
|
||||
assertEquals("g1f3", forward.forward().last?.uci)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `long actions jump without an extra step`() {
|
||||
val line = line("e2e4", "e7e5", "g1f3")
|
||||
assertEquals(0, line.start().cursor)
|
||||
assertEquals(line.steps.size, line.start().end().cursor)
|
||||
assertEquals(line, line.end())
|
||||
assertEquals(line.start(), line.start().start())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a played line replaces only the temporary future`() {
|
||||
val original = line("e2e4", "e7e5", "g1f3").back().back()
|
||||
val prefix = original.steps.take(original.cursor)
|
||||
val replacement = step("c7c5", 2, "c5")
|
||||
val changed = original.replaceVisibleLine(prefix + replacement, replacement.node)
|
||||
|
||||
assertEquals(listOf("e2e4", "c7c5"), changed.moves)
|
||||
assertEquals(2, changed.cursor)
|
||||
assertFalse(changed.canForward)
|
||||
assertEquals(listOf("e2e4", "e7e5", "g1f3"), original.moves)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `opponent color puts the user at the bottom`() {
|
||||
assertTrue(prepBoardStartsFlipped(opponentWhite = true))
|
||||
assertFalse(prepBoardStartsFlipped(opponentWhite = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `side and number come from FEN rather than parity`() {
|
||||
val black = "8/8/8/8/8/8/4k3/4K3 b - - 0 0"
|
||||
assertEquals(false, prepWhiteToMove(black))
|
||||
assertEquals("0…Kd2", moveLabel(black, "Kd2"))
|
||||
assertEquals("12.Nf3", moveLabel(STANDARD_START.substringBeforeLast(" 1") + " 12", "Nf3"))
|
||||
assertNull(prepWhiteToMove("not a fen"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `frequency and WDL have separate denominators`() {
|
||||
val move = PrepContinuation("e7e5", "e5", games = 4, wins = 2, draws = 0, losses = 1, unknown = 1)
|
||||
assertEquals("40", frequencyPercent(move.games, 10))
|
||||
assertEquals(Triple("67", "0", "33"), outcomePercents(move))
|
||||
assertEquals("<1", frequencyPercent(1, 113))
|
||||
assertEquals("0", frequencyPercent(0, 113))
|
||||
assertEquals(Triple("—", "—", "—"), outcomePercents(move.copy(wins = 0, losses = 0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `continuations are sorted by games then SAN without hiding rare moves`() {
|
||||
val position = PrepPosition(
|
||||
games = 5,
|
||||
continuations = listOf(
|
||||
PrepContinuation("g1f3", "Nf3", 1, 1, 0, 0),
|
||||
PrepContinuation("e2e4", "e4", 3, 1, 1, 1),
|
||||
PrepContinuation("d2d4", "d4", 1, 0, 1, 0),
|
||||
),
|
||||
)
|
||||
assertEquals(listOf("e4", "Nf3", "d4"), sortedContinuations(position).map { it.san })
|
||||
}
|
||||
|
||||
private fun line(vararg moves: String): PrepLineState = PrepLineState(
|
||||
startFen = STANDARD_START,
|
||||
rootFen = STANDARD_START,
|
||||
steps = moves.mapIndexed { i, uci -> step(uci, i + 1, uci.take(4)) },
|
||||
cursor = moves.size,
|
||||
)
|
||||
|
||||
private fun step(uci: String, node: Int, san: String) = PrepLineStep(
|
||||
node = node,
|
||||
uci = uci,
|
||||
san = san,
|
||||
moveNumber = (node + 1) / 2,
|
||||
white = node % 2 == 1,
|
||||
fen = STANDARD_START,
|
||||
from = uci.take(2),
|
||||
to = uci.substring(2, 4),
|
||||
)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue