Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8891e2a081 | ||
|
|
06e02da33a | ||
|
|
52b0cb43c6 |
@@ -21,11 +21,9 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="assets/screenshots/5-move-count.png" width="160" alt="Make your next move count">
|
<img src="assets/screenshots/1-play-learn-solve-left.png" width="160" alt="Play, learn, solve"><img src="assets/screenshots/2-play-learn-solve-right.png" width="160" alt="Home screen">
|
||||||
<img src="assets/screenshots/4-home.png" width="160" alt="Home screen">
|
<img src="assets/screenshots/3-play-ai-or-a-friend.png" width="160" alt="Play AI or a friend">
|
||||||
<img src="assets/screenshots/1-friendly-matches.png" width="160" alt="From solo games to friendly matches">
|
<img src="assets/screenshots/4-puzzles.png" width="160" alt="Puzzles for your rating">
|
||||||
<img src="assets/screenshots/3-play-together.png" width="160" alt="Play together">
|
|
||||||
<img src="assets/screenshots/2-keep-growing.png" width="160" alt="Keep growing">
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
> [!TIP]
|
> [!TIP]
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
applicationId = "cc.skysparkle.matewave"
|
applicationId = "cc.skysparkle.matewave"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 4
|
versionCode = 5
|
||||||
versionName = "1.0.46"
|
versionName = "1.0.47"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
@@ -34,6 +34,15 @@ android {
|
|||||||
compose = true
|
compose = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
androidResources {
|
||||||
|
// The app's languages, plus the regional variants libraries ship for them.
|
||||||
|
localeFilters += listOf(
|
||||||
|
"en", "en-rAU", "en-rCA", "en-rGB", "en-rIN",
|
||||||
|
"ru", "de", "ja", "lt",
|
||||||
|
"zh", "zh-rCN", "zh-rHK", "zh-rTW"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
testOptions {
|
testOptions {
|
||||||
unitTests.isReturnDefaultValues = true
|
unitTests.isReturnDefaultValues = true
|
||||||
}
|
}
|
||||||
@@ -62,6 +71,20 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
androidComponents {
|
||||||
|
// Release APKs leave out files only build and debug tools read: library version markers,
|
||||||
|
// Kotlin reflection metadata and the coroutines debug agent.
|
||||||
|
onVariants(selector().withBuildType("release")) { variant ->
|
||||||
|
variant.packaging.resources.excludes.addAll(
|
||||||
|
"/META-INF/*.version",
|
||||||
|
"/META-INF/*.kotlin_module",
|
||||||
|
"/kotlin/**",
|
||||||
|
"/kotlin-tooling-metadata.json",
|
||||||
|
"/DebugProbesKt.bin"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
|
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
|
||||||
implementation("androidx.compose.material3:material3")
|
implementation("androidx.compose.material3:material3")
|
||||||
|
|||||||
@@ -25,7 +25,6 @@
|
|||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
|
||||||
|
|
||||||
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
|
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
|
||||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||||
|
|||||||
@@ -69,6 +69,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
val appContext = applicationContext
|
val appContext = applicationContext
|
||||||
kotlin.concurrent.thread(name = "warmup", isDaemon = true) {
|
kotlin.concurrent.thread(name = "warmup", isDaemon = true) {
|
||||||
runCatching { cc.skysparkle.matewave.data.FriendsStore.preload() }
|
runCatching { cc.skysparkle.matewave.data.FriendsStore.preload() }
|
||||||
|
// Decoded here, the pieces are ready before the first board is shown.
|
||||||
|
runCatching { cc.skysparkle.matewave.ui.components.PieceImages.get(appContext) }
|
||||||
runCatching { cc.skysparkle.matewave.puzzles.PuzzleRepository.load(appContext) }
|
runCatching { cc.skysparkle.matewave.puzzles.PuzzleRepository.load(appContext) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,5 +19,18 @@ class MatewaveApp : Application() {
|
|||||||
Stats.init(this)
|
Stats.init(this)
|
||||||
GameSaveStore.init(this)
|
GameSaveStore.init(this)
|
||||||
Haptics.init(this)
|
Haptics.init(this)
|
||||||
|
|
||||||
|
// Settings files load on a background thread from first use; start them now, so the
|
||||||
|
// first screen finds them in memory instead of waiting for the disk.
|
||||||
|
for (name in EARLY_PREFS) getSharedPreferences(name, MODE_PRIVATE)
|
||||||
|
GameSaveStore.preload()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
/** Settings the home screen and its view models read while starting. */
|
||||||
|
val EARLY_PREFS = arrayOf(
|
||||||
|
"chess_profile_prefs", "chess_friends_prefs", "chess_stats_prefs", "chess_sound_prefs",
|
||||||
|
"last_game_setup", "presence_settings", "opening_srs"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import cc.skysparkle.matewave.engine.ChessEngine
|
|||||||
import cc.skysparkle.matewave.engine.Move
|
import cc.skysparkle.matewave.engine.Move
|
||||||
import cc.skysparkle.matewave.engine.Notation
|
import cc.skysparkle.matewave.engine.Notation
|
||||||
import cc.skysparkle.matewave.engine.PieceColor
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
import cc.skysparkle.matewave.engine.PieceType
|
import cc.skysparkle.matewave.engine.Position
|
||||||
|
|
||||||
enum class AiDifficulty(val maxDepth: Int, val timeBudgetMs: Long, val noiseCp: Int) {
|
enum class AiDifficulty(val maxDepth: Int, val timeBudgetMs: Long, val noiseCp: Int) {
|
||||||
EASY(2, 400, 150),
|
EASY(2, 400, 150),
|
||||||
@@ -19,16 +19,13 @@ enum class AiDifficulty(val maxDepth: Int, val timeBudgetMs: Long, val noiseCp:
|
|||||||
* quiescence search over captures. The time budget per move is derived from the
|
* quiescence search over captures. The time budget per move is derived from the
|
||||||
* remaining clock, and lower difficulty levels add Gaussian noise at the root so the
|
* remaining clock, and lower difficulty levels add Gaussian noise at the root so the
|
||||||
* AI does not play the same game every time (mates are never randomized away).
|
* AI does not play the same game every time (mates are never randomized away).
|
||||||
|
*
|
||||||
|
* The search makes and takes back moves on one [Position] and keeps moves in reused int
|
||||||
|
* buffers, so it allocates nothing per node.
|
||||||
*/
|
*/
|
||||||
object ChessAI {
|
object ChessAI {
|
||||||
private fun valueOf(type: PieceType): Int = when (type) {
|
/** Piece values by [Position] piece type: pawn, knight, bishop, rook, queen, king. */
|
||||||
PieceType.PAWN -> 100
|
private val VALUE = intArrayOf(0, 100, 320, 330, 500, 900, 20000)
|
||||||
PieceType.KNIGHT -> 320
|
|
||||||
PieceType.BISHOP -> 330
|
|
||||||
PieceType.ROOK -> 500
|
|
||||||
PieceType.QUEEN -> 900
|
|
||||||
PieceType.KING -> 20000
|
|
||||||
}
|
|
||||||
|
|
||||||
private const val MATE = 100_000
|
private const val MATE = 100_000
|
||||||
|
|
||||||
@@ -109,139 +106,225 @@ object ChessAI {
|
|||||||
-50, -40, -30, -20, -20, -30, -40, -50
|
-50, -40, -30, -20, -20, -30, -40, -50
|
||||||
)
|
)
|
||||||
|
|
||||||
internal fun evaluate(board: Board): Int {
|
// Material plus table bonus per piece code and square, signed from White's side. Kings are
|
||||||
var nonPawnMaterial = 0
|
// kept apart because their table depends on the phase.
|
||||||
for (sq in 0 until 64) {
|
private val PIECE_SQUARE = IntArray(16 * 64)
|
||||||
val p = board.squares[sq] ?: continue
|
private val KING_MIDDLE = IntArray(16 * 64)
|
||||||
if (p.type != PieceType.PAWN && p.type != PieceType.KING) nonPawnMaterial += valueOf(p.type)
|
private val KING_END = IntArray(16 * 64)
|
||||||
}
|
private val NON_PAWN_VALUE = IntArray(16)
|
||||||
val endgame = nonPawnMaterial <= 1_300
|
|
||||||
|
|
||||||
var score = 0
|
init {
|
||||||
for (sq in 0 until 64) {
|
for (color in Position.WHITE..Position.BLACK) for (type in Position.PAWN..Position.KING) {
|
||||||
val piece = board.squares[sq] ?: continue
|
val code = Position.code(type, color)
|
||||||
val white = piece.color == PieceColor.WHITE
|
val sign = if (color == Position.WHITE) 1 else -1
|
||||||
val idx = if (white) sq else sq xor 56
|
if (type != Position.PAWN && type != Position.KING) NON_PAWN_VALUE[code] = VALUE[type]
|
||||||
val positional = when (piece.type) {
|
for (sq in 0 until 64) {
|
||||||
PieceType.PAWN -> pawnTable[idx]
|
val idx = if (color == Position.WHITE) sq else sq xor 56
|
||||||
PieceType.KNIGHT -> knightTable[idx]
|
val i = code * 64 + sq
|
||||||
PieceType.BISHOP -> bishopTable[idx]
|
when (type) {
|
||||||
PieceType.ROOK -> rookTable[idx]
|
Position.PAWN -> PIECE_SQUARE[i] = sign * (VALUE[type] + pawnTable[idx])
|
||||||
PieceType.QUEEN -> queenTable[idx]
|
Position.KNIGHT -> PIECE_SQUARE[i] = sign * (VALUE[type] + knightTable[idx])
|
||||||
PieceType.KING -> if (endgame) kingEndTable[idx] else kingMiddleTable[idx]
|
Position.BISHOP -> PIECE_SQUARE[i] = sign * (VALUE[type] + bishopTable[idx])
|
||||||
|
Position.ROOK -> PIECE_SQUARE[i] = sign * (VALUE[type] + rookTable[idx])
|
||||||
|
Position.QUEEN -> PIECE_SQUARE[i] = sign * (VALUE[type] + queenTable[idx])
|
||||||
|
else -> {
|
||||||
|
KING_MIDDLE[i] = sign * (VALUE[type] + kingMiddleTable[idx])
|
||||||
|
KING_END[i] = sign * (VALUE[type] + kingEndTable[idx])
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
val value = valueOf(piece.type) + positional
|
|
||||||
score += if (white) value else -value
|
|
||||||
}
|
}
|
||||||
return score
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun moveScore(board: Board, m: Move): Int {
|
/** Score from White's side; the endgame king table applies with little non-pawn material. */
|
||||||
|
private fun evaluate(position: Position): Int {
|
||||||
|
val squares = position.squares
|
||||||
var score = 0
|
var score = 0
|
||||||
val victim = board.squares[m.to]
|
var nonPawnMaterial = 0
|
||||||
if (victim != null) {
|
var kingMiddle = 0
|
||||||
val attacker = board.squares[m.from]
|
var kingEnd = 0
|
||||||
score = valueOf(victim.type) * 16 - (if (attacker != null) valueOf(attacker.type) / 100 else 0)
|
for (sq in 0 until 64) {
|
||||||
} else if (m.isEnPassant) {
|
val code = squares[sq]
|
||||||
score = valueOf(PieceType.PAWN) * 16
|
if (code == 0) continue
|
||||||
|
val i = code * 64 + sq
|
||||||
|
if (Position.typeOf(code) == Position.KING) {
|
||||||
|
kingMiddle += KING_MIDDLE[i]
|
||||||
|
kingEnd += KING_END[i]
|
||||||
|
} else {
|
||||||
|
score += PIECE_SQUARE[i]
|
||||||
|
nonPawnMaterial += NON_PAWN_VALUE[code]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (m.promotion == PieceType.QUEEN) score += 800
|
return score + if (nonPawnMaterial <= 1_300) kingEnd else kingMiddle
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun moveScore(squares: IntArray, move: Int): Int {
|
||||||
|
var score = 0
|
||||||
|
val victim = squares[Position.moveTo(move)]
|
||||||
|
if (victim != 0) {
|
||||||
|
val attacker = squares[Position.moveFrom(move)]
|
||||||
|
score = VALUE[Position.typeOf(victim)] * 16 -
|
||||||
|
(if (attacker != 0) VALUE[Position.typeOf(attacker)] / 100 else 0)
|
||||||
|
} else if (Position.isEnPassant(move)) {
|
||||||
|
score = VALUE[Position.PAWN] * 16
|
||||||
|
}
|
||||||
|
if (Position.promotionOf(move) == Position.QUEEN) score += 800
|
||||||
return score
|
return score
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun orderMoves(board: Board, moves: List<Move>): List<Move> =
|
private class Search(
|
||||||
moves.sortedByDescending { m -> moveScore(board, m) }
|
private val position: Position,
|
||||||
|
private val deadline: Long,
|
||||||
internal fun isTactical(board: Board, m: Move): Boolean =
|
private val history: Set<String>,
|
||||||
board.squares[m.to] != null || m.isEnPassant || m.promotion != null
|
/** Sorted [Position.keyHash] values of [history]. */
|
||||||
|
private val historyHashes: LongArray,
|
||||||
private class Search(private val deadline: Long, val history: Set<String>) {
|
private val isCancelled: () -> Boolean
|
||||||
|
) {
|
||||||
private var nodes = 0
|
private var nodes = 0
|
||||||
var timedOut = false
|
var timedOut = false
|
||||||
private set
|
private set
|
||||||
|
|
||||||
fun timeUp(): Boolean {
|
// Move stack: each node uses the slots from [top] on and frees them when it returns.
|
||||||
|
private var moves = IntArray(Position.MAX_MOVES * 16)
|
||||||
|
private var scores = IntArray(Position.MAX_MOVES * 16)
|
||||||
|
private var top = 0
|
||||||
|
|
||||||
|
private fun timeUp(): Boolean {
|
||||||
if (timedOut) return true
|
if (timedOut) return true
|
||||||
nodes++
|
nodes++
|
||||||
if ((nodes and 1023) == 0 && System.currentTimeMillis() >= deadline) timedOut = true
|
if ((nodes and 1023) == 0 && (System.currentTimeMillis() >= deadline || isCancelled())) timedOut = true
|
||||||
return timedOut
|
return timedOut
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun quiesce(
|
/**
|
||||||
board: Board, alphaIn: Int, betaIn: Int, maximizing: Boolean, qDepth: Int, search: Search
|
* Generates the moves from [start] and orders them by [moveScore], best first and stable,
|
||||||
): Int {
|
* as sorting the list of legal moves would.
|
||||||
val standPat = evaluate(board)
|
*/
|
||||||
if (search.timeUp() || qDepth == 0) return standPat
|
private fun generateOrdered(start: Int, tacticalOnly: Boolean): Int {
|
||||||
var alpha = alphaIn
|
if (start + Position.MAX_MOVES > moves.size) {
|
||||||
var beta = betaIn
|
moves = moves.copyOf(moves.size * 2)
|
||||||
if (maximizing) {
|
scores = scores.copyOf(scores.size * 2)
|
||||||
if (standPat >= beta) return standPat
|
}
|
||||||
if (standPat > alpha) alpha = standPat
|
val moves = moves
|
||||||
} else {
|
val scores = scores
|
||||||
if (standPat <= alpha) return standPat
|
val end = position.generate(moves, start, tacticalOnly)
|
||||||
if (standPat < beta) beta = standPat
|
for (i in start until end) scores[i] = moveScore(position.squares, moves[i])
|
||||||
|
for (i in start + 1 until end) {
|
||||||
|
val move = moves[i]
|
||||||
|
val score = scores[i]
|
||||||
|
var j = i - 1
|
||||||
|
while (j >= start && scores[j] < score) {
|
||||||
|
moves[j + 1] = moves[j]
|
||||||
|
scores[j + 1] = scores[j]
|
||||||
|
j--
|
||||||
|
}
|
||||||
|
moves[j + 1] = move
|
||||||
|
scores[j + 1] = score
|
||||||
|
}
|
||||||
|
return end
|
||||||
}
|
}
|
||||||
val captures = ChessEngine.legalMoves(board).filter { isTactical(board, it) }
|
|
||||||
if (captures.isEmpty()) return standPat
|
/** Whether the position occurred in the game before the search started. */
|
||||||
var best = standPat
|
private fun isRepetition(): Boolean {
|
||||||
for (m in orderMoves(board, captures)) {
|
if (historyHashes.isEmpty() || historyHashes.binarySearch(position.keyHash()) < 0) return false
|
||||||
val value = quiesce(ChessEngine.applyMove(board, m), alpha, beta, !maximizing, qDepth - 1, search)
|
return Notation.positionKey(position.toBoard()) in history
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun quiesce(alphaIn: Int, betaIn: Int, maximizing: Boolean, qDepth: Int): Int {
|
||||||
|
val standPat = evaluate(position)
|
||||||
|
if (timeUp() || qDepth == 0) return standPat
|
||||||
|
var alpha = alphaIn
|
||||||
|
var beta = betaIn
|
||||||
if (maximizing) {
|
if (maximizing) {
|
||||||
if (value > best) best = value
|
if (standPat >= beta) return standPat
|
||||||
if (value > alpha) alpha = value
|
if (standPat > alpha) alpha = standPat
|
||||||
} else {
|
} else {
|
||||||
if (value < best) best = value
|
if (standPat <= alpha) return standPat
|
||||||
if (value < beta) beta = value
|
if (standPat < beta) beta = standPat
|
||||||
}
|
}
|
||||||
if (beta <= alpha || search.timedOut) break
|
val start = top
|
||||||
|
val end = generateOrdered(start, tacticalOnly = true)
|
||||||
|
top = end
|
||||||
|
var best = standPat
|
||||||
|
for (i in start until end) {
|
||||||
|
val move = moves[i]
|
||||||
|
position.make(move)
|
||||||
|
if (!position.moverKingSafe()) {
|
||||||
|
position.unmake(move)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val value = quiesce(alpha, beta, !maximizing, qDepth - 1)
|
||||||
|
position.unmake(move)
|
||||||
|
if (maximizing) {
|
||||||
|
if (value > best) best = value
|
||||||
|
if (value > alpha) alpha = value
|
||||||
|
} else {
|
||||||
|
if (value < best) best = value
|
||||||
|
if (value < beta) beta = value
|
||||||
|
}
|
||||||
|
if (beta <= alpha || timedOut) break
|
||||||
|
}
|
||||||
|
top = start
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
fun minimax(depth: Int, alphaIn: Int, betaIn: Int, maximizing: Boolean, ply: Int): Int {
|
||||||
|
if (timeUp()) return evaluate(position)
|
||||||
|
var alpha = alphaIn
|
||||||
|
var beta = betaIn
|
||||||
|
|
||||||
|
if (ply in 1..2 && isRepetition()) return 0
|
||||||
|
|
||||||
|
if (position.halfmove >= 100 || position.isDeadPosition()) return 0
|
||||||
|
|
||||||
|
val inCheck = position.inCheck()
|
||||||
|
if (depth <= 0 && !inCheck) return quiesce(alpha, beta, maximizing, QUIESCENCE_DEPTH)
|
||||||
|
|
||||||
|
val nextDepth = if (depth <= 0) 0 else depth - 1
|
||||||
|
|
||||||
|
val start = top
|
||||||
|
val end = generateOrdered(start, tacticalOnly = false)
|
||||||
|
top = end
|
||||||
|
var legal = 0
|
||||||
|
var best = if (maximizing) Int.MIN_VALUE else Int.MAX_VALUE
|
||||||
|
for (i in start until end) {
|
||||||
|
val move = moves[i]
|
||||||
|
position.make(move)
|
||||||
|
if (!position.moverKingSafe()) {
|
||||||
|
position.unmake(move)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
legal++
|
||||||
|
val value = minimax(nextDepth, alpha, beta, !maximizing, ply + 1)
|
||||||
|
position.unmake(move)
|
||||||
|
if (maximizing) {
|
||||||
|
best = maxOf(best, value)
|
||||||
|
alpha = maxOf(alpha, value)
|
||||||
|
} else {
|
||||||
|
best = minOf(best, value)
|
||||||
|
beta = minOf(beta, value)
|
||||||
|
}
|
||||||
|
if (beta <= alpha || timedOut) break
|
||||||
|
}
|
||||||
|
top = start
|
||||||
|
|
||||||
|
if (legal == 0) {
|
||||||
|
return if (inCheck) {
|
||||||
|
if (maximizing) -MATE + ply else MATE - ply
|
||||||
|
} else 0
|
||||||
|
}
|
||||||
|
return best
|
||||||
}
|
}
|
||||||
return best
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun minimax(
|
private fun hashesOf(history: Set<String>): LongArray {
|
||||||
board: Board, depth: Int, alphaIn: Int, betaIn: Int, maximizing: Boolean, ply: Int, search: Search
|
val hashes = LongArray(history.size)
|
||||||
): Int {
|
var n = 0
|
||||||
if (search.timeUp()) return evaluate(board)
|
for (key in history) {
|
||||||
var alpha = alphaIn
|
val board = runCatching { Board.fromFen(key) }.getOrNull() ?: continue
|
||||||
var beta = betaIn
|
hashes[n++] = Position(board).keyHash()
|
||||||
|
|
||||||
if (ply in 1..2 && Notation.positionKey(board) in search.history) return 0
|
|
||||||
|
|
||||||
if (board.halfmoveClock >= 100 || ChessEngine.isDeadPosition(board)) return 0
|
|
||||||
|
|
||||||
val inCheck = ChessEngine.isInCheck(board, board.sideToMove)
|
|
||||||
if (depth <= 0 && !inCheck) return quiesce(board, alpha, beta, maximizing, QUIESCENCE_DEPTH, search)
|
|
||||||
|
|
||||||
val moves = ChessEngine.legalMoves(board)
|
|
||||||
if (moves.isEmpty()) {
|
|
||||||
return if (inCheck) {
|
|
||||||
if (maximizing) -MATE + ply else MATE - ply
|
|
||||||
} else 0
|
|
||||||
}
|
|
||||||
|
|
||||||
val nextDepth = if (depth <= 0) 0 else depth - 1
|
|
||||||
|
|
||||||
val ordered = orderMoves(board, moves)
|
|
||||||
if (maximizing) {
|
|
||||||
var best = Int.MIN_VALUE
|
|
||||||
for (m in ordered) {
|
|
||||||
val value = minimax(ChessEngine.applyMove(board, m), nextDepth, alpha, beta, false, ply + 1, search)
|
|
||||||
best = maxOf(best, value)
|
|
||||||
alpha = maxOf(alpha, value)
|
|
||||||
if (beta <= alpha || search.timedOut) break
|
|
||||||
}
|
|
||||||
return best
|
|
||||||
} else {
|
|
||||||
var best = Int.MAX_VALUE
|
|
||||||
for (m in ordered) {
|
|
||||||
val value = minimax(ChessEngine.applyMove(board, m), nextDepth, alpha, beta, true, ply + 1, search)
|
|
||||||
best = minOf(best, value)
|
|
||||||
beta = minOf(beta, value)
|
|
||||||
if (beta <= alpha || search.timedOut) break
|
|
||||||
}
|
|
||||||
return best
|
|
||||||
}
|
}
|
||||||
|
return hashes.copyOf(n).also { it.sort() }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun bestMove(
|
fun bestMove(
|
||||||
@@ -250,7 +333,9 @@ object ChessAI {
|
|||||||
history: Set<String> = emptySet(),
|
history: Set<String> = emptySet(),
|
||||||
clockMillis: Long? = null,
|
clockMillis: Long? = null,
|
||||||
incrementMillis: Long = 0L,
|
incrementMillis: Long = 0L,
|
||||||
random: java.util.Random = java.util.Random()
|
random: java.util.Random = java.util.Random(),
|
||||||
|
/** Polled during the search; returning true stops it early. */
|
||||||
|
isCancelled: () -> Boolean = { false }
|
||||||
): Move? {
|
): Move? {
|
||||||
val rootMoves = ChessEngine.legalMoves(board)
|
val rootMoves = ChessEngine.legalMoves(board)
|
||||||
if (rootMoves.isEmpty()) return null
|
if (rootMoves.isEmpty()) return null
|
||||||
@@ -263,9 +348,10 @@ object ChessAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val maximizing = board.sideToMove == PieceColor.WHITE
|
val maximizing = board.sideToMove == PieceColor.WHITE
|
||||||
val search = Search(System.currentTimeMillis() + budget, history)
|
val position = Position(board)
|
||||||
|
val search = Search(position, System.currentTimeMillis() + budget, history, hashesOf(history), isCancelled)
|
||||||
|
|
||||||
var order = orderMoves(board, rootMoves)
|
var order = rootMoves.sortedByDescending { moveScore(position.squares, Position.encode(it)) }
|
||||||
var lastScored: List<Pair<Move, Int>> = emptyList()
|
var lastScored: List<Pair<Move, Int>> = emptyList()
|
||||||
|
|
||||||
var depth = 1
|
var depth = 1
|
||||||
@@ -278,11 +364,13 @@ object ChessAI {
|
|||||||
var completed = true
|
var completed = true
|
||||||
|
|
||||||
for (m in order) {
|
for (m in order) {
|
||||||
val next = ChessEngine.applyMove(board, m)
|
val move = Position.encode(m)
|
||||||
|
position.make(move)
|
||||||
|
|
||||||
val a = if (difficulty.noiseCp > 0) Int.MIN_VALUE else alpha
|
val a = if (difficulty.noiseCp > 0) Int.MIN_VALUE else alpha
|
||||||
val b = if (difficulty.noiseCp > 0) Int.MAX_VALUE else beta
|
val b = if (difficulty.noiseCp > 0) Int.MAX_VALUE else beta
|
||||||
val value = minimax(next, depth - 1, a, b, !maximizing, 1, search)
|
val value = search.minimax(depth - 1, a, b, !maximizing, 1)
|
||||||
|
position.unmake(move)
|
||||||
|
|
||||||
if (search.timedOut) { completed = false; break }
|
if (search.timedOut) { completed = false; break }
|
||||||
scored.add(m to value)
|
scored.add(m to value)
|
||||||
|
|||||||
@@ -143,7 +143,8 @@ object SoundManager {
|
|||||||
musicEnabled = prefs.getBoolean(KEY_MUSIC, false)
|
musicEnabled = prefs.getBoolean(KEY_MUSIC, false)
|
||||||
sfxEnabled = prefs.getBoolean(KEY_SFX, true)
|
sfxEnabled = prefs.getBoolean(KEY_SFX, true)
|
||||||
|
|
||||||
ensureSoundPool(ctx)
|
// Building the pool and opening the sounds takes a while: do it off the main thread.
|
||||||
|
kotlin.concurrent.thread(name = "sound-pool", isDaemon = true) { soundPool = createSoundPool(ctx) }
|
||||||
|
|
||||||
if (musicEnabled) {
|
if (musicEnabled) {
|
||||||
mainHandler.postDelayed({ if (musicEnabled) startRadio() }, RADIO_START_DELAY_MS)
|
mainHandler.postDelayed({ if (musicEnabled) startRadio() }, RADIO_START_DELAY_MS)
|
||||||
@@ -446,12 +447,12 @@ object SoundManager {
|
|||||||
?.putBoolean(KEY_SFX, enabled)?.apply()
|
?.putBoolean(KEY_SFX, enabled)?.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
private var soundPool: SoundPool? = null
|
/** Set once, after [sfxSoundIds] is filled. */
|
||||||
|
@Volatile private var soundPool: SoundPool? = null
|
||||||
private val sfxSoundIds = HashMap<Int, Int>()
|
private val sfxSoundIds = HashMap<Int, Int>()
|
||||||
private val sfxLoaded = HashSet<Int>()
|
private val sfxLoaded = HashSet<Int>()
|
||||||
|
|
||||||
private fun ensureSoundPool(ctx: Context): SoundPool {
|
private fun createSoundPool(ctx: Context): SoundPool {
|
||||||
soundPool?.let { return it }
|
|
||||||
val attributes = AudioAttributes.Builder()
|
val attributes = AudioAttributes.Builder()
|
||||||
.setUsage(AudioAttributes.USAGE_GAME)
|
.setUsage(AudioAttributes.USAGE_GAME)
|
||||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||||
@@ -467,14 +468,13 @@ object SoundManager {
|
|||||||
)) {
|
)) {
|
||||||
sfxSoundIds[resId] = pool.load(ctx, resId, 1)
|
sfxSoundIds[resId] = pool.load(ctx, resId, 1)
|
||||||
}
|
}
|
||||||
soundPool = pool
|
|
||||||
return pool
|
return pool
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun playSfx(resId: Int) {
|
private fun playSfx(resId: Int) {
|
||||||
if (!sfxEnabled) return
|
if (!sfxEnabled) return
|
||||||
val ctx = appContext ?: return
|
// Like a sound still decoding, one asked for before the pool exists is skipped.
|
||||||
val pool = ensureSoundPool(ctx)
|
val pool = soundPool ?: return
|
||||||
val soundId = sfxSoundIds[resId] ?: return
|
val soundId = sfxSoundIds[resId] ?: return
|
||||||
val ready = synchronized(sfxLoaded) { soundId in sfxLoaded }
|
val ready = synchronized(sfxLoaded) { soundId in sfxLoaded }
|
||||||
if (ready) pool.play(soundId, 1f, 1f, 1, 0, 1f)
|
if (ready) pool.play(soundId, 1f, 1f, 1, 0, 1f)
|
||||||
|
|||||||
@@ -106,13 +106,6 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti
|
|||||||
publish()
|
publish()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun pause() {
|
|
||||||
tickJob?.cancel()
|
|
||||||
account()
|
|
||||||
running = null
|
|
||||||
publish()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun stop() {
|
fun stop() {
|
||||||
tickJob?.cancel()
|
tickJob?.cancel()
|
||||||
account()
|
account()
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import android.content.ContentValues
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.database.sqlite.SQLiteDatabase
|
import android.database.sqlite.SQLiteDatabase
|
||||||
import android.database.sqlite.SQLiteOpenHelper
|
import android.database.sqlite.SQLiteOpenHelper
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue
|
||||||
|
import java.util.concurrent.ThreadPoolExecutor
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
data class SavedGame(
|
data class SavedGame(
|
||||||
val fen: String,
|
val fen: String,
|
||||||
@@ -13,11 +16,15 @@ data class SavedGame(
|
|||||||
val incrementSeconds: Int,
|
val incrementSeconds: Int,
|
||||||
val whiteMillis: Long = -1,
|
val whiteMillis: Long = -1,
|
||||||
val blackMillis: Long = -1,
|
val blackMillis: Long = -1,
|
||||||
/** Moves from the standard start in UCI, space separated; empty for saves made before version 3. */
|
/** Moves from the standard start in UCI, space separated; empty for a game that started elsewhere. */
|
||||||
val movesUci: String = ""
|
val movesUci: String = ""
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Persists the unfinished game against the AI: moves, position and remaining clock time. */
|
/**
|
||||||
|
* Persists the unfinished game against the AI: moves, position and remaining clock time.
|
||||||
|
* The game is kept in memory once read or saved; the database is written in the background,
|
||||||
|
* in order, so moves never wait for the disk.
|
||||||
|
*/
|
||||||
object GameSaveStore {
|
object GameSaveStore {
|
||||||
private const val DB_NAME = "chess_save.db"
|
private const val DB_NAME = "chess_save.db"
|
||||||
private const val DB_VERSION = 3
|
private const val DB_VERSION = 3
|
||||||
@@ -25,12 +32,30 @@ object GameSaveStore {
|
|||||||
|
|
||||||
@Volatile private var helper: DbHelper? = null
|
@Volatile private var helper: DbHelper? = null
|
||||||
|
|
||||||
|
/** One thread at most, so writes keep their order; it ends when idle. */
|
||||||
|
private val io = ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, LinkedBlockingQueue()) { task ->
|
||||||
|
Thread(task, "game-save").apply { isDaemon = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
private val lock = Any()
|
||||||
|
/** Whether [current] matches what is (or is about to be) on disk. */
|
||||||
|
private var known = false
|
||||||
|
private var current: SavedGame? = null
|
||||||
|
|
||||||
fun init(context: Context) {
|
fun init(context: Context) {
|
||||||
if (helper == null) synchronized(this) {
|
if (helper == null) synchronized(this) {
|
||||||
if (helper == null) helper = DbHelper(context.applicationContext)
|
if (helper == null) helper = DbHelper(context.applicationContext)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Reads the save in the background, so the first screen finds it in memory. */
|
||||||
|
fun preload() {
|
||||||
|
io.execute { load() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether [load] would return without reading the database. */
|
||||||
|
fun isLoaded(): Boolean = synchronized(lock) { known }
|
||||||
|
|
||||||
private class DbHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
|
private class DbHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
|
||||||
override fun onCreate(db: SQLiteDatabase) {
|
override fun onCreate(db: SQLiteDatabase) {
|
||||||
db.execSQL(
|
db.execSQL(
|
||||||
@@ -50,18 +75,19 @@ object GameSaveStore {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Saves from older versions are not carried over.
|
||||||
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
|
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
|
||||||
if (oldVersion < 2) {
|
db.execSQL("DROP TABLE IF EXISTS $TABLE")
|
||||||
db.execSQL("ALTER TABLE $TABLE ADD COLUMN white_ms INTEGER NOT NULL DEFAULT -1")
|
onCreate(db)
|
||||||
db.execSQL("ALTER TABLE $TABLE ADD COLUMN black_ms INTEGER NOT NULL DEFAULT -1")
|
|
||||||
}
|
|
||||||
if (oldVersion < 3) {
|
|
||||||
db.execSQL("ALTER TABLE $TABLE ADD COLUMN moves TEXT NOT NULL DEFAULT ''")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun save(game: SavedGame) {
|
fun save(game: SavedGame) {
|
||||||
|
synchronized(lock) { current = game; known = true }
|
||||||
|
io.execute { write(game) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun write(game: SavedGame) {
|
||||||
val db = runCatching { helper?.writableDatabase }.getOrNull() ?: return
|
val db = runCatching { helper?.writableDatabase }.getOrNull() ?: return
|
||||||
val values = ContentValues().apply {
|
val values = ContentValues().apply {
|
||||||
put("id", 1)
|
put("id", 1)
|
||||||
@@ -77,7 +103,21 @@ object GameSaveStore {
|
|||||||
runCatching { db.insertWithOnConflict(TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE) }
|
runCatching { db.insertWithOnConflict(TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The saved game; the first call reads the database, so make it off the main thread. */
|
||||||
fun load(): SavedGame? {
|
fun load(): SavedGame? {
|
||||||
|
synchronized(lock) { if (known) return current }
|
||||||
|
val read = read()
|
||||||
|
synchronized(lock) {
|
||||||
|
// A save or clear made while reading is newer than what was read.
|
||||||
|
if (!known) {
|
||||||
|
current = read
|
||||||
|
known = true
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun read(): SavedGame? {
|
||||||
val db = runCatching { helper?.readableDatabase }.getOrNull() ?: return null
|
val db = runCatching { helper?.readableDatabase }.getOrNull() ?: return null
|
||||||
return runCatching {
|
return runCatching {
|
||||||
db.query(TABLE, null, "id = 1", null, null, null, null).use { cursor ->
|
db.query(TABLE, null, "id = 1", null, null, null, null).use { cursor ->
|
||||||
@@ -97,6 +137,7 @@ object GameSaveStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun clear() {
|
fun clear() {
|
||||||
runCatching { helper?.writableDatabase?.delete(TABLE, "id = 1", null) }
|
synchronized(lock) { current = null; known = true }
|
||||||
|
io.execute { runCatching { helper?.writableDatabase?.delete(TABLE, "id = 1", null) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,8 +66,6 @@ object ProfileStore {
|
|||||||
prefs()?.edit()?.putString(KEY_AVATAR, base64)?.apply()
|
prefs()?.edit()?.putString(KEY_AVATAR, base64)?.apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun resetAvatarToDefault() = setAvatar(null)
|
|
||||||
|
|
||||||
fun setBackground(base64: String?) {
|
fun setBackground(base64: String?) {
|
||||||
prefs()?.edit()?.putString(KEY_BACKGROUND, base64)?.apply()
|
prefs()?.edit()?.putString(KEY_BACKGROUND, base64)?.apply()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ data class Board(
|
|||||||
) {
|
) {
|
||||||
fun pieceAt(sq: Int): Piece? = squares[sq]
|
fun pieceAt(sq: Int): Piece? = squares[sq]
|
||||||
|
|
||||||
fun deepCopySquares(): Array<Piece?> = squares.copyOf()
|
|
||||||
|
|
||||||
fun kingSquare(color: PieceColor): Int {
|
fun kingSquare(color: PieceColor): Int {
|
||||||
for (i in 0 until 64) {
|
for (i in 0 until 64) {
|
||||||
val p = squares[i]
|
val p = squares[i]
|
||||||
|
|||||||
@@ -13,198 +13,8 @@ enum class GameStatus {
|
|||||||
* repetition, insufficient material).
|
* repetition, insufficient material).
|
||||||
*/
|
*/
|
||||||
object ChessEngine {
|
object ChessEngine {
|
||||||
private fun file(sq: Int) = sq % 8
|
|
||||||
private fun rank(sq: Int) = sq / 8
|
|
||||||
private fun inBounds(f: Int, r: Int) = f in 0..7 && r in 0..7
|
|
||||||
private fun sq(f: Int, r: Int) = r * 8 + f
|
|
||||||
|
|
||||||
private val KNIGHT_DF = intArrayOf(1, 2, 2, 1, -1, -2, -2, -1)
|
|
||||||
private val KNIGHT_DR = intArrayOf(2, 1, -1, -2, -2, -1, 1, 2)
|
|
||||||
private val DIAG_DF = intArrayOf(1, 1, -1, -1)
|
|
||||||
private val DIAG_DR = intArrayOf(1, -1, 1, -1)
|
|
||||||
private val ORTHO_DF = intArrayOf(1, -1, 0, 0)
|
|
||||||
private val ORTHO_DR = intArrayOf(0, 0, 1, -1)
|
|
||||||
private val ALL_DF = intArrayOf(1, -1, 0, 0, 1, 1, -1, -1)
|
|
||||||
private val ALL_DR = intArrayOf(0, 0, 1, -1, 1, -1, 1, -1)
|
|
||||||
private val PAWN_DF = intArrayOf(-1, 1)
|
|
||||||
|
|
||||||
private fun pseudoLegalMoves(board: Board): List<Move> {
|
|
||||||
val moves = ArrayList<Move>(48)
|
|
||||||
for (from in 0 until 64) {
|
|
||||||
val piece = board.squares[from] ?: continue
|
|
||||||
if (piece.color != board.sideToMove) continue
|
|
||||||
when (piece.type) {
|
|
||||||
PieceType.PAWN -> generatePawnMoves(board, from, piece, moves)
|
|
||||||
PieceType.KNIGHT -> generateKnightMoves(board, from, piece, moves)
|
|
||||||
PieceType.BISHOP -> generateSlidingMoves(board, from, piece, moves, DIAG_DF, DIAG_DR)
|
|
||||||
PieceType.ROOK -> generateSlidingMoves(board, from, piece, moves, ORTHO_DF, ORTHO_DR)
|
|
||||||
PieceType.QUEEN -> generateSlidingMoves(board, from, piece, moves, ALL_DF, ALL_DR)
|
|
||||||
PieceType.KING -> generateKingMoves(board, from, piece, moves)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return moves
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun generatePawnMoves(board: Board, from: Int, piece: Piece, out: MutableList<Move>) {
|
|
||||||
val dir = if (piece.color == PieceColor.WHITE) 1 else -1
|
|
||||||
val startRank = if (piece.color == PieceColor.WHITE) 1 else 6
|
|
||||||
val promoRank = if (piece.color == PieceColor.WHITE) 7 else 0
|
|
||||||
val f = file(from); val r = rank(from)
|
|
||||||
|
|
||||||
val oneR = r + dir
|
|
||||||
if (inBounds(f, oneR) && board.squares[sq(f, oneR)] == null) {
|
|
||||||
addPawnMoveOrPromotion(from, sq(f, oneR), oneR, promoRank, out)
|
|
||||||
val twoR = r + 2 * dir
|
|
||||||
if (r == startRank && board.squares[sq(f, twoR)] == null) {
|
|
||||||
out.add(Move(from, sq(f, twoR)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (df in PAWN_DF) {
|
|
||||||
val nf = f + df; val nr = r + dir
|
|
||||||
if (!inBounds(nf, nr)) continue
|
|
||||||
val target = sq(nf, nr)
|
|
||||||
val targetPiece = board.squares[target]
|
|
||||||
if (targetPiece != null && targetPiece.color != piece.color) {
|
|
||||||
addPawnMoveOrPromotion(from, target, nr, promoRank, out)
|
|
||||||
} else if (target == board.enPassantTarget) {
|
|
||||||
out.add(Move(from, target, isEnPassant = true))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun addPawnMoveOrPromotion(from: Int, to: Int, toRank: Int, promoRank: Int, out: MutableList<Move>) {
|
|
||||||
if (toRank == promoRank) {
|
|
||||||
out.add(Move(from, to, promotion = PieceType.QUEEN))
|
|
||||||
out.add(Move(from, to, promotion = PieceType.ROOK))
|
|
||||||
out.add(Move(from, to, promotion = PieceType.BISHOP))
|
|
||||||
out.add(Move(from, to, promotion = PieceType.KNIGHT))
|
|
||||||
} else {
|
|
||||||
out.add(Move(from, to))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun generateKnightMoves(board: Board, from: Int, piece: Piece, out: MutableList<Move>) {
|
|
||||||
val f = file(from); val r = rank(from)
|
|
||||||
for (i in 0 until 8) {
|
|
||||||
val nf = f + KNIGHT_DF[i]; val nr = r + KNIGHT_DR[i]
|
|
||||||
if (!inBounds(nf, nr)) continue
|
|
||||||
val target = sq(nf, nr)
|
|
||||||
val targetPiece = board.squares[target]
|
|
||||||
if (targetPiece == null || targetPiece.color != piece.color) out.add(Move(from, target))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun generateSlidingMoves(
|
|
||||||
board: Board, from: Int, piece: Piece, out: MutableList<Move>, dfs: IntArray, drs: IntArray
|
|
||||||
) {
|
|
||||||
val f = file(from); val r = rank(from)
|
|
||||||
for (i in dfs.indices) {
|
|
||||||
val df = dfs[i]; val dr = drs[i]
|
|
||||||
var nf = f + df; var nr = r + dr
|
|
||||||
while (inBounds(nf, nr)) {
|
|
||||||
val target = sq(nf, nr)
|
|
||||||
val targetPiece = board.squares[target]
|
|
||||||
if (targetPiece == null) {
|
|
||||||
out.add(Move(from, target))
|
|
||||||
} else {
|
|
||||||
if (targetPiece.color != piece.color) out.add(Move(from, target))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
nf += df; nr += dr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun generateKingMoves(board: Board, from: Int, piece: Piece, out: MutableList<Move>) {
|
|
||||||
val f = file(from); val r = rank(from)
|
|
||||||
for (df in -1..1) for (dr in -1..1) {
|
|
||||||
if (df == 0 && dr == 0) continue
|
|
||||||
val nf = f + df; val nr = r + dr
|
|
||||||
if (!inBounds(nf, nr)) continue
|
|
||||||
val target = sq(nf, nr)
|
|
||||||
val targetPiece = board.squares[target]
|
|
||||||
if (targetPiece == null || targetPiece.color != piece.color) out.add(Move(from, target))
|
|
||||||
}
|
|
||||||
val backRank = if (piece.color == PieceColor.WHITE) 0 else 7
|
|
||||||
if (from == sq(4, backRank)) {
|
|
||||||
val ownRook = Piece(PieceType.ROOK, piece.color)
|
|
||||||
val kingSide = (if (piece.color == PieceColor.WHITE) board.whiteKingSideCastle else board.blackKingSideCastle) &&
|
|
||||||
board.squares[sq(7, backRank)] == ownRook
|
|
||||||
val queenSide = (if (piece.color == PieceColor.WHITE) board.whiteQueenSideCastle else board.blackQueenSideCastle) &&
|
|
||||||
board.squares[sq(0, backRank)] == ownRook
|
|
||||||
val enemy = piece.color.opposite()
|
|
||||||
if (kingSide &&
|
|
||||||
board.squares[sq(5, backRank)] == null && board.squares[sq(6, backRank)] == null &&
|
|
||||||
!isSquareAttacked(board, sq(4, backRank), enemy) &&
|
|
||||||
!isSquareAttacked(board, sq(5, backRank), enemy) &&
|
|
||||||
!isSquareAttacked(board, sq(6, backRank), enemy)
|
|
||||||
) {
|
|
||||||
out.add(Move(from, sq(6, backRank), isCastleKingSide = true))
|
|
||||||
}
|
|
||||||
if (queenSide &&
|
|
||||||
board.squares[sq(3, backRank)] == null && board.squares[sq(2, backRank)] == null && board.squares[sq(1, backRank)] == null &&
|
|
||||||
!isSquareAttacked(board, sq(4, backRank), enemy) &&
|
|
||||||
!isSquareAttacked(board, sq(3, backRank), enemy) &&
|
|
||||||
!isSquareAttacked(board, sq(2, backRank), enemy)
|
|
||||||
) {
|
|
||||||
out.add(Move(from, sq(2, backRank), isCastleQueenSide = true))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isSquareAttacked(board: Board, target: Int, byColor: PieceColor): Boolean =
|
fun isSquareAttacked(board: Board, target: Int, byColor: PieceColor): Boolean =
|
||||||
attacked(board.squares, target, byColor)
|
Position(board).isAttacked(target, byColor.ordinal)
|
||||||
|
|
||||||
private fun attacked(squares: Array<Piece?>, target: Int, byColor: PieceColor): Boolean {
|
|
||||||
val tf = file(target); val tr = rank(target)
|
|
||||||
val pawnDir = if (byColor == PieceColor.WHITE) -1 else 1
|
|
||||||
for (df in PAWN_DF) {
|
|
||||||
val f = tf + df; val r = tr + pawnDir
|
|
||||||
if (inBounds(f, r)) {
|
|
||||||
val p = squares[sq(f, r)]
|
|
||||||
if (p != null && p.color == byColor && p.type == PieceType.PAWN) return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (i in 0 until 8) {
|
|
||||||
val f = tf + KNIGHT_DF[i]; val r = tr + KNIGHT_DR[i]
|
|
||||||
if (inBounds(f, r)) {
|
|
||||||
val p = squares[sq(f, r)]
|
|
||||||
if (p != null && p.color == byColor && p.type == PieceType.KNIGHT) return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (i in 0 until 8) {
|
|
||||||
val f = tf + ALL_DF[i]; val r = tr + ALL_DR[i]
|
|
||||||
if (inBounds(f, r)) {
|
|
||||||
val p = squares[sq(f, r)]
|
|
||||||
if (p != null && p.color == byColor && p.type == PieceType.KING) return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (i in 0 until 4) {
|
|
||||||
val df = DIAG_DF[i]; val dr = DIAG_DR[i]
|
|
||||||
var f = tf + df; var r = tr + dr
|
|
||||||
while (inBounds(f, r)) {
|
|
||||||
val p = squares[sq(f, r)]
|
|
||||||
if (p != null) {
|
|
||||||
if (p.color == byColor && (p.type == PieceType.BISHOP || p.type == PieceType.QUEEN)) return true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
f += df; r += dr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (i in 0 until 4) {
|
|
||||||
val df = ORTHO_DF[i]; val dr = ORTHO_DR[i]
|
|
||||||
var f = tf + df; var r = tr + dr
|
|
||||||
while (inBounds(f, r)) {
|
|
||||||
val p = squares[sq(f, r)]
|
|
||||||
if (p != null) {
|
|
||||||
if (p.color == byColor && (p.type == PieceType.ROOK || p.type == PieceType.QUEEN)) return true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
f += df; r += dr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isInCheck(board: Board, color: PieceColor): Boolean {
|
fun isInCheck(board: Board, color: PieceColor): Boolean {
|
||||||
val kingSq = board.kingSquare(color)
|
val kingSq = board.kingSquare(color)
|
||||||
@@ -212,54 +22,17 @@ object ChessEngine {
|
|||||||
return isSquareAttacked(board, kingSq, color.opposite())
|
return isSquareAttacked(board, kingSq, color.opposite())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Square of the side to move's king while it is in check, for highlighting. */
|
||||||
|
fun checkedKingSquare(board: Board): Int? =
|
||||||
|
if (isInCheck(board, board.sideToMove)) board.kingSquare(board.sideToMove) else null
|
||||||
|
|
||||||
fun legalMoves(board: Board): List<Move> {
|
fun legalMoves(board: Board): List<Move> {
|
||||||
val pseudo = pseudoLegalMoves(board)
|
val position = Position(board)
|
||||||
val side = board.sideToMove
|
val moves = IntArray(Position.MAX_MOVES)
|
||||||
val enemy = side.opposite()
|
val end = position.generate(moves, 0, tacticalOnly = false)
|
||||||
val work = board.squares.copyOf()
|
val result = ArrayList<Move>(end)
|
||||||
val ownKing = board.kingSquare(side)
|
for (i in 0 until end) {
|
||||||
val result = ArrayList<Move>(pseudo.size)
|
if (position.isLegal(moves[i])) result.add(Position.toMove(moves[i]))
|
||||||
for (m in pseudo) {
|
|
||||||
val moving = work[m.from] ?: continue
|
|
||||||
val captured = work[m.to]
|
|
||||||
|
|
||||||
var epIdx = -1
|
|
||||||
var epPiece: Piece? = null
|
|
||||||
if (m.isEnPassant) {
|
|
||||||
val capturedRank = if (moving.color == PieceColor.WHITE) rank(m.to) - 1 else rank(m.to) + 1
|
|
||||||
epIdx = sq(file(m.to), capturedRank)
|
|
||||||
epPiece = work[epIdx]
|
|
||||||
work[epIdx] = null
|
|
||||||
}
|
|
||||||
work[m.to] = if (m.promotion != null) Piece(m.promotion, moving.color) else moving
|
|
||||||
work[m.from] = null
|
|
||||||
|
|
||||||
var rookFrom = -1
|
|
||||||
var rookTo = -1
|
|
||||||
var rook: Piece? = null
|
|
||||||
if (m.isCastleKingSide) {
|
|
||||||
val backRank = rank(m.from); rookFrom = sq(7, backRank); rookTo = sq(5, backRank)
|
|
||||||
} else if (m.isCastleQueenSide) {
|
|
||||||
val backRank = rank(m.from); rookFrom = sq(0, backRank); rookTo = sq(3, backRank)
|
|
||||||
}
|
|
||||||
if (rookFrom >= 0) {
|
|
||||||
rook = work[rookFrom]
|
|
||||||
work[rookTo] = rook
|
|
||||||
work[rookFrom] = null
|
|
||||||
}
|
|
||||||
|
|
||||||
val kingSq = if (moving.type == PieceType.KING) m.to else ownKing
|
|
||||||
val safe = kingSq == -1 || !attacked(work, kingSq, enemy)
|
|
||||||
|
|
||||||
if (rookFrom >= 0) {
|
|
||||||
work[rookFrom] = rook
|
|
||||||
work[rookTo] = null
|
|
||||||
}
|
|
||||||
work[m.from] = moving
|
|
||||||
work[m.to] = captured
|
|
||||||
if (epIdx >= 0) work[epIdx] = epPiece
|
|
||||||
|
|
||||||
if (safe) result.add(m)
|
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -267,60 +40,10 @@ object ChessEngine {
|
|||||||
fun legalMovesFrom(board: Board, from: Int): List<Move> = legalMoves(board).filter { it.from == from }
|
fun legalMovesFrom(board: Board, from: Int): List<Move> = legalMoves(board).filter { it.from == from }
|
||||||
|
|
||||||
fun applyMove(board: Board, move: Move): Board {
|
fun applyMove(board: Board, move: Move): Board {
|
||||||
val squares = board.deepCopySquares()
|
if (board.squares[move.from] == null) return board
|
||||||
val moving = squares[move.from] ?: return board
|
val position = Position(board)
|
||||||
val isPawn = moving.type == PieceType.PAWN
|
position.make(Position.encode(move))
|
||||||
val isCapture = squares[move.to] != null
|
return position.toBoard()
|
||||||
|
|
||||||
if (move.isEnPassant) {
|
|
||||||
val capturedRank = if (moving.color == PieceColor.WHITE) rank(move.to) - 1 else rank(move.to) + 1
|
|
||||||
squares[sq(file(move.to), capturedRank)] = null
|
|
||||||
}
|
|
||||||
|
|
||||||
squares[move.to] = if (move.promotion != null) Piece(move.promotion, moving.color) else moving
|
|
||||||
squares[move.from] = null
|
|
||||||
|
|
||||||
if (move.isCastleKingSide) {
|
|
||||||
val backRank = rank(move.from)
|
|
||||||
squares[sq(5, backRank)] = squares[sq(7, backRank)]
|
|
||||||
squares[sq(7, backRank)] = null
|
|
||||||
}
|
|
||||||
if (move.isCastleQueenSide) {
|
|
||||||
val backRank = rank(move.from)
|
|
||||||
squares[sq(3, backRank)] = squares[sq(0, backRank)]
|
|
||||||
squares[sq(0, backRank)] = null
|
|
||||||
}
|
|
||||||
|
|
||||||
var wk = board.whiteKingSideCastle
|
|
||||||
var wq = board.whiteQueenSideCastle
|
|
||||||
var bk = board.blackKingSideCastle
|
|
||||||
var bq = board.blackQueenSideCastle
|
|
||||||
if (moving.type == PieceType.KING) {
|
|
||||||
if (moving.color == PieceColor.WHITE) { wk = false; wq = false } else { bk = false; bq = false }
|
|
||||||
}
|
|
||||||
if (move.from == sq(0, 0) || move.to == sq(0, 0)) wq = false
|
|
||||||
if (move.from == sq(7, 0) || move.to == sq(7, 0)) wk = false
|
|
||||||
if (move.from == sq(0, 7) || move.to == sq(0, 7)) bq = false
|
|
||||||
if (move.from == sq(7, 7) || move.to == sq(7, 7)) bk = false
|
|
||||||
|
|
||||||
val newEnPassant = if (isPawn && kotlin.math.abs(rank(move.to) - rank(move.from)) == 2) {
|
|
||||||
sq(file(move.from), (rank(move.from) + rank(move.to)) / 2)
|
|
||||||
} else null
|
|
||||||
|
|
||||||
val newHalfmove = if (isPawn || isCapture) 0 else board.halfmoveClock + 1
|
|
||||||
val newFullmove = if (board.sideToMove == PieceColor.BLACK) board.fullmoveNumber + 1 else board.fullmoveNumber
|
|
||||||
|
|
||||||
return Board(
|
|
||||||
squares = squares,
|
|
||||||
sideToMove = board.sideToMove.opposite(),
|
|
||||||
whiteKingSideCastle = wk,
|
|
||||||
whiteQueenSideCastle = wq,
|
|
||||||
blackKingSideCastle = bk,
|
|
||||||
blackQueenSideCastle = bq,
|
|
||||||
enPassantTarget = newEnPassant,
|
|
||||||
halfmoveClock = newHalfmove,
|
|
||||||
fullmoveNumber = newFullmove
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun gameStatus(board: Board, positionHistory: List<String> = emptyList()): GameStatus {
|
fun gameStatus(board: Board, positionHistory: List<String> = emptyList()): GameStatus {
|
||||||
@@ -339,21 +62,7 @@ object ChessEngine {
|
|||||||
* Neither side can ever mate: kings alone, a single minor piece, or only bishops that all
|
* Neither side can ever mate: kings alone, a single minor piece, or only bishops that all
|
||||||
* stand on squares of one colour.
|
* stand on squares of one colour.
|
||||||
*/
|
*/
|
||||||
fun isDeadPosition(board: Board): Boolean {
|
fun isDeadPosition(board: Board): Boolean = Position(board).isDeadPosition()
|
||||||
val minors = ArrayList<Int>(4)
|
|
||||||
for (i in 0 until 64) {
|
|
||||||
val p = board.squares[i] ?: continue
|
|
||||||
when (p.type) {
|
|
||||||
PieceType.KING -> Unit
|
|
||||||
PieceType.BISHOP, PieceType.KNIGHT -> minors.add(i)
|
|
||||||
else -> return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (minors.size <= 1) return true
|
|
||||||
if (minors.any { board.squares[it]?.type != PieceType.BISHOP }) return false
|
|
||||||
val shade = (file(minors[0]) + rank(minors[0])) % 2
|
|
||||||
return minors.all { (file(it) + rank(it)) % 2 == shade }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether [color] has enough material to mate at all. A player whose flag falls loses only if
|
* Whether [color] has enough material to mate at all. A player whose flag falls loses only if
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package cc.skysparkle.matewave.engine
|
|||||||
* (e.g. "Nbd7", "exd6", "e8=Q", "O-O"), which is the key format of the opening data.
|
* (e.g. "Nbd7", "exd6", "e8=Q", "O-O"), which is the key format of the opening data.
|
||||||
*/
|
*/
|
||||||
object Notation {
|
object Notation {
|
||||||
|
private val LOOSE_SAN = Regex("^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])([QRBN])?$")
|
||||||
|
|
||||||
fun isCastle(board: Board, move: Move): Boolean {
|
fun isCastle(board: Board, move: Move): Boolean {
|
||||||
if (move.isCastleKingSide || move.isCastleQueenSide) return true
|
if (move.isCastleKingSide || move.isCastleQueenSide) return true
|
||||||
@@ -69,7 +70,7 @@ object Notation {
|
|||||||
legal.firstOrNull { normalizeSan(toSan(board, it, legal)) == wanted }?.let { return it }
|
legal.firstOrNull { normalizeSan(toSan(board, it, legal)) == wanted }?.let { return it }
|
||||||
|
|
||||||
// Over-disambiguated or loosely written SAN, e.g. "Ngf3" or "e8Q".
|
// Over-disambiguated or loosely written SAN, e.g. "Ngf3" or "e8Q".
|
||||||
val m = Regex("^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])([QRBN])?$").find(wanted) ?: return null
|
val m = LOOSE_SAN.find(wanted) ?: return null
|
||||||
val type = when (m.groupValues[1]) {
|
val type = when (m.groupValues[1]) {
|
||||||
"K" -> PieceType.KING; "Q" -> PieceType.QUEEN; "R" -> PieceType.ROOK
|
"K" -> PieceType.KING; "Q" -> PieceType.QUEEN; "R" -> PieceType.ROOK
|
||||||
"B" -> PieceType.BISHOP; "N" -> PieceType.KNIGHT; else -> PieceType.PAWN
|
"B" -> PieceType.BISHOP; "N" -> PieceType.KNIGHT; else -> PieceType.PAWN
|
||||||
@@ -88,6 +89,15 @@ object Notation {
|
|||||||
}.singleOrNull()
|
}.singleOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The legal move written as [uci]; without a valid promotion letter the first match is taken. */
|
||||||
|
fun fromUci(board: Board, uci: String): Move? {
|
||||||
|
if (uci.length !in 4..5) return null
|
||||||
|
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null
|
||||||
|
if (candidate.from !in 0..63 || candidate.to !in 0..63) return null
|
||||||
|
val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to }
|
||||||
|
return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
/** Position part of a FEN without move counters, used to compare positions. */
|
/** Position part of a FEN without move counters, used to compare positions. */
|
||||||
fun positionKey(board: Board): String =
|
fun positionKey(board: Board): String =
|
||||||
board.toFen().substringBeforeLast(' ').substringBeforeLast(' ')
|
board.toFen().substringBeforeLast(' ').substringBeforeLast(' ')
|
||||||
|
|||||||
@@ -0,0 +1,485 @@
|
|||||||
|
package cc.skysparkle.matewave.engine
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mutable position for move generation and search: pieces are int codes, moves are ints, and
|
||||||
|
* [make]/[unmake] change one position in place instead of copying boards. [ChessEngine] wraps it
|
||||||
|
* for the immutable [Board] API, so the rules exist once.
|
||||||
|
*
|
||||||
|
* Piece code: type (1 pawn .. 6 king) plus 8 for black, 0 for an empty square. Move: from in bits
|
||||||
|
* 0-5, to in bits 6-11, promotion type in bits 12-14, then the castling and en passant flags.
|
||||||
|
*/
|
||||||
|
internal class Position(board: Board) {
|
||||||
|
val squares = IntArray(64)
|
||||||
|
var side = WHITE
|
||||||
|
private set
|
||||||
|
private var castling = 0
|
||||||
|
private var enPassant = -1
|
||||||
|
var halfmove = 0
|
||||||
|
private set
|
||||||
|
private var fullmove = 1
|
||||||
|
|
||||||
|
/** King square per colour, -1 without a king. */
|
||||||
|
private val kings = intArrayOf(-1, -1)
|
||||||
|
|
||||||
|
private var undo = IntArray(UNDO_FIELDS * 16)
|
||||||
|
private var undoDepth = 0
|
||||||
|
|
||||||
|
init {
|
||||||
|
for (sq in 0 until 64) {
|
||||||
|
val piece = board.squares[sq] ?: continue
|
||||||
|
val code = code(piece.type.ordinal + 1, piece.color.ordinal)
|
||||||
|
squares[sq] = code
|
||||||
|
if (piece.type == PieceType.KING && kings[piece.color.ordinal] == -1) kings[piece.color.ordinal] = sq
|
||||||
|
}
|
||||||
|
side = board.sideToMove.ordinal
|
||||||
|
if (board.whiteKingSideCastle) castling = castling or CASTLE_WK
|
||||||
|
if (board.whiteQueenSideCastle) castling = castling or CASTLE_WQ
|
||||||
|
if (board.blackKingSideCastle) castling = castling or CASTLE_BK
|
||||||
|
if (board.blackQueenSideCastle) castling = castling or CASTLE_BQ
|
||||||
|
enPassant = board.enPassantTarget ?: -1
|
||||||
|
halfmove = board.halfmoveClock
|
||||||
|
fullmove = board.fullmoveNumber
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toBoard(): Board {
|
||||||
|
val pieces = arrayOfNulls<Piece>(64)
|
||||||
|
for (sq in 0 until 64) {
|
||||||
|
val code = squares[sq]
|
||||||
|
if (code != 0) pieces[sq] = PIECES[code]
|
||||||
|
}
|
||||||
|
return Board(
|
||||||
|
squares = pieces,
|
||||||
|
sideToMove = if (side == WHITE) PieceColor.WHITE else PieceColor.BLACK,
|
||||||
|
whiteKingSideCastle = (castling and CASTLE_WK) != 0,
|
||||||
|
whiteQueenSideCastle = (castling and CASTLE_WQ) != 0,
|
||||||
|
blackKingSideCastle = (castling and CASTLE_BK) != 0,
|
||||||
|
blackQueenSideCastle = (castling and CASTLE_BQ) != 0,
|
||||||
|
enPassantTarget = if (enPassant == -1) null else enPassant,
|
||||||
|
halfmoveClock = halfmove,
|
||||||
|
fullmoveNumber = fullmove
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes the pseudo-legal moves of the side to move into [out] from [start] and returns the end
|
||||||
|
* index; [out] needs room for [MAX_MOVES]. With [tacticalOnly] only captures, en passant and
|
||||||
|
* promotions are written, in the same relative order.
|
||||||
|
*/
|
||||||
|
fun generate(out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||||
|
var n = start
|
||||||
|
val us = side
|
||||||
|
for (from in 0 until 64) {
|
||||||
|
val piece = squares[from]
|
||||||
|
if (piece == 0 || colorOf(piece) != us) continue
|
||||||
|
n = when (typeOf(piece)) {
|
||||||
|
PAWN -> pawnMoves(from, us, out, n, tacticalOnly)
|
||||||
|
KNIGHT -> stepMoves(from, us, KNIGHT_TARGETS[from], out, n, tacticalOnly)
|
||||||
|
BISHOP -> slidingMoves(from, us, 4, 8, out, n, tacticalOnly)
|
||||||
|
ROOK -> slidingMoves(from, us, 0, 4, out, n, tacticalOnly)
|
||||||
|
QUEEN -> slidingMoves(from, us, 0, 8, out, n, tacticalOnly)
|
||||||
|
else -> kingMoves(from, us, out, n, tacticalOnly)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pawnMoves(from: Int, us: Int, out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||||
|
var n = start
|
||||||
|
val file = from and 7
|
||||||
|
val rank = from shr 3
|
||||||
|
val toRank = if (us == WHITE) rank + 1 else rank - 1
|
||||||
|
if (toRank !in 0..7) return n
|
||||||
|
val promotes = toRank == (if (us == WHITE) 7 else 0)
|
||||||
|
val one = toRank * 8 + file
|
||||||
|
if (squares[one] == 0) {
|
||||||
|
if (promotes) {
|
||||||
|
n = promotions(from, one, out, n)
|
||||||
|
} else if (!tacticalOnly) {
|
||||||
|
out[n++] = moveCode(from, one)
|
||||||
|
if (rank == (if (us == WHITE) 1 else 6)) {
|
||||||
|
val two = if (us == WHITE) one + 8 else one - 8
|
||||||
|
if (squares[two] == 0) out[n++] = moveCode(from, two)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (file > 0) n = pawnCapture(from, one - 1, promotes, us, out, n)
|
||||||
|
if (file < 7) n = pawnCapture(from, one + 1, promotes, us, out, n)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pawnCapture(from: Int, to: Int, promotes: Boolean, us: Int, out: IntArray, start: Int): Int {
|
||||||
|
var n = start
|
||||||
|
val target = squares[to]
|
||||||
|
if (target != 0 && colorOf(target) != us) {
|
||||||
|
if (promotes) n = promotions(from, to, out, n) else out[n++] = moveCode(from, to)
|
||||||
|
} else if (to == enPassant) {
|
||||||
|
out[n++] = moveCode(from, to) or FLAG_EN_PASSANT
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun promotions(from: Int, to: Int, out: IntArray, start: Int): Int {
|
||||||
|
var n = start
|
||||||
|
val base = moveCode(from, to)
|
||||||
|
out[n++] = base or (QUEEN shl 12)
|
||||||
|
out[n++] = base or (ROOK shl 12)
|
||||||
|
out[n++] = base or (BISHOP shl 12)
|
||||||
|
out[n++] = base or (KNIGHT shl 12)
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stepMoves(from: Int, us: Int, targets: IntArray, out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||||
|
var n = start
|
||||||
|
for (to in targets) {
|
||||||
|
val target = squares[to]
|
||||||
|
if (target == 0) {
|
||||||
|
if (!tacticalOnly) out[n++] = moveCode(from, to)
|
||||||
|
} else if (colorOf(target) != us) {
|
||||||
|
out[n++] = moveCode(from, to)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun slidingMoves(
|
||||||
|
from: Int, us: Int, firstDir: Int, endDir: Int, out: IntArray, start: Int, tacticalOnly: Boolean
|
||||||
|
): Int {
|
||||||
|
var n = start
|
||||||
|
for (dir in firstDir until endDir) {
|
||||||
|
val ray = dir * 64 + from
|
||||||
|
val base = ray * 7
|
||||||
|
for (i in 0 until RAY_LENGTH[ray]) {
|
||||||
|
val to = RAYS[base + i]
|
||||||
|
val target = squares[to]
|
||||||
|
if (target == 0) {
|
||||||
|
if (!tacticalOnly) out[n++] = moveCode(from, to)
|
||||||
|
} else {
|
||||||
|
if (colorOf(target) != us) out[n++] = moveCode(from, to)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun kingMoves(from: Int, us: Int, out: IntArray, start: Int, tacticalOnly: Boolean): Int {
|
||||||
|
var n = stepMoves(from, us, KING_TARGETS[from], out, start, tacticalOnly)
|
||||||
|
if (tacticalOnly) return n
|
||||||
|
val e = if (us == WHITE) 4 else 60
|
||||||
|
if (from != e) return n
|
||||||
|
val rook = code(ROOK, us)
|
||||||
|
val them = us xor 1
|
||||||
|
val kingSide = (castling and (if (us == WHITE) CASTLE_WK else CASTLE_BK)) != 0 && squares[e + 3] == rook
|
||||||
|
val queenSide = (castling and (if (us == WHITE) CASTLE_WQ else CASTLE_BQ)) != 0 && squares[e - 4] == rook
|
||||||
|
if (kingSide && squares[e + 1] == 0 && squares[e + 2] == 0 &&
|
||||||
|
!isAttacked(e, them) && !isAttacked(e + 1, them) && !isAttacked(e + 2, them)
|
||||||
|
) {
|
||||||
|
out[n++] = moveCode(from, e + 2) or FLAG_CASTLE_KING
|
||||||
|
}
|
||||||
|
if (queenSide && squares[e - 1] == 0 && squares[e - 2] == 0 && squares[e - 3] == 0 &&
|
||||||
|
!isAttacked(e, them) && !isAttacked(e - 1, them) && !isAttacked(e - 2, them)
|
||||||
|
) {
|
||||||
|
out[n++] = moveCode(from, e - 2) or FLAG_CASTLE_QUEEN
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a piece of colour [by] attacks [target]. */
|
||||||
|
fun isAttacked(target: Int, by: Int): Boolean {
|
||||||
|
val file = target and 7
|
||||||
|
// Pawns of [by] capture towards the target from one rank behind it.
|
||||||
|
val pawnRank = (target shr 3) + (if (by == WHITE) -1 else 1)
|
||||||
|
if (pawnRank in 0..7) {
|
||||||
|
val pawn = code(PAWN, by)
|
||||||
|
if (file > 0 && squares[pawnRank * 8 + file - 1] == pawn) return true
|
||||||
|
if (file < 7 && squares[pawnRank * 8 + file + 1] == pawn) return true
|
||||||
|
}
|
||||||
|
val knight = code(KNIGHT, by)
|
||||||
|
for (sq in KNIGHT_TARGETS[target]) if (squares[sq] == knight) return true
|
||||||
|
val king = code(KING, by)
|
||||||
|
for (sq in KING_TARGETS[target]) if (squares[sq] == king) return true
|
||||||
|
val queen = code(QUEEN, by)
|
||||||
|
val rook = code(ROOK, by)
|
||||||
|
val bishop = code(BISHOP, by)
|
||||||
|
for (dir in 0 until 8) {
|
||||||
|
val slider = if (dir < 4) rook else bishop
|
||||||
|
val ray = dir * 64 + target
|
||||||
|
val base = ray * 7
|
||||||
|
for (i in 0 until RAY_LENGTH[ray]) {
|
||||||
|
val piece = squares[RAYS[base + i]]
|
||||||
|
if (piece != 0) {
|
||||||
|
if (piece == queen || piece == slider) return true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the king of the side to move is attacked. */
|
||||||
|
fun inCheck(): Boolean {
|
||||||
|
val king = kings[side]
|
||||||
|
return king != -1 && isAttacked(king, side xor 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** After [make]: whether the side that moved kept its king out of check. */
|
||||||
|
fun moverKingSafe(): Boolean {
|
||||||
|
val king = kings[side xor 1]
|
||||||
|
return king == -1 || !isAttacked(king, side)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isLegal(move: Int): Boolean {
|
||||||
|
make(move)
|
||||||
|
val safe = moverKingSafe()
|
||||||
|
unmake(move)
|
||||||
|
return safe
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plays [move] for the piece on its from-square, which must not be empty. */
|
||||||
|
fun make(move: Int) {
|
||||||
|
val from = move and 63
|
||||||
|
val to = (move shr 6) and 63
|
||||||
|
val promotion = (move shr 12) and 7
|
||||||
|
val moving = squares[from]
|
||||||
|
val color = colorOf(moving)
|
||||||
|
val captured = squares[to]
|
||||||
|
|
||||||
|
if ((undoDepth + 1) * UNDO_FIELDS > undo.size) undo = undo.copyOf(undo.size * 2)
|
||||||
|
val u = undoDepth * UNDO_FIELDS
|
||||||
|
undoDepth++
|
||||||
|
undo[u] = moving
|
||||||
|
undo[u + 1] = captured
|
||||||
|
undo[u + 2] = 0
|
||||||
|
undo[u + 3] = castling
|
||||||
|
undo[u + 4] = enPassant
|
||||||
|
undo[u + 5] = halfmove
|
||||||
|
undo[u + 6] = fullmove
|
||||||
|
undo[u + 7] = kings[WHITE]
|
||||||
|
undo[u + 8] = kings[BLACK]
|
||||||
|
|
||||||
|
if ((move and FLAG_EN_PASSANT) != 0) {
|
||||||
|
val victim = if (color == WHITE) to - 8 else to + 8
|
||||||
|
undo[u + 2] = squares[victim]
|
||||||
|
squares[victim] = 0
|
||||||
|
}
|
||||||
|
squares[to] = if (promotion != 0) code(promotion, color) else moving
|
||||||
|
squares[from] = 0
|
||||||
|
val backRank = from and 56
|
||||||
|
if ((move and FLAG_CASTLE_KING) != 0) {
|
||||||
|
squares[backRank + 5] = squares[backRank + 7]
|
||||||
|
squares[backRank + 7] = 0
|
||||||
|
}
|
||||||
|
if ((move and FLAG_CASTLE_QUEEN) != 0) {
|
||||||
|
squares[backRank + 3] = squares[backRank]
|
||||||
|
squares[backRank] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
val type = typeOf(moving)
|
||||||
|
if (type == KING) {
|
||||||
|
val rights = if (color == WHITE) CASTLE_WK or CASTLE_WQ else CASTLE_BK or CASTLE_BQ
|
||||||
|
castling = castling and rights.inv()
|
||||||
|
kings[color] = to
|
||||||
|
}
|
||||||
|
if (captured != 0 && typeOf(captured) == KING) kings[colorOf(captured)] = -1
|
||||||
|
if (from == 0 || to == 0) castling = castling and CASTLE_WQ.inv()
|
||||||
|
if (from == 7 || to == 7) castling = castling and CASTLE_WK.inv()
|
||||||
|
if (from == 56 || to == 56) castling = castling and CASTLE_BQ.inv()
|
||||||
|
if (from == 63 || to == 63) castling = castling and CASTLE_BK.inv()
|
||||||
|
|
||||||
|
val fromRank = from shr 3
|
||||||
|
val toRank = to shr 3
|
||||||
|
enPassant = if (type == PAWN && (toRank - fromRank == 2 || fromRank - toRank == 2)) {
|
||||||
|
(fromRank + toRank) / 2 * 8 + (from and 7)
|
||||||
|
} else -1
|
||||||
|
halfmove = if (type == PAWN || captured != 0) 0 else halfmove + 1
|
||||||
|
if (side == BLACK) fullmove++
|
||||||
|
side = side xor 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes back [move], which must be the last one made and a move from [generate]. */
|
||||||
|
fun unmake(move: Int) {
|
||||||
|
undoDepth--
|
||||||
|
val u = undoDepth * UNDO_FIELDS
|
||||||
|
val from = move and 63
|
||||||
|
val to = (move shr 6) and 63
|
||||||
|
side = side xor 1
|
||||||
|
squares[from] = undo[u]
|
||||||
|
squares[to] = undo[u + 1]
|
||||||
|
if ((move and FLAG_EN_PASSANT) != 0) squares[if (side == WHITE) to - 8 else to + 8] = undo[u + 2]
|
||||||
|
val backRank = from and 56
|
||||||
|
if ((move and FLAG_CASTLE_KING) != 0) {
|
||||||
|
squares[backRank + 7] = squares[backRank + 5]
|
||||||
|
squares[backRank + 5] = 0
|
||||||
|
}
|
||||||
|
if ((move and FLAG_CASTLE_QUEEN) != 0) {
|
||||||
|
squares[backRank] = squares[backRank + 3]
|
||||||
|
squares[backRank + 3] = 0
|
||||||
|
}
|
||||||
|
castling = undo[u + 3]
|
||||||
|
enPassant = undo[u + 4]
|
||||||
|
halfmove = undo[u + 5]
|
||||||
|
fullmove = undo[u + 6]
|
||||||
|
kings[WHITE] = undo[u + 7]
|
||||||
|
kings[BLACK] = undo[u + 8]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** See [ChessEngine.isDeadPosition]. */
|
||||||
|
fun isDeadPosition(): Boolean {
|
||||||
|
var minors = 0
|
||||||
|
var knights = false
|
||||||
|
var shade = -1
|
||||||
|
var oneShade = true
|
||||||
|
for (sq in 0 until 64) {
|
||||||
|
val code = squares[sq]
|
||||||
|
if (code == 0) continue
|
||||||
|
when (typeOf(code)) {
|
||||||
|
KING -> Unit
|
||||||
|
KNIGHT -> { minors++; knights = true }
|
||||||
|
BISHOP -> {
|
||||||
|
minors++
|
||||||
|
val s = ((sq and 7) + (sq shr 3)) and 1
|
||||||
|
if (shade == -1) shade = s else if (s != shade) oneShade = false
|
||||||
|
}
|
||||||
|
else -> return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return minors <= 1 || (!knights && oneShade)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash of what [Notation.positionKey] covers: pieces, side to move, castling rights and the
|
||||||
|
* en passant square. Equal keys give equal hashes; different keys can still collide.
|
||||||
|
*/
|
||||||
|
fun keyHash(): Long {
|
||||||
|
var h = if (side == BLACK) ZOBRIST_BLACK else 0L
|
||||||
|
for (sq in 0 until 64) {
|
||||||
|
val code = squares[sq]
|
||||||
|
if (code != 0) h = h xor ZOBRIST[code * 64 + sq]
|
||||||
|
}
|
||||||
|
h = h xor ZOBRIST[CASTLING_KEYS + castling]
|
||||||
|
if (enPassant in 0..63) h = h xor ZOBRIST[EN_PASSANT_KEYS + enPassant]
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val WHITE = 0
|
||||||
|
const val BLACK = 1
|
||||||
|
|
||||||
|
const val PAWN = 1
|
||||||
|
const val KNIGHT = 2
|
||||||
|
const val BISHOP = 3
|
||||||
|
const val ROOK = 4
|
||||||
|
const val QUEEN = 5
|
||||||
|
const val KING = 6
|
||||||
|
|
||||||
|
/** More pseudo-legal moves than any position can have. */
|
||||||
|
const val MAX_MOVES = 512
|
||||||
|
|
||||||
|
private const val FLAG_CASTLE_KING = 1 shl 15
|
||||||
|
private const val FLAG_CASTLE_QUEEN = 1 shl 16
|
||||||
|
private const val FLAG_EN_PASSANT = 1 shl 17
|
||||||
|
|
||||||
|
private const val CASTLE_WK = 1
|
||||||
|
private const val CASTLE_WQ = 2
|
||||||
|
private const val CASTLE_BK = 4
|
||||||
|
private const val CASTLE_BQ = 8
|
||||||
|
|
||||||
|
private const val UNDO_FIELDS = 9
|
||||||
|
|
||||||
|
fun code(type: Int, color: Int): Int = type or (color shl 3)
|
||||||
|
fun typeOf(code: Int): Int = code and 7
|
||||||
|
fun colorOf(code: Int): Int = code shr 3
|
||||||
|
|
||||||
|
fun moveFrom(move: Int): Int = move and 63
|
||||||
|
fun moveTo(move: Int): Int = (move shr 6) and 63
|
||||||
|
fun promotionOf(move: Int): Int = (move shr 12) and 7
|
||||||
|
fun isEnPassant(move: Int): Boolean = (move and FLAG_EN_PASSANT) != 0
|
||||||
|
|
||||||
|
private fun moveCode(from: Int, to: Int): Int = from or (to shl 6)
|
||||||
|
|
||||||
|
private val TYPES = PieceType.entries.toTypedArray()
|
||||||
|
|
||||||
|
/** Shared [Piece] per code; pieces are immutable values. */
|
||||||
|
private val PIECES = arrayOfNulls<Piece>(16).also {
|
||||||
|
for (type in TYPES) for (color in PieceColor.entries) {
|
||||||
|
it[code(type.ordinal + 1, color.ordinal)] = Piece(type, color)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encode(move: Move): Int {
|
||||||
|
var m = moveCode(move.from, move.to)
|
||||||
|
if (move.promotion != null) m = m or ((move.promotion.ordinal + 1) shl 12)
|
||||||
|
if (move.isCastleKingSide) m = m or FLAG_CASTLE_KING
|
||||||
|
if (move.isCastleQueenSide) m = m or FLAG_CASTLE_QUEEN
|
||||||
|
if (move.isEnPassant) m = m or FLAG_EN_PASSANT
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toMove(move: Int): Move {
|
||||||
|
val promotion = promotionOf(move)
|
||||||
|
return Move(
|
||||||
|
from = moveFrom(move),
|
||||||
|
to = moveTo(move),
|
||||||
|
promotion = if (promotion == 0) null else TYPES[promotion - 1],
|
||||||
|
isCastleKingSide = (move and FLAG_CASTLE_KING) != 0,
|
||||||
|
isCastleQueenSide = (move and FLAG_CASTLE_QUEEN) != 0,
|
||||||
|
isEnPassant = (move and FLAG_EN_PASSANT) != 0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Knight targets per square, in the order moves are generated. */
|
||||||
|
private val KNIGHT_TARGETS = targets(intArrayOf(1, 2, 2, 1, -1, -2, -2, -1), intArrayOf(2, 1, -1, -2, -2, -1, 1, 2))
|
||||||
|
|
||||||
|
/** King targets per square, file offset first, then rank offset. */
|
||||||
|
private val KING_TARGETS = targets(intArrayOf(-1, -1, -1, 0, 0, 1, 1, 1), intArrayOf(-1, 0, 1, -1, 1, -1, 0, 1))
|
||||||
|
|
||||||
|
private fun targets(df: IntArray, dr: IntArray): Array<IntArray> = Array(64) { sq ->
|
||||||
|
val list = ArrayList<Int>(8)
|
||||||
|
for (i in df.indices) {
|
||||||
|
val f = (sq and 7) + df[i]
|
||||||
|
val r = (sq shr 3) + dr[i]
|
||||||
|
if (f in 0..7 && r in 0..7) list.add(r * 8 + f)
|
||||||
|
}
|
||||||
|
list.toIntArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Directions 0-3 are orthogonal, 4-7 diagonal, in the order moves are generated. */
|
||||||
|
private val DIR_FILE = intArrayOf(1, -1, 0, 0, 1, 1, -1, -1)
|
||||||
|
private val DIR_RANK = intArrayOf(0, 0, 1, -1, 1, -1, 1, -1)
|
||||||
|
|
||||||
|
/** Squares along each direction from each square: 7 slots per ray (direction * 64 + square). */
|
||||||
|
private val RAYS = IntArray(8 * 64 * 7)
|
||||||
|
private val RAY_LENGTH = IntArray(8 * 64)
|
||||||
|
|
||||||
|
init {
|
||||||
|
for (dir in 0 until 8) for (sq in 0 until 64) {
|
||||||
|
val ray = dir * 64 + sq
|
||||||
|
var f = (sq and 7) + DIR_FILE[dir]
|
||||||
|
var r = (sq shr 3) + DIR_RANK[dir]
|
||||||
|
var length = 0
|
||||||
|
while (f in 0..7 && r in 0..7) {
|
||||||
|
RAYS[ray * 7 + length++] = r * 8 + f
|
||||||
|
f += DIR_FILE[dir]
|
||||||
|
r += DIR_RANK[dir]
|
||||||
|
}
|
||||||
|
RAY_LENGTH[ray] = length
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val CASTLING_KEYS = 16 * 64
|
||||||
|
private const val EN_PASSANT_KEYS = CASTLING_KEYS + 16
|
||||||
|
|
||||||
|
/** Fixed pseudo-random keys (splitmix64): piece and square, castling rights, en passant. */
|
||||||
|
private val ZOBRIST = LongArray(EN_PASSANT_KEYS + 64).also {
|
||||||
|
var state = 0x2545F4914F6CDD1DL
|
||||||
|
for (i in it.indices) {
|
||||||
|
state += -0x61c8864680b583ebL
|
||||||
|
var z = state
|
||||||
|
z = (z xor (z ushr 30)) * -0x40a7b892e31b1a47L
|
||||||
|
z = (z xor (z ushr 27)) * -0x6b2fb644ecceee15L
|
||||||
|
it[i] = z xor (z ushr 31)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private val ZOBRIST_BLACK = ZOBRIST[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@ import android.content.Intent
|
|||||||
import android.content.IntentFilter
|
import android.content.IntentFilter
|
||||||
import android.os.ParcelUuid
|
import android.os.ParcelUuid
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
|
import cc.skysparkle.matewave.security.toHex
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
@@ -52,6 +53,7 @@ class BleTransport(
|
|||||||
) : ConnectionTransport {
|
) : ConnectionTransport {
|
||||||
companion object {
|
companion object {
|
||||||
val SERVICE_UUID: UUID = UUID.fromString("6b1e7f10-2c3d-4a5b-8e9f-0a1b2c3d4e5f")
|
val SERVICE_UUID: UUID = UUID.fromString("6b1e7f10-2c3d-4a5b-8e9f-0a1b2c3d4e5f")
|
||||||
|
private val SERVICE_PARCEL_UUID = ParcelUuid(SERVICE_UUID)
|
||||||
|
|
||||||
val CHAR_WRITE_UUID: UUID = UUID.fromString("6b1e7f11-2c3d-4a5b-8e9f-0a1b2c3d4e5f")
|
val CHAR_WRITE_UUID: UUID = UUID.fromString("6b1e7f11-2c3d-4a5b-8e9f-0a1b2c3d4e5f")
|
||||||
|
|
||||||
@@ -94,11 +96,6 @@ class BleTransport(
|
|||||||
private const val NAME_BYTES_LIMIT = 6
|
private const val NAME_BYTES_LIMIT = 6
|
||||||
|
|
||||||
const val MAX_MESSAGE_BYTES = 1_000_000
|
const val MAX_MESSAGE_BYTES = 1_000_000
|
||||||
|
|
||||||
fun fingerprintOf(publicKeyOrId: String): String =
|
|
||||||
java.security.MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(publicKeyOrId.toByteArray(Charsets.UTF_8))
|
|
||||||
.take(FINGERPRINT_BYTES).joinToString("") { "%02x".format(it) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override val type = TransportType.BLUETOOTH
|
override val type = TransportType.BLUETOOTH
|
||||||
@@ -110,8 +107,6 @@ class BleTransport(
|
|||||||
private val adapter: BluetoothAdapter? = manager?.adapter
|
private val adapter: BluetoothAdapter? = manager?.adapter
|
||||||
|
|
||||||
private val dispatcher = MessageDispatcher()
|
private val dispatcher = MessageDispatcher()
|
||||||
var lastError: String? = null
|
|
||||||
private set
|
|
||||||
|
|
||||||
private enum class Role { NONE, PERIPHERAL, CENTRAL }
|
private enum class Role { NONE, PERIPHERAL, CENTRAL }
|
||||||
private var role = Role.NONE
|
private var role = Role.NONE
|
||||||
@@ -119,8 +114,6 @@ class BleTransport(
|
|||||||
private var gattServerActive = false
|
private var gattServerActive = false
|
||||||
private var advertisingActive = false
|
private var advertisingActive = false
|
||||||
|
|
||||||
private var shuttingDown = false
|
|
||||||
|
|
||||||
private var gattServer: BluetoothGattServer? = null
|
private var gattServer: BluetoothGattServer? = null
|
||||||
private var notifyCharacteristic: BluetoothGattCharacteristic? = null
|
private var notifyCharacteristic: BluetoothGattCharacteristic? = null
|
||||||
private var connectedCentral: BluetoothDevice? = null
|
private var connectedCentral: BluetoothDevice? = null
|
||||||
@@ -143,8 +136,10 @@ class BleTransport(
|
|||||||
|
|
||||||
private var outgoingMessageId = 0
|
private var outgoingMessageId = 0
|
||||||
|
|
||||||
private var sendGeneration = 0
|
@Volatile private var sendGeneration = 0
|
||||||
private var partialWatcherStarted = false
|
|
||||||
|
/** Guarded by [incoming]. */
|
||||||
|
private var partialWatcherRunning = false
|
||||||
|
|
||||||
private val pendingAcks = HashMap<Int, kotlinx.coroutines.CompletableDeferred<Set<Int>>>()
|
private val pendingAcks = HashMap<Int, kotlinx.coroutines.CompletableDeferred<Set<Int>>>()
|
||||||
|
|
||||||
@@ -211,25 +206,17 @@ class BleTransport(
|
|||||||
|
|
||||||
@SuppressLint("MissingPermission")
|
@SuppressLint("MissingPermission")
|
||||||
fun startPresence() {
|
fun startPresence() {
|
||||||
shuttingDown = false
|
|
||||||
val ad = adapter
|
val ad = adapter
|
||||||
if (ad == null || !ad.isEnabled) {
|
if (ad == null || !ad.isEnabled) return
|
||||||
lastError = "Bluetooth is off"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
val serverWasReady = gattServerActive
|
val serverWasReady = gattServerActive
|
||||||
if (!gattServerActive) {
|
if (!gattServerActive) {
|
||||||
if (!startGattServer()) {
|
if (!startGattServer()) return
|
||||||
lastError = "Could not start the Bluetooth service"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
gattServerActive = true
|
gattServerActive = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if (serverWasReady && !advertisingActive) startAdvertising()
|
if (serverWasReady && !advertisingActive) startAdvertising()
|
||||||
} catch (e: SecurityException) {
|
} catch (_: SecurityException) {
|
||||||
lastError = "No Bluetooth permission"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.PERMISSION_DENIED)
|
NetworkLog.reason("BLE", DisconnectReason.PERMISSION_DENIED)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,12 +225,10 @@ class BleTransport(
|
|||||||
override fun startHosting() {
|
override fun startHosting() {
|
||||||
val ad = adapter
|
val ad = adapter
|
||||||
if (ad == null || !ad.isEnabled) {
|
if (ad == null || !ad.isEnabled) {
|
||||||
lastError = "Bluetooth is off"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.BLUETOOTH_OFF)
|
NetworkLog.reason("BLE", DisconnectReason.BLUETOOTH_OFF)
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
lastError = null
|
|
||||||
role = Role.PERIPHERAL
|
role = Role.PERIPHERAL
|
||||||
hosting = true
|
hosting = true
|
||||||
|
|
||||||
@@ -310,7 +295,6 @@ class BleTransport(
|
|||||||
if (!announceAllowed()) return
|
if (!announceAllowed()) return
|
||||||
val advertiser = adapter?.bluetoothLeAdvertiser
|
val advertiser = adapter?.bluetoothLeAdvertiser
|
||||||
if (advertiser == null) {
|
if (advertiser == null) {
|
||||||
lastError = "This device does not support Bluetooth advertising"
|
|
||||||
if (hosting) _connectionState.value = ConnectionState.FAILED
|
if (hosting) _connectionState.value = ConnectionState.FAILED
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -325,12 +309,12 @@ class BleTransport(
|
|||||||
|
|
||||||
val data = AdvertiseData.Builder()
|
val data = AdvertiseData.Builder()
|
||||||
.setIncludeDeviceName(false)
|
.setIncludeDeviceName(false)
|
||||||
.addServiceUuid(ParcelUuid(SERVICE_UUID))
|
.addServiceUuid(SERVICE_PARCEL_UUID)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
val scanResponse = AdvertiseData.Builder()
|
val scanResponse = AdvertiseData.Builder()
|
||||||
.setIncludeDeviceName(false)
|
.setIncludeDeviceName(false)
|
||||||
.addServiceData(ParcelUuid(SERVICE_UUID), buildIdentityPayload())
|
.addServiceData(SERVICE_PARCEL_UUID, buildIdentityPayload())
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
val cb = object : AdvertiseCallback() {
|
val cb = object : AdvertiseCallback() {
|
||||||
@@ -345,7 +329,6 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
advertisingActive = false
|
advertisingActive = false
|
||||||
if (advertiseCallback === this) advertiseCallback = null
|
if (advertiseCallback === this) advertiseCallback = null
|
||||||
lastError = "Advertising failed (code $errorCode)"
|
|
||||||
NetworkLog.log("BLE", "Advertising failed, code $errorCode")
|
NetworkLog.log("BLE", "Advertising failed, code $errorCode")
|
||||||
// Without advertising nobody can find a hosted game; plain presence just goes quiet.
|
// Without advertising nobody can find a hosted game; plain presence just goes quiet.
|
||||||
if (hosting && connectedCentral == null) _connectionState.value = ConnectionState.FAILED
|
if (hosting && connectedCentral == null) _connectionState.value = ConnectionState.FAILED
|
||||||
@@ -354,9 +337,8 @@ class BleTransport(
|
|||||||
advertiseCallback = cb
|
advertiseCallback = cb
|
||||||
try {
|
try {
|
||||||
advertiser.startAdvertising(settings, data, scanResponse, cb)
|
advertiser.startAdvertising(settings, data, scanResponse, cb)
|
||||||
} catch (e: Exception) {
|
} catch (_: Exception) {
|
||||||
advertiseCallback = null
|
advertiseCallback = null
|
||||||
lastError = "Advertising failed: ${e.message}"
|
|
||||||
if (hosting) _connectionState.value = ConnectionState.FAILED
|
if (hosting) _connectionState.value = ConnectionState.FAILED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -380,7 +362,7 @@ class BleTransport(
|
|||||||
|
|
||||||
private fun parseIdentityPayload(data: ByteArray?): Pair<String?, String?> {
|
private fun parseIdentityPayload(data: ByteArray?): Pair<String?, String?> {
|
||||||
if (data == null || data.size < FINGERPRINT_BYTES) return null to null
|
if (data == null || data.size < FINGERPRINT_BYTES) return null to null
|
||||||
val fingerprint = data.take(FINGERPRINT_BYTES).joinToString("") { "%02x".format(it) }
|
val fingerprint = data.toHex(FINGERPRINT_BYTES)
|
||||||
val name = if (data.size > FINGERPRINT_BYTES) {
|
val name = if (data.size > FINGERPRINT_BYTES) {
|
||||||
String(data, FINGERPRINT_BYTES, data.size - FINGERPRINT_BYTES, Charsets.UTF_8)
|
String(data, FINGERPRINT_BYTES, data.size - FINGERPRINT_BYTES, Charsets.UTF_8)
|
||||||
.trim().ifBlank { null }
|
.trim().ifBlank { null }
|
||||||
@@ -392,12 +374,11 @@ class BleTransport(
|
|||||||
@SuppressLint("MissingPermission")
|
@SuppressLint("MissingPermission")
|
||||||
override fun onServiceAdded(status: Int, service: BluetoothGattService?) {
|
override fun onServiceAdded(status: Int, service: BluetoothGattService?) {
|
||||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||||
lastError = "Could not start the Bluetooth service (code $status)"
|
|
||||||
NetworkLog.log("BLE", "Service not added, code $status")
|
NetworkLog.log("BLE", "Service not added, code $status")
|
||||||
gattServerActive = false
|
gattServerActive = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!advertisingActive && !shuttingDown) startAdvertising()
|
if (!advertisingActive) startAdvertising()
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressLint("MissingPermission")
|
@SuppressLint("MissingPermission")
|
||||||
@@ -420,7 +401,6 @@ class BleTransport(
|
|||||||
role = Role.PERIPHERAL
|
role = Role.PERIPHERAL
|
||||||
// A new peer starts at the default MTU until it negotiates a larger one.
|
// A new peer starts at the default MTU until it negotiates a larger one.
|
||||||
chunkSize = SAFE_CHUNK
|
chunkSize = SAFE_CHUNK
|
||||||
startWriterIfNeeded()
|
|
||||||
|
|
||||||
_connectionState.value = ConnectionState.CONNECTING
|
_connectionState.value = ConnectionState.CONNECTING
|
||||||
stopAdvertising()
|
stopAdvertising()
|
||||||
@@ -462,7 +442,7 @@ class BleTransport(
|
|||||||
if (enabled) {
|
if (enabled) {
|
||||||
subscribeWatchJob?.cancel()
|
subscribeWatchJob?.cancel()
|
||||||
subscribeWatchJob = null
|
subscribeWatchJob = null
|
||||||
_connectionState.value = ConnectionState.CONNECTED
|
markReady()
|
||||||
} else {
|
} else {
|
||||||
NetworkLog.log("BLE", "Opponent disabled notifications")
|
NetworkLog.log("BLE", "Opponent disabled notifications")
|
||||||
dropPeripheralPeer(device)
|
dropPeripheralPeer(device)
|
||||||
@@ -539,7 +519,22 @@ class BleTransport(
|
|||||||
|
|
||||||
val lastSeen = HashMap<String, Long>()
|
val lastSeen = HashMap<String, Long>()
|
||||||
|
|
||||||
val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(SERVICE_UUID)).build()
|
// Drops players not seen for a while; true if any were dropped.
|
||||||
|
fun dropExpired(now: Long): Boolean {
|
||||||
|
var dropped = false
|
||||||
|
val entries = lastSeen.entries.iterator()
|
||||||
|
while (entries.hasNext()) {
|
||||||
|
val entry = entries.next()
|
||||||
|
if (now - entry.value > NEARBY_TTL_MS) {
|
||||||
|
found.remove(entry.key)
|
||||||
|
entries.remove()
|
||||||
|
dropped = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dropped
|
||||||
|
}
|
||||||
|
|
||||||
|
val filter = ScanFilter.Builder().setServiceUuid(SERVICE_PARCEL_UUID).build()
|
||||||
val settings = ScanSettings.Builder()
|
val settings = ScanSettings.Builder()
|
||||||
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
||||||
|
|
||||||
@@ -552,7 +547,7 @@ class BleTransport(
|
|||||||
if (myGeneration != scanGeneration) return
|
if (myGeneration != scanGeneration) return
|
||||||
val device = result.device ?: return
|
val device = result.device ?: return
|
||||||
|
|
||||||
val payload = result.scanRecord?.getServiceData(ParcelUuid(SERVICE_UUID))
|
val payload = result.scanRecord?.getServiceData(SERVICE_PARCEL_UUID)
|
||||||
val (fingerprint, advertisedName) = parseIdentityPayload(payload)
|
val (fingerprint, advertisedName) = parseIdentityPayload(payload)
|
||||||
|
|
||||||
val bondedName = try { device.name } catch (e: SecurityException) { null }
|
val bondedName = try { device.name } catch (e: SecurityException) { null }
|
||||||
@@ -566,25 +561,20 @@ class BleTransport(
|
|||||||
val previous = found.put(player.address, player)
|
val previous = found.put(player.address, player)
|
||||||
lastSeen[player.address] = now
|
lastSeen[player.address] = now
|
||||||
|
|
||||||
val expired = lastSeen.filterValues { now - it > NEARBY_TTL_MS }.keys
|
val expired = dropExpired(now)
|
||||||
expired.forEach { found.remove(it); lastSeen.remove(it) }
|
|
||||||
|
|
||||||
if (previous == null || previous.name != player.name || expired.isNotEmpty()) {
|
if (previous == null || previous.name != player.name || expired) {
|
||||||
val snapshot = found.values.toList()
|
val snapshot = found.values.toList()
|
||||||
scope.launch(Dispatchers.Main) { onFound(snapshot) }
|
scope.launch(Dispatchers.Main) { onFound(snapshot) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onScanFailed(errorCode: Int) {
|
override fun onScanFailed(errorCode: Int) {}
|
||||||
if (myGeneration != scanGeneration) return
|
|
||||||
lastError = "Nearby scan failed to start (code $errorCode)"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
scanCallback = cb
|
scanCallback = cb
|
||||||
try {
|
try {
|
||||||
scanner.startScan(listOf(filter), settings, cb)
|
scanner.startScan(listOf(filter), settings, cb)
|
||||||
} catch (e: SecurityException) {
|
} catch (_: SecurityException) {
|
||||||
lastError = "No permission to scan for devices"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scan results arrive on the main thread, so the expiry check runs there too.
|
// Scan results arrive on the main thread, so the expiry check runs there too.
|
||||||
@@ -592,12 +582,7 @@ class BleTransport(
|
|||||||
while (true) {
|
while (true) {
|
||||||
kotlinx.coroutines.delay(NEARBY_TTL_MS / 3)
|
kotlinx.coroutines.delay(NEARBY_TTL_MS / 3)
|
||||||
if (myGeneration != scanGeneration) return@launch
|
if (myGeneration != scanGeneration) return@launch
|
||||||
val now = System.currentTimeMillis()
|
if (dropExpired(System.currentTimeMillis())) onFound(found.values.toList())
|
||||||
val expired = lastSeen.filterValues { now - it > NEARBY_TTL_MS }.keys.toList()
|
|
||||||
if (expired.isNotEmpty()) {
|
|
||||||
expired.forEach { found.remove(it); lastSeen.remove(it) }
|
|
||||||
onFound(found.values.toList())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -617,18 +602,15 @@ class BleTransport(
|
|||||||
override fun startDiscoveryAndConnect(targetId: String?) {
|
override fun startDiscoveryAndConnect(targetId: String?) {
|
||||||
val ad = adapter
|
val ad = adapter
|
||||||
if (ad == null || !ad.isEnabled || targetId.isNullOrBlank()) {
|
if (ad == null || !ad.isEnabled || targetId.isNullOrBlank()) {
|
||||||
lastError = "Bluetooth is off or no opponent selected"
|
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (role == Role.PERIPHERAL && connectedCentral != null) {
|
if (role == Role.PERIPHERAL && connectedCentral != null) {
|
||||||
lastError = "A connection is already active, close it first"
|
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_connectionState.value = ConnectionState.CONNECTING
|
_connectionState.value = ConnectionState.CONNECTING
|
||||||
lastError = null
|
|
||||||
stopDiscovery()
|
stopDiscovery()
|
||||||
// A previous attempt must release its client: Android allows only a few at a time.
|
// A previous attempt must release its client: Android allows only a few at a time.
|
||||||
gattClient?.let { old ->
|
gattClient?.let { old ->
|
||||||
@@ -646,8 +628,7 @@ class BleTransport(
|
|||||||
context, false, clientCallback(myGeneration), BluetoothDevice.TRANSPORT_LE
|
context, false, clientCallback(myGeneration), BluetoothDevice.TRANSPORT_LE
|
||||||
)
|
)
|
||||||
gattClient = gatt
|
gattClient = gatt
|
||||||
} catch (e: Exception) {
|
} catch (_: Exception) {
|
||||||
lastError = "Connection failed: ${e.message}"
|
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -700,7 +681,6 @@ class BleTransport(
|
|||||||
if (!isCurrent()) return
|
if (!isCurrent()) return
|
||||||
val service = if (status == BluetoothGatt.GATT_SUCCESS) gatt.getService(SERVICE_UUID) else null
|
val service = if (status == BluetoothGatt.GATT_SUCCESS) gatt.getService(SERVICE_UUID) else null
|
||||||
if (service == null) {
|
if (service == null) {
|
||||||
lastError = "Peer does not expose this app's service"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "status $status")
|
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "status $status")
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
closeClient()
|
closeClient()
|
||||||
@@ -708,7 +688,6 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
writeCharacteristic = service.getCharacteristic(CHAR_WRITE_UUID)
|
writeCharacteristic = service.getCharacteristic(CHAR_WRITE_UUID)
|
||||||
if (writeCharacteristic == null) {
|
if (writeCharacteristic == null) {
|
||||||
lastError = "Peer does not support move exchange"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "no write characteristic")
|
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "no write characteristic")
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
closeClient()
|
closeClient()
|
||||||
@@ -717,7 +696,12 @@ class BleTransport(
|
|||||||
|
|
||||||
val notifyChar = service.getCharacteristic(CHAR_NOTIFY_UUID)
|
val notifyChar = service.getCharacteristic(CHAR_NOTIFY_UUID)
|
||||||
if (notifyChar != null) {
|
if (notifyChar != null) {
|
||||||
gatt.setCharacteristicNotification(notifyChar, true)
|
if (!gatt.setCharacteristicNotification(notifyChar, true)) {
|
||||||
|
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED, "local notification registration failed")
|
||||||
|
_connectionState.value = ConnectionState.FAILED
|
||||||
|
closeClient()
|
||||||
|
return
|
||||||
|
}
|
||||||
val cccd = notifyChar.getDescriptor(CCCD_UUID)
|
val cccd = notifyChar.getDescriptor(CCCD_UUID)
|
||||||
if (cccd != null) {
|
if (cccd != null) {
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
@@ -728,7 +712,6 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notifyChar == null || notifyChar.getDescriptor(CCCD_UUID) == null) {
|
if (notifyChar == null || notifyChar.getDescriptor(CCCD_UUID) == null) {
|
||||||
lastError = "Peer does not support the Bluetooth return channel"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "no notify characteristic")
|
NetworkLog.reason("BLE", DisconnectReason.SERVICE_NOT_FOUND, "no notify characteristic")
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
closeClient()
|
closeClient()
|
||||||
@@ -739,7 +722,6 @@ class BleTransport(
|
|||||||
kotlinx.coroutines.delay(SUBSCRIBE_TIMEOUT_MS)
|
kotlinx.coroutines.delay(SUBSCRIBE_TIMEOUT_MS)
|
||||||
if (!isCurrent()) return@launch
|
if (!isCurrent()) return@launch
|
||||||
if (_connectionState.value != ConnectionState.CONNECTED) {
|
if (_connectionState.value != ConnectionState.CONNECTED) {
|
||||||
lastError = "Peer did not confirm readiness"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED)
|
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED)
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
closeClient()
|
closeClient()
|
||||||
@@ -762,7 +744,6 @@ class BleTransport(
|
|||||||
if (status == BluetoothGatt.GATT_SUCCESS) {
|
if (status == BluetoothGatt.GATT_SUCCESS) {
|
||||||
markReady()
|
markReady()
|
||||||
} else {
|
} else {
|
||||||
lastError = "Could not enable Bluetooth notifications (code $status)"
|
|
||||||
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED, "code $status")
|
NetworkLog.reason("BLE", DisconnectReason.SUBSCRIBE_FAILED, "code $status")
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
closeClient()
|
closeClient()
|
||||||
@@ -812,6 +793,7 @@ class BleTransport(
|
|||||||
val entry = incoming.getOrPut(messageId) { PartialMessage(total, now) }
|
val entry = incoming.getOrPut(messageId) { PartialMessage(total, now) }
|
||||||
if (entry.total != total) {
|
if (entry.total != total) {
|
||||||
incoming[messageId] = PartialMessage(total, now).also { it.parts[index] = payload }
|
incoming[messageId] = PartialMessage(total, now).also { it.parts[index] = payload }
|
||||||
|
startPartialWatcher()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (entry.receivedBytes + payload.size > MAX_MESSAGE_BYTES) {
|
if (entry.receivedBytes + payload.size > MAX_MESSAGE_BYTES) {
|
||||||
@@ -833,6 +815,8 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
incoming.remove(messageId)
|
incoming.remove(messageId)
|
||||||
|
} else {
|
||||||
|
startPartialWatcher()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -945,14 +929,22 @@ class BleTransport(
|
|||||||
var lastChunkAt: Long = startedAt
|
var lastChunkAt: Long = startedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asks again for the missing chunks of stalled messages. Runs only while some message is
|
||||||
|
* incomplete; call with [incoming] locked.
|
||||||
|
*/
|
||||||
private fun startPartialWatcher() {
|
private fun startPartialWatcher() {
|
||||||
if (partialWatcherStarted) return
|
if (partialWatcherRunning) return
|
||||||
partialWatcherStarted = true
|
partialWatcherRunning = true
|
||||||
scope.launch {
|
scope.launch {
|
||||||
while (true) {
|
while (true) {
|
||||||
kotlinx.coroutines.delay(STALLED_PARTIAL_MS)
|
kotlinx.coroutines.delay(STALLED_PARTIAL_MS)
|
||||||
val requests = ArrayList<Pair<Int, List<Int>>>()
|
val requests = ArrayList<Pair<Int, List<Int>>>()
|
||||||
synchronized(incoming) {
|
synchronized(incoming) {
|
||||||
|
if (incoming.isEmpty()) {
|
||||||
|
partialWatcherRunning = false
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
for ((messageId, entry) in incoming) {
|
for ((messageId, entry) in incoming) {
|
||||||
if (now - entry.lastChunkAt < STALLED_PARTIAL_MS) continue
|
if (now - entry.lastChunkAt < STALLED_PARTIAL_MS) continue
|
||||||
@@ -971,7 +963,6 @@ class BleTransport(
|
|||||||
private fun startWriterIfNeeded() {
|
private fun startWriterIfNeeded() {
|
||||||
if (writerStarted) return
|
if (writerStarted) return
|
||||||
writerStarted = true
|
writerStarted = true
|
||||||
startPartialWatcher()
|
|
||||||
scope.launch(Dispatchers.IO) {
|
scope.launch(Dispatchers.IO) {
|
||||||
while (true) {
|
while (true) {
|
||||||
var handled = false
|
var handled = false
|
||||||
@@ -1064,9 +1055,12 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val answer = kotlinx.coroutines.withTimeoutOrNull(ACK_TIMEOUT_MS) {
|
val answer = kotlinx.coroutines.withTimeoutOrNull(ACK_TIMEOUT_MS) {
|
||||||
|
// Control frames keep going out while we wait for the answer.
|
||||||
while (!waiter.isCompleted) {
|
while (!waiter.isCompleted) {
|
||||||
val control = controlOutbox.tryReceive().getOrNull()
|
kotlinx.coroutines.selects.select<Unit> {
|
||||||
if (control != null) writeRaw(control) else kotlinx.coroutines.delay(20)
|
waiter.onAwait {}
|
||||||
|
controlOutbox.onReceive { writeRaw(it) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
waiter.await()
|
waiter.await()
|
||||||
}
|
}
|
||||||
@@ -1117,6 +1111,9 @@ class BleTransport(
|
|||||||
synchronized(nackAccumulator) { nackAccumulator.clear() }
|
synchronized(nackAccumulator) { nackAccumulator.clear() }
|
||||||
synchronized(incoming) { incoming.clear() }
|
synchronized(incoming) { incoming.clear() }
|
||||||
synchronized(recentlyCompleted) { recentlyCompleted.clear() }
|
synchronized(recentlyCompleted) { recentlyCompleted.clear() }
|
||||||
|
while (outbox.tryReceive().isSuccess) { }
|
||||||
|
while (bulkOutbox.tryReceive().isSuccess) { }
|
||||||
|
while (controlOutbox.tryReceive().isSuccess) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressLint("MissingPermission")
|
@SuppressLint("MissingPermission")
|
||||||
@@ -1125,12 +1122,17 @@ class BleTransport(
|
|||||||
val central = connectedCentral
|
val central = connectedCentral
|
||||||
if (role == Role.PERIPHERAL && central != null) {
|
if (role == Role.PERIPHERAL && central != null) {
|
||||||
val ch = notifyCharacteristic ?: return false
|
val ch = notifyCharacteristic ?: return false
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
ch.value = chunk
|
|
||||||
val waiter = kotlinx.coroutines.CompletableDeferred<Boolean>()
|
val waiter = kotlinx.coroutines.CompletableDeferred<Boolean>()
|
||||||
notificationSent = waiter
|
notificationSent = waiter
|
||||||
@Suppress("DEPRECATION")
|
val queued = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||||
val queued = gattServer?.notifyCharacteristicChanged(central, ch, false) ?: false
|
gattServer?.notifyCharacteristicChanged(central, ch, false, chunk) ==
|
||||||
|
android.bluetooth.BluetoothStatusCodes.SUCCESS
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
ch.value = chunk
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
gattServer?.notifyCharacteristicChanged(central, ch, false) ?: false
|
||||||
|
}
|
||||||
if (!queued) {
|
if (!queued) {
|
||||||
notificationSent = null
|
notificationSent = null
|
||||||
return false
|
return false
|
||||||
@@ -1141,14 +1143,19 @@ class BleTransport(
|
|||||||
sent == true
|
sent == true
|
||||||
} else {
|
} else {
|
||||||
val ch = writeCharacteristic ?: return false
|
val ch = writeCharacteristic ?: return false
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
ch.value = chunk
|
|
||||||
|
|
||||||
ch.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
|
||||||
val waiter = kotlinx.coroutines.CompletableDeferred<Boolean>()
|
val waiter = kotlinx.coroutines.CompletableDeferred<Boolean>()
|
||||||
characteristicWritten = waiter
|
characteristicWritten = waiter
|
||||||
@Suppress("DEPRECATION")
|
val queued = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||||
val queued = gattClient?.writeCharacteristic(ch) ?: false
|
gattClient?.writeCharacteristic(
|
||||||
|
ch, chunk, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||||
|
) == android.bluetooth.BluetoothStatusCodes.SUCCESS
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
ch.value = chunk
|
||||||
|
ch.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
gattClient?.writeCharacteristic(ch) ?: false
|
||||||
|
}
|
||||||
if (!queued) {
|
if (!queued) {
|
||||||
characteristicWritten = null
|
characteristicWritten = null
|
||||||
return false
|
return false
|
||||||
@@ -1173,6 +1180,11 @@ class BleTransport(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun send(message: GameMessage) {
|
override fun send(message: GameMessage) {
|
||||||
|
if (_connectionState.value != ConnectionState.CONNECTED) {
|
||||||
|
NetworkMetrics.messageDropped()
|
||||||
|
NetworkLog.log("BLE", "Message not queued: GATT session is not ready")
|
||||||
|
return
|
||||||
|
}
|
||||||
val json = message.toJson()
|
val json = message.toJson()
|
||||||
|
|
||||||
if (json.toByteArray(Charsets.UTF_8).size > currentMaxMessageBytes()) {
|
if (json.toByteArray(Charsets.UTF_8).size > currentMaxMessageBytes()) {
|
||||||
@@ -1226,18 +1238,4 @@ class BleTransport(
|
|||||||
while (controlOutbox.tryReceive().isSuccess) { }
|
while (controlOutbox.tryReceive().isSuccess) { }
|
||||||
_connectionState.value = ConnectionState.DISCONNECTED
|
_connectionState.value = ConnectionState.DISCONNECTED
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressLint("MissingPermission")
|
|
||||||
fun shutdown() {
|
|
||||||
shuttingDown = true
|
|
||||||
stopDiscovery()
|
|
||||||
stopAdvertising()
|
|
||||||
disconnect()
|
|
||||||
try { gattServer?.close() } catch (_: Exception) {}
|
|
||||||
gattServer = null
|
|
||||||
notifyCharacteristic = null
|
|
||||||
gattServerActive = false
|
|
||||||
advertisingActive = false
|
|
||||||
shuttingDown = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package cc.skysparkle.matewave.network
|
|||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
/** Periodic ping that detects a silently dropped connection. */
|
/** Periodic ping that detects a silently dropped connection. */
|
||||||
@@ -35,38 +36,31 @@ class Heartbeat(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sleeps while disconnected; every new connection starts with fresh timestamps.
|
||||||
job = scope.launch {
|
job = scope.launch {
|
||||||
var wasConnected = false
|
transport.connectionState.collectLatest { state ->
|
||||||
while (true) {
|
if (state != ConnectionState.CONNECTED) return@collectLatest
|
||||||
delay(INTERVAL_MS)
|
lastReplyAt = System.currentTimeMillis()
|
||||||
val connected = transport.connectionState.value == ConnectionState.CONNECTED
|
lastTrafficAt = lastReplyAt
|
||||||
if (!connected) {
|
while (true) {
|
||||||
wasConnected = false
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (!wasConnected) {
|
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
lastReplyAt = now
|
val silence = now - lastReplyAt
|
||||||
lastTrafficAt = now
|
|
||||||
wasConnected = true
|
|
||||||
}
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val silence = now - lastReplyAt
|
|
||||||
|
|
||||||
if (silence > TIMEOUT_MS && now - lastTrafficAt > TIMEOUT_MS) {
|
if (silence > TIMEOUT_MS && now - lastTrafficAt > TIMEOUT_MS) {
|
||||||
NetworkLog.reason(
|
NetworkLog.reason(
|
||||||
transport.type.name,
|
transport.type.name,
|
||||||
DisconnectReason.REMOTE_DISCONNECTED,
|
DisconnectReason.REMOTE_DISCONNECTED,
|
||||||
"no reply for ${silence / 1000} s"
|
"no reply for ${silence / 1000} s"
|
||||||
)
|
)
|
||||||
transport.disconnect()
|
transport.disconnect()
|
||||||
continue
|
} else {
|
||||||
|
if (silence > TIMEOUT_MS) {
|
||||||
|
NetworkLog.log(transport.type.name, "No heartbeat reply for ${silence / 1000} s, but data is flowing")
|
||||||
|
}
|
||||||
|
transport.send(GameMessage.PingMsg(reply = false, sessionId = sessionId))
|
||||||
|
}
|
||||||
|
delay(INTERVAL_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (silence > TIMEOUT_MS) {
|
|
||||||
NetworkLog.log(transport.type.name, "No heartbeat reply for ${silence / 1000} s, but data is flowing")
|
|
||||||
}
|
|
||||||
transport.send(GameMessage.PingMsg(reply = false, sessionId = sessionId))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,8 +57,6 @@ class LanTransport(
|
|||||||
|
|
||||||
const val MAX_MESSAGE_CHARS = 1_400_000
|
const val MAX_MESSAGE_CHARS = 1_400_000
|
||||||
|
|
||||||
const val ACCEPT_POLL_MS = 1_000
|
|
||||||
|
|
||||||
const val RESOLVE_RETRY_MS = 400L
|
const val RESOLVE_RETRY_MS = 400L
|
||||||
|
|
||||||
fun presencePayload(playerId: String, name: String, elo: Int): String =
|
fun presencePayload(playerId: String, name: String, elo: Int): String =
|
||||||
@@ -108,9 +106,6 @@ class LanTransport(
|
|||||||
private val resolveQueue = java.util.ArrayDeque<Pair<Int, NsdServiceInfo>>()
|
private val resolveQueue = java.util.ArrayDeque<Pair<Int, NsdServiceInfo>>()
|
||||||
private var resolving = false
|
private var resolving = false
|
||||||
|
|
||||||
var lastError: String? = null
|
|
||||||
private set
|
|
||||||
|
|
||||||
private val outbox = Channel<String>(capacity = Channel.UNLIMITED)
|
private val outbox = Channel<String>(capacity = Channel.UNLIMITED)
|
||||||
private var writerStarted = false
|
private var writerStarted = false
|
||||||
|
|
||||||
@@ -154,13 +149,12 @@ class LanTransport(
|
|||||||
|
|
||||||
server.bind(InetSocketAddress(0))
|
server.bind(InetSocketAddress(0))
|
||||||
|
|
||||||
server.soTimeout = ACCEPT_POLL_MS
|
// accept() blocks until a peer connects; shutdown() closes the socket to end it.
|
||||||
synchronized(presenceLock) { serverSocket = server; presenceStarting = false }
|
synchronized(presenceLock) { serverSocket = server; presenceStarting = false }
|
||||||
if (announceAllowed()) registerService(server.localPort)
|
if (announceAllowed()) registerService(server.localPort)
|
||||||
acceptLoop(server)
|
acceptLoop(server)
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
synchronized(presenceLock) { presenceStarting = false }
|
synchronized(presenceLock) { presenceStarting = false }
|
||||||
lastError = "Could not open port: ${e.message}"
|
|
||||||
NetworkLog.reason("LAN", DisconnectReason.PORT_BUSY, e.message)
|
NetworkLog.reason("LAN", DisconnectReason.PORT_BUSY, e.message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -186,8 +180,6 @@ class LanTransport(
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
onConnected(client)
|
onConnected(client)
|
||||||
} catch (e: java.net.SocketTimeoutException) {
|
|
||||||
continue
|
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
if (server.isClosed) return
|
if (server.isClosed) return
|
||||||
NetworkLog.log("LAN", "Accept failed: ${e.message}")
|
NetworkLog.log("LAN", "Accept failed: ${e.message}")
|
||||||
@@ -199,7 +191,6 @@ class LanTransport(
|
|||||||
override fun startHosting() {
|
override fun startHosting() {
|
||||||
hosting = true
|
hosting = true
|
||||||
_connectionState.value = ConnectionState.CONNECTING
|
_connectionState.value = ConnectionState.CONNECTING
|
||||||
lastError = null
|
|
||||||
|
|
||||||
val port = serverSocket?.localPort
|
val port = serverSocket?.localPort
|
||||||
if (port != null) registerService(port) else startPresence()
|
if (port != null) registerService(port) else startPresence()
|
||||||
@@ -236,16 +227,18 @@ class LanTransport(
|
|||||||
registeredServiceName = info?.serviceName
|
registeredServiceName = info?.serviceName
|
||||||
}
|
}
|
||||||
override fun onRegistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
|
override fun onRegistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
|
||||||
lastError = "Network service registration failed (code $errorCode). Connect by address manually."
|
NetworkLog.log("LAN", "Service registration failed, code $errorCode")
|
||||||
|
if (registrationListener === this) registrationListener = null
|
||||||
}
|
}
|
||||||
override fun onServiceUnregistered(info: NsdServiceInfo?) {}
|
override fun onServiceUnregistered(info: NsdServiceInfo?) {}
|
||||||
override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) {}
|
override fun onUnregistrationFailed(info: NsdServiceInfo?, errorCode: Int) {
|
||||||
|
NetworkLog.log("LAN", "Service unregistration failed, code $errorCode")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
registrationListener = listener
|
registrationListener = listener
|
||||||
try {
|
try {
|
||||||
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
|
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||||
} catch (e: Exception) {
|
} catch (_: Exception) {
|
||||||
lastError = "Service registration: ${e.message}"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,8 +283,8 @@ class LanTransport(
|
|||||||
|
|
||||||
override fun onDiscoveryStopped(serviceType: String?) {}
|
override fun onDiscoveryStopped(serviceType: String?) {}
|
||||||
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
|
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
|
||||||
lastError = "Network discovery failed (code $errorCode). Enter the address manually."
|
|
||||||
NetworkLog.log("LAN", "Network discovery failed to start, code $errorCode")
|
NetworkLog.log("LAN", "Network discovery failed to start, code $errorCode")
|
||||||
|
if (discoveryListener === this) discoveryListener = null
|
||||||
}
|
}
|
||||||
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {}
|
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {}
|
||||||
}
|
}
|
||||||
@@ -299,8 +292,8 @@ class LanTransport(
|
|||||||
try {
|
try {
|
||||||
nsd.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)
|
nsd.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
lastError = "Network discovery: ${e.message}"
|
|
||||||
NetworkLog.log("LAN", "Network discovery: ${e.message}")
|
NetworkLog.log("LAN", "Network discovery: ${e.message}")
|
||||||
|
discoveryListener = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -386,9 +379,12 @@ class LanTransport(
|
|||||||
|
|
||||||
if (serviceName == ownServiceName) return true
|
if (serviceName == ownServiceName) return true
|
||||||
|
|
||||||
return Regex("^${Regex.escape(ownServiceName)} \\(\\d+\\)$").matches(serviceName)
|
return renamedOwnService.matches(serviceName)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Our own service after NSD renamed it on a clash, e.g. "ChessApp-ab12 (2)". */
|
||||||
|
private val renamedOwnService: Regex by lazy { Regex("^${Regex.escape(ownServiceName)} \\(\\d+\\)$") }
|
||||||
|
|
||||||
private fun isSelfEndpoint(host: String, port: Int): Boolean {
|
private fun isSelfEndpoint(host: String, port: Int): Boolean {
|
||||||
val ourPort = serverSocket?.localPort ?: return false
|
val ourPort = serverSocket?.localPort ?: return false
|
||||||
if (port != ourPort) return false
|
if (port != ourPort) return false
|
||||||
@@ -484,14 +480,12 @@ class LanTransport(
|
|||||||
val host = targetId.substringBeforeLast(':', targetId).trim()
|
val host = targetId.substringBeforeLast(':', targetId).trim()
|
||||||
|
|
||||||
val port = targetId.substringAfterLast(':', "").toIntOrNull() ?: run {
|
val port = targetId.substringAfterLast(':', "").toIntOrNull() ?: run {
|
||||||
lastError = "Address must look like 192.168.1.5:port"
|
|
||||||
NetworkLog.reason("LAN", DisconnectReason.PEER_NOT_FOUND)
|
NetworkLog.reason("LAN", DisconnectReason.PEER_NOT_FOUND)
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_connectionState.value = ConnectionState.CONNECTING
|
_connectionState.value = ConnectionState.CONNECTING
|
||||||
lastError = null
|
|
||||||
scope.launch(Dispatchers.IO) {
|
scope.launch(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
val s = Socket()
|
val s = Socket()
|
||||||
@@ -508,8 +502,7 @@ class LanTransport(
|
|||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
onConnected(s)
|
onConnected(s)
|
||||||
} catch (e: IOException) {
|
} catch (_: IOException) {
|
||||||
lastError = "Could not connect to $host:$port: ${e.message}"
|
|
||||||
NetworkLog.reason("LAN", DisconnectReason.CONNECT_TIMEOUT, "$host:$port")
|
NetworkLog.reason("LAN", DisconnectReason.CONNECT_TIMEOUT, "$host:$port")
|
||||||
_connectionState.value = ConnectionState.FAILED
|
_connectionState.value = ConnectionState.FAILED
|
||||||
}
|
}
|
||||||
@@ -560,6 +553,12 @@ class LanTransport(
|
|||||||
if (wasCurrent) {
|
if (wasCurrent) {
|
||||||
hosting = false
|
hosting = false
|
||||||
onHostingEnded()
|
onHostingEnded()
|
||||||
|
var dropped = 0
|
||||||
|
while (outbox.tryReceive().isSuccess) dropped++
|
||||||
|
if (dropped > 0) {
|
||||||
|
repeat(dropped) { NetworkMetrics.messageDropped() }
|
||||||
|
NetworkLog.log("LAN", "Dropped unsent messages after disconnect: $dropped")
|
||||||
|
}
|
||||||
_connectionState.value = ConnectionState.DISCONNECTED
|
_connectionState.value = ConnectionState.DISCONNECTED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -586,6 +585,11 @@ class LanTransport(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun send(message: GameMessage) {
|
override fun send(message: GameMessage) {
|
||||||
|
if (_connectionState.value != ConnectionState.CONNECTED) {
|
||||||
|
NetworkMetrics.messageDropped()
|
||||||
|
NetworkLog.log("LAN", "Message not queued: TCP session is not connected")
|
||||||
|
return
|
||||||
|
}
|
||||||
val json = message.toJson()
|
val json = message.toJson()
|
||||||
val size = json.length
|
val size = json.length
|
||||||
if (size > MAX_MESSAGE_CHARS) {
|
if (size > MAX_MESSAGE_CHARS) {
|
||||||
|
|||||||
@@ -18,8 +18,4 @@ class MessageDispatcher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clear() {
|
|
||||||
listeners.clear()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ enum class DisconnectReason(val userText: String, val textRes: Int) {
|
|||||||
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
|
NONE("—", cc.skysparkle.matewave.R.string.reason_unknown),
|
||||||
PERMISSION_DENIED("No nearby devices permission", cc.skysparkle.matewave.R.string.reason_permission_denied),
|
PERMISSION_DENIED("No nearby devices permission", cc.skysparkle.matewave.R.string.reason_permission_denied),
|
||||||
BLUETOOTH_OFF("Bluetooth is off", cc.skysparkle.matewave.R.string.reason_bluetooth_off),
|
BLUETOOTH_OFF("Bluetooth is off", cc.skysparkle.matewave.R.string.reason_bluetooth_off),
|
||||||
WIFI_UNAVAILABLE("Phone is not connected to Wi-Fi", cc.skysparkle.matewave.R.string.reason_wifi_unavailable),
|
|
||||||
PEER_NOT_FOUND("Opponent not found", cc.skysparkle.matewave.R.string.reason_peer_not_found),
|
PEER_NOT_FOUND("Opponent not found", cc.skysparkle.matewave.R.string.reason_peer_not_found),
|
||||||
CONNECT_TIMEOUT("Opponent did not respond in time", cc.skysparkle.matewave.R.string.reason_connect_timeout),
|
CONNECT_TIMEOUT("Opponent did not respond in time", cc.skysparkle.matewave.R.string.reason_connect_timeout),
|
||||||
SERVICE_NOT_FOUND("The other device does not have this app", cc.skysparkle.matewave.R.string.reason_service_not_found),
|
SERVICE_NOT_FOUND("The other device does not have this app", cc.skysparkle.matewave.R.string.reason_service_not_found),
|
||||||
@@ -16,8 +15,7 @@ enum class DisconnectReason(val userText: String, val textRes: Int) {
|
|||||||
WRITE_FAILED("Could not send data", cc.skysparkle.matewave.R.string.reason_write_failed),
|
WRITE_FAILED("Could not send data", cc.skysparkle.matewave.R.string.reason_write_failed),
|
||||||
MESSAGE_TOO_LARGE("Received message is too large", cc.skysparkle.matewave.R.string.reason_message_too_large),
|
MESSAGE_TOO_LARGE("Received message is too large", cc.skysparkle.matewave.R.string.reason_message_too_large),
|
||||||
REMOTE_DISCONNECTED("Opponent disconnected", cc.skysparkle.matewave.R.string.reason_remote_disconnected),
|
REMOTE_DISCONNECTED("Opponent disconnected", cc.skysparkle.matewave.R.string.reason_remote_disconnected),
|
||||||
PORT_BUSY("Could not open port", cc.skysparkle.matewave.R.string.reason_port_busy),
|
PORT_BUSY("Could not open port", cc.skysparkle.matewave.R.string.reason_port_busy)
|
||||||
UNKNOWN("Unknown connection error", cc.skysparkle.matewave.R.string.reason_unknown)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
data class NetworkEvent(
|
data class NetworkEvent(
|
||||||
@@ -45,9 +43,10 @@ object NetworkLog {
|
|||||||
log(transport, reason.userText + (detail?.let { ": $it" } ?: ""))
|
log(transport, reason.userText + (detail?.let { ": $it" } ?: ""))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun asText(): String = _events.value.joinToString("\n") { e ->
|
fun asText(): String {
|
||||||
val time = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
|
val format = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault())
|
||||||
.format(java.util.Date(e.at))
|
return _events.value.joinToString("\n") { e ->
|
||||||
"$time [${e.transport}] ${e.text}"
|
"${format.format(java.util.Date(e.at))} [${e.transport}] ${e.text}"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,16 +14,7 @@ data class NetworkStatus(
|
|||||||
val wifiConnected: Boolean,
|
val wifiConnected: Boolean,
|
||||||
val permissionsGranted: Boolean,
|
val permissionsGranted: Boolean,
|
||||||
val notificationsGranted: Boolean
|
val notificationsGranted: Boolean
|
||||||
) {
|
)
|
||||||
val bluetoothReady: Boolean
|
|
||||||
get() = bluetoothSupported && bluetoothOn && permissionsGranted
|
|
||||||
|
|
||||||
val lanReady: Boolean get() = wifiConnected
|
|
||||||
|
|
||||||
val anyChannelReady: Boolean get() = bluetoothReady || lanReady
|
|
||||||
|
|
||||||
val onlineBlocked: Boolean get() = !anyChannelReady
|
|
||||||
}
|
|
||||||
|
|
||||||
object NetworkRequirements {
|
object NetworkRequirements {
|
||||||
fun check(context: Context): NetworkStatus {
|
fun check(context: Context): NetworkStatus {
|
||||||
|
|||||||
@@ -9,9 +9,8 @@ data class OpeningName(val eco: String, val name: String)
|
|||||||
* deviations, and opening names from lichess-org/chess-openings (CC0). Both are keyed by SAN move
|
* deviations, and opening names from lichess-org/chess-openings (CC0). Both are keyed by SAN move
|
||||||
* sequences from the standard starting position, so no position hashing is needed at runtime.
|
* sequences from the standard starting position, so no position hashing is needed at runtime.
|
||||||
*
|
*
|
||||||
* explorer.txt: header "#games N", then one node per line "parentId san white draws black";
|
* explorer.txt: header "#games N", then one node per line "parentId san"; node ids are line
|
||||||
* node ids are line numbers (the root is 0) and parents always come before children. Only the
|
* numbers (the root is 0) and parents always come before children.
|
||||||
* tree shape is used here.
|
|
||||||
*/
|
*/
|
||||||
object OpeningBook {
|
object OpeningBook {
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ data class Puzzle(
|
|||||||
val theme: String,
|
val theme: String,
|
||||||
val fen: String,
|
val fen: String,
|
||||||
val solutionUci: List<String>,
|
val solutionUci: List<String>,
|
||||||
val rating: Int,
|
val rating: Int
|
||||||
val themes: List<String> = emptyList()
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Localized name of the puzzle theme, shown as the screen title. */
|
/** Localized name of the puzzle theme, shown as the screen title. */
|
||||||
@@ -59,16 +58,13 @@ object PuzzleRepository {
|
|||||||
val o = arr.getJSONObject(i)
|
val o = arr.getJSONObject(i)
|
||||||
val solutionArr = o.getJSONArray("solution")
|
val solutionArr = o.getJSONArray("solution")
|
||||||
val solution = (0 until solutionArr.length()).map { solutionArr.getString(it) }
|
val solution = (0 until solutionArr.length()).map { solutionArr.getString(it) }
|
||||||
val themesArr = o.optJSONArray("themes")
|
|
||||||
val themes = themesArr?.let { t -> (0 until t.length()).map { t.getString(it) } } ?: emptyList()
|
|
||||||
result.add(
|
result.add(
|
||||||
Puzzle(
|
Puzzle(
|
||||||
id = o.getInt("id"),
|
id = o.getInt("id"),
|
||||||
theme = o.optString("theme", "tactic"),
|
theme = o.optString("theme", "tactic"),
|
||||||
fen = o.getString("fen"),
|
fen = o.getString("fen"),
|
||||||
solutionUci = solution,
|
solutionUci = solution,
|
||||||
rating = o.getInt("rating"),
|
rating = o.getInt("rating")
|
||||||
themes = themes
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ object DeviceKeys {
|
|||||||
fun fingerprintOf(publicKey: String): String =
|
fun fingerprintOf(publicKey: String): String =
|
||||||
MessageDigest.getInstance("SHA-256")
|
MessageDigest.getInstance("SHA-256")
|
||||||
.digest(publicKey.toByteArray(Charsets.UTF_8))
|
.digest(publicKey.toByteArray(Charsets.UTF_8))
|
||||||
.take(16).joinToString("") { "%02x".format(it) }
|
.toHex(16)
|
||||||
|
|
||||||
fun sign(context: Context, data: String): String? {
|
fun sign(context: Context, data: String): String? {
|
||||||
val privateKey: PrivateKey = keyPair(context)?.private ?: return null
|
val privateKey: PrivateKey = keyPair(context)?.private ?: return null
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package cc.skysparkle.matewave.security
|
||||||
|
|
||||||
|
private const val HEX_DIGITS = "0123456789abcdef"
|
||||||
|
|
||||||
|
/** Lowercase hex of the first [count] bytes. */
|
||||||
|
internal fun ByteArray.toHex(count: Int = size): String {
|
||||||
|
val n = minOf(count, size)
|
||||||
|
val out = CharArray(n * 2)
|
||||||
|
for (i in 0 until n) {
|
||||||
|
val v = this[i].toInt() and 0xFF
|
||||||
|
out[i * 2] = HEX_DIGITS[v ushr 4]
|
||||||
|
out[i * 2 + 1] = HEX_DIGITS[v and 0x0F]
|
||||||
|
}
|
||||||
|
return String(out)
|
||||||
|
}
|
||||||
@@ -79,7 +79,7 @@ class KnownPeers(context: Context) {
|
|||||||
if (value.isNullOrEmpty()) return ""
|
if (value.isNullOrEmpty()) return ""
|
||||||
return java.security.MessageDigest.getInstance("SHA-256")
|
return java.security.MessageDigest.getInstance("SHA-256")
|
||||||
.digest(value.toByteArray(Charsets.UTF_8))
|
.digest(value.toByteArray(Charsets.UTF_8))
|
||||||
.take(8).joinToString("") { "%02x".format(it) }
|
.toHex(8)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Forgets every pinned key, e.g. after opponents reinstalled the app. */
|
/** Forgets every pinned key, e.g. after opponents reinstalled the app. */
|
||||||
|
|||||||
@@ -25,21 +25,21 @@ object Haptics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun select() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_TICK, fallbackMs = 8)
|
fun select() = play(VibrationEffect.EFFECT_TICK, fallbackMs = 8)
|
||||||
|
|
||||||
fun move() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_CLICK, fallbackMs = 15)
|
fun move() = play(VibrationEffect.EFFECT_CLICK, fallbackMs = 15)
|
||||||
|
|
||||||
fun capture() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_HEAVY_CLICK, fallbackMs = 25)
|
fun capture() = play(VibrationEffect.EFFECT_HEAVY_CLICK, fallbackMs = 25)
|
||||||
|
|
||||||
fun alert() = play(Build.VERSION_CODES.Q, predefined = VibrationEffect.EFFECT_DOUBLE_CLICK, fallbackMs = 40)
|
fun alert() = play(VibrationEffect.EFFECT_DOUBLE_CLICK, fallbackMs = 40)
|
||||||
|
|
||||||
private fun play(minApiForPredefined: Int, predefined: Int, fallbackMs: Long) {
|
private fun play(predefined: Int, fallbackMs: Long) {
|
||||||
val context = appContext ?: return
|
val context = appContext ?: return
|
||||||
val v = vibrator ?: return
|
val v = vibrator ?: return
|
||||||
if (!v.hasVibrator()) return
|
if (!v.hasVibrator()) return
|
||||||
if (!FeedbackSettings(context).vibrationEnabled) return
|
if (!FeedbackSettings(context).vibrationEnabled) return
|
||||||
runCatching {
|
runCatching {
|
||||||
val effect = if (Build.VERSION.SDK_INT >= minApiForPredefined) {
|
val effect = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
VibrationEffect.createPredefined(predefined)
|
VibrationEffect.createPredefined(predefined)
|
||||||
} else {
|
} else {
|
||||||
VibrationEffect.createOneShot(fallbackMs, VibrationEffect.DEFAULT_AMPLITUDE)
|
VibrationEffect.createOneShot(fallbackMs, VibrationEffect.DEFAULT_AMPLITUDE)
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package cc.skysparkle.matewave.spectate
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.security.toHex
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What this device adds to its network announcement while it plays a watchable LAN game: a short
|
* What this device adds to its network announcement while it plays a watchable LAN game: a short
|
||||||
* tag shared by both players of the game, and, on the host, the spectator port. Older app versions
|
* tag shared by both players of the game, and, on the host, the spectator port. Older app versions
|
||||||
@@ -40,7 +42,7 @@ object SpectatorAdvert {
|
|||||||
fun tagOf(gameId: String): String {
|
fun tagOf(gameId: String): String {
|
||||||
if (gameId.isEmpty()) return ""
|
if (gameId.isEmpty()) return ""
|
||||||
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8))
|
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8))
|
||||||
return digest.take(4).joinToString("") { "%02x".format(it) }
|
return digest.toHex(4)
|
||||||
}
|
}
|
||||||
|
|
||||||
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ class SpectatorGame {
|
|||||||
val sans = ArrayList<String>(snapshot.movesUci.size)
|
val sans = ArrayList<String>(snapshot.movesUci.size)
|
||||||
var last: Move? = null
|
var last: Move? = null
|
||||||
for (uci in snapshot.movesUci) {
|
for (uci in snapshot.movesUci) {
|
||||||
val move = resolve(board, uci) ?: return false
|
val move = Notation.fromUci(board, uci) ?: return false
|
||||||
sans.add(Notation.toSan(board, move))
|
sans.add(Notation.toSan(board, move))
|
||||||
board = ChessEngine.applyMove(board, move)
|
board = ChessEngine.applyMove(board, move)
|
||||||
last = move
|
last = move
|
||||||
@@ -69,7 +69,7 @@ class SpectatorGame {
|
|||||||
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||||
if (current.result != null || message.ply <= current.ply) return Applied.IGNORED
|
if (current.result != null || message.ply <= current.ply) return Applied.IGNORED
|
||||||
if (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC
|
if (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC
|
||||||
val move = resolve(current.board, message.uci) ?: return Applied.NEEDS_RESYNC
|
val move = Notation.fromUci(current.board, message.uci) ?: return Applied.NEEDS_RESYNC
|
||||||
view = current.copy(
|
view = current.copy(
|
||||||
board = ChessEngine.applyMove(current.board, move),
|
board = ChessEngine.applyMove(current.board, move),
|
||||||
movesUci = current.movesUci + move.toUci(),
|
movesUci = current.movesUci + move.toUci(),
|
||||||
@@ -95,14 +95,6 @@ class SpectatorGame {
|
|||||||
if (clock == null || current.result != null) return
|
if (clock == null || current.result != null) return
|
||||||
view = current.copy(clock = clock)
|
view = current.copy(clock = clock)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resolve(board: Board, uci: String): Move? {
|
|
||||||
if (uci.length !in 4..5) return null
|
|
||||||
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null
|
|
||||||
if (candidate.from !in 0..63 || candidate.to !in 0..63) return null
|
|
||||||
val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to }
|
|
||||||
return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Turns successive host snapshots into the messages spectators need to follow along. */
|
/** Turns successive host snapshots into the messages spectators need to follow along. */
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ private object BackgroundAssetCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun AppBackgroundImage(modifier: Modifier = Modifier.fillMaxSize()) {
|
fun AppBackgroundImage() {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
||||||
var bitmap by remember { mutableStateOf(BackgroundAssetCache.cached()) }
|
var bitmap by remember { mutableStateOf(BackgroundAssetCache.cached()) }
|
||||||
@@ -72,10 +72,10 @@ fun AppBackgroundImage(modifier: Modifier = Modifier.fillMaxSize()) {
|
|||||||
Image(
|
Image(
|
||||||
bitmap = image,
|
bitmap = image,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = modifier,
|
modifier = Modifier.fillMaxSize(),
|
||||||
contentScale = ContentScale.Crop
|
contentScale = ContentScale.Crop
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Box(modifier = modifier.background(Color(0xFF101413)))
|
Box(modifier = Modifier.fillMaxSize().background(Color(0xFF101413)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ package cc.skysparkle.matewave.ui.components
|
|||||||
|
|
||||||
import cc.skysparkle.matewave.ui.theme.ink
|
import cc.skysparkle.matewave.ui.theme.ink
|
||||||
|
|
||||||
import androidx.compose.animation.animateColorAsState
|
|
||||||
import androidx.compose.animation.core.tween
|
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.runtime.getValue
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -54,48 +51,51 @@ fun AppBottomBar(
|
|||||||
.padding(vertical = 6.dp),
|
.padding(vertical = 6.dp),
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly
|
horizontalArrangement = Arrangement.SpaceEvenly
|
||||||
) {
|
) {
|
||||||
NavItem(iconRes = R.drawable.ic_home, label = stringResource(R.string.nav_home), active = current == BottomTab.HOME, onClick = onHomeClick)
|
NavItem(stringResource(R.string.nav_home), current == BottomTab.HOME, onHomeClick) { tint ->
|
||||||
|
NavIcon(R.drawable.ic_home, tint)
|
||||||
NavItem(iconRes = R.drawable.ic_friends, label = stringResource(R.string.nav_friends), active = current == BottomTab.FRIENDS, onClick = onFriendsClick)
|
}
|
||||||
NavItem(iconRes = R.drawable.ic_settings, label = stringResource(R.string.nav_settings), active = current == BottomTab.SETTINGS, onClick = onSettingsClick)
|
NavItem(stringResource(R.string.nav_friends), current == BottomTab.FRIENDS, onFriendsClick) { tint ->
|
||||||
|
NavIcon(R.drawable.ic_friends, tint)
|
||||||
AccountNavItem(
|
}
|
||||||
avatarBase64 = accountAvatarBase64,
|
NavItem(stringResource(R.string.nav_settings), current == BottomTab.SETTINGS, onSettingsClick) { tint ->
|
||||||
active = current == BottomTab.ACCOUNT,
|
NavIcon(R.drawable.ic_settings, tint)
|
||||||
onClick = onAccountClick
|
}
|
||||||
)
|
NavItem(stringResource(R.string.account_title), current == BottomTab.ACCOUNT, onAccountClick) { tint ->
|
||||||
|
val bitmap = rememberChatImage(accountAvatarBase64, AVATAR_MAX_DIMENSION_PX)
|
||||||
|
if (bitmap != null) {
|
||||||
|
Image(
|
||||||
|
bitmap = bitmap,
|
||||||
|
contentDescription = null,
|
||||||
|
contentScale = ContentScale.Crop,
|
||||||
|
modifier = Modifier.size(24.dp).clip(CircleShape)
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
NavIcon(R.drawable.ic_default_avatar, tint)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every screen has its own bar, so a tab never changes between active and inactive while shown. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun RowScope.NavItem(iconRes: Int, label: String, active: Boolean, onClick: () -> Unit) {
|
private fun RowScope.NavItem(
|
||||||
|
label: String,
|
||||||
|
active: Boolean,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
icon: @Composable (tint: Color) -> Unit
|
||||||
|
) {
|
||||||
val shape = RoundedCornerShape(UiCornerRadius)
|
val shape = RoundedCornerShape(UiCornerRadius)
|
||||||
|
val itemColor = if (active) ink else ink.copy(alpha = 0.7f)
|
||||||
val highlight by animateColorAsState(
|
|
||||||
if (active) ink.copy(alpha = 0.14f) else ink.copy(alpha = 0f),
|
|
||||||
animationSpec = tween(220),
|
|
||||||
label = "navHighlight"
|
|
||||||
)
|
|
||||||
val itemColor by animateColorAsState(
|
|
||||||
if (active) ink else ink.copy(alpha = 0.7f),
|
|
||||||
animationSpec = tween(220),
|
|
||||||
label = "navColor"
|
|
||||||
)
|
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.weight(1f)
|
.weight(1f)
|
||||||
.clip(shape)
|
.clip(shape)
|
||||||
.background(highlight, shape)
|
.background(if (active) ink.copy(alpha = 0.14f) else ink.copy(alpha = 0f), shape)
|
||||||
.clickable(onClick = onClick)
|
.clickable(onClick = onClick)
|
||||||
.padding(vertical = 8.dp),
|
.padding(vertical = 8.dp),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
) {
|
) {
|
||||||
Image(
|
icon(itemColor)
|
||||||
painter = painterResource(iconRes),
|
|
||||||
contentDescription = null,
|
|
||||||
colorFilter = ColorFilter.tint(itemColor),
|
|
||||||
modifier = Modifier.size(24.dp)
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
label,
|
label,
|
||||||
@@ -106,48 +106,11 @@ private fun RowScope.NavItem(iconRes: Int, label: String, active: Boolean, onCli
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun RowScope.AccountNavItem(avatarBase64: String?, active: Boolean, onClick: () -> Unit) {
|
private fun NavIcon(iconRes: Int, tint: Color) {
|
||||||
val shape = RoundedCornerShape(UiCornerRadius)
|
Image(
|
||||||
val bitmap = rememberChatImage(avatarBase64, AVATAR_MAX_DIMENSION_PX)
|
painter = painterResource(iconRes),
|
||||||
val highlight by animateColorAsState(
|
contentDescription = null,
|
||||||
if (active) ink.copy(alpha = 0.14f) else ink.copy(alpha = 0f),
|
colorFilter = ColorFilter.tint(tint),
|
||||||
animationSpec = tween(220),
|
modifier = Modifier.size(24.dp)
|
||||||
label = "navHighlight"
|
|
||||||
)
|
)
|
||||||
val itemColor by animateColorAsState(
|
|
||||||
if (active) ink else ink.copy(alpha = 0.7f),
|
|
||||||
animationSpec = tween(220),
|
|
||||||
label = "navColor"
|
|
||||||
)
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.weight(1f)
|
|
||||||
.clip(shape)
|
|
||||||
.background(highlight, shape)
|
|
||||||
.clickable(onClick = onClick)
|
|
||||||
.padding(vertical = 8.dp),
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally
|
|
||||||
) {
|
|
||||||
if (bitmap != null) {
|
|
||||||
Image(
|
|
||||||
bitmap = bitmap,
|
|
||||||
contentDescription = null,
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
modifier = Modifier.size(24.dp).clip(CircleShape)
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Image(
|
|
||||||
painter = painterResource(R.drawable.ic_default_avatar),
|
|
||||||
contentDescription = null,
|
|
||||||
colorFilter = ColorFilter.tint(itemColor),
|
|
||||||
modifier = Modifier.size(24.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.height(4.dp))
|
|
||||||
Text(
|
|
||||||
stringResource(R.string.account_title),
|
|
||||||
color = if (active) itemColor else Color.Transparent,
|
|
||||||
style = MaterialTheme.typography.labelMedium
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -156,12 +156,11 @@ fun AppDialog(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun DialogText(text: String, modifier: Modifier = Modifier) {
|
fun DialogText(text: String) {
|
||||||
Text(
|
Text(
|
||||||
text,
|
text,
|
||||||
color = ink.copy(alpha = 0.78f),
|
color = ink.copy(alpha = 0.78f),
|
||||||
style = MaterialTheme.typography.bodyLarge,
|
style = MaterialTheme.typography.bodyLarge
|
||||||
modifier = modifier
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,9 +15,8 @@ import androidx.compose.material3.Text
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import cc.skysparkle.matewave.engine.Piece
|
|
||||||
import cc.skysparkle.matewave.engine.PieceColor
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
import cc.skysparkle.matewave.engine.PieceType
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
|
|
||||||
@@ -25,11 +24,11 @@ import cc.skysparkle.matewave.engine.PieceType
|
|||||||
fun CapturedPiecesRow(
|
fun CapturedPiecesRow(
|
||||||
captured: List<PieceType>,
|
captured: List<PieceType>,
|
||||||
capturedColor: PieceColor,
|
capturedColor: PieceColor,
|
||||||
advantage: Int,
|
advantage: Int
|
||||||
modifier: Modifier = Modifier
|
|
||||||
) {
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier.fillMaxWidth().height(22.dp),
|
modifier = Modifier.fillMaxWidth().height(22.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), verticalAlignment = Alignment.CenterVertically) {
|
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
@@ -37,7 +36,7 @@ fun CapturedPiecesRow(
|
|||||||
Row(horizontalArrangement = Arrangement.spacedBy((-10).dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy((-10).dp)) {
|
||||||
repeat(group.size) {
|
repeat(group.size) {
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(Piece(type, capturedColor).drawableRes()),
|
bitmap = PieceImages.of(context, type, capturedColor),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(20.dp)
|
modifier = Modifier.size(20.dp)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ fun ChatDialog(
|
|||||||
},
|
},
|
||||||
enabled = text.isNotBlank()
|
enabled = text.isNotBlank()
|
||||||
) {
|
) {
|
||||||
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp)
|
AppIcon(R.drawable.ic_send, size = 20.dp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import android.content.Context
|
|||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
import android.graphics.Paint
|
import android.graphics.Paint
|
||||||
import android.graphics.Typeface
|
import android.graphics.Typeface
|
||||||
import androidx.compose.foundation.Canvas
|
|
||||||
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
|
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
|
||||||
import androidx.compose.foundation.gestures.detectTapGestures
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.aspectRatio
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -16,6 +16,7 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberUpdatedState
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.drawWithCache
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.geometry.Size
|
import androidx.compose.ui.geometry.Size
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
@@ -43,7 +44,8 @@ import cc.skysparkle.matewave.ui.theme.HighlightMove
|
|||||||
import kotlin.math.floor
|
import kotlin.math.floor
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
private object PieceImages {
|
/** The twelve piece pictures, decoded once and shared by the board and the other piece views. */
|
||||||
|
internal object PieceImages {
|
||||||
@Volatile private var cache: Array<ImageBitmap>? = null
|
@Volatile private var cache: Array<ImageBitmap>? = null
|
||||||
|
|
||||||
fun get(context: Context): Array<ImageBitmap> {
|
fun get(context: Context): Array<ImageBitmap> {
|
||||||
@@ -51,9 +53,9 @@ private object PieceImages {
|
|||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
cache?.let { return it }
|
cache?.let { return it }
|
||||||
val options = BitmapFactory.Options().apply { inScaled = false }
|
val options = BitmapFactory.Options().apply { inScaled = false }
|
||||||
val types = PieceType.values()
|
val types = PieceType.entries
|
||||||
val loaded = Array(PieceColor.values().size * types.size) { i ->
|
val loaded = Array(PieceColor.entries.size * types.size) { i ->
|
||||||
val piece = Piece(types[i % types.size], PieceColor.values()[i / types.size])
|
val piece = Piece(types[i % types.size], PieceColor.entries[i / types.size])
|
||||||
BitmapFactory.decodeResource(context.resources, piece.drawableRes(), options).asImageBitmap()
|
BitmapFactory.decodeResource(context.resources, piece.drawableRes(), options).asImageBitmap()
|
||||||
}
|
}
|
||||||
cache = loaded
|
cache = loaded
|
||||||
@@ -61,7 +63,9 @@ private object PieceImages {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun indexOf(piece: Piece): Int = piece.color.ordinal * PieceType.values().size + piece.type.ordinal
|
fun of(context: Context, type: PieceType, color: PieceColor): ImageBitmap = get(context)[indexOf(type, color)]
|
||||||
|
|
||||||
|
fun indexOf(type: PieceType, color: PieceColor): Int = color.ordinal * PieceType.entries.size + type.ordinal
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -83,12 +87,14 @@ fun ChessBoardView(
|
|||||||
highlightLastMove: Boolean? = null
|
highlightLastMove: Boolean? = null
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
// Read once: the appearance changes only in settings, while no board is on screen.
|
||||||
val appearance = remember { BoardAppearance(context) }
|
val appearance = remember { BoardAppearance(context) }
|
||||||
val theme = appearance.theme
|
val theme = remember { appearance.theme }
|
||||||
val showCoords = appearance.showCoordinates
|
val showCoords = remember { appearance.showCoordinates }
|
||||||
val imagePieces = appearance.useImagePieces
|
val imagePieces = remember { appearance.useImagePieces }
|
||||||
val showLastMove = highlightLastMove ?: appearance.showLastMove
|
val lastMoveSetting = remember { appearance.showLastMove }
|
||||||
val showCheck = appearance.showCheckHighlight
|
val showLastMove = highlightLastMove ?: lastMoveSetting
|
||||||
|
val showCheck = remember { appearance.showCheckHighlight }
|
||||||
|
|
||||||
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
||||||
|
|
||||||
@@ -113,7 +119,7 @@ fun ChessBoardView(
|
|||||||
var dragSquare by remember { mutableStateOf<Int?>(null) }
|
var dragSquare by remember { mutableStateOf<Int?>(null) }
|
||||||
var dragPos by remember { mutableStateOf<Offset?>(null) }
|
var dragPos by remember { mutableStateOf<Offset?>(null) }
|
||||||
|
|
||||||
Canvas(
|
Spacer(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.aspectRatio(1f)
|
.aspectRatio(1f)
|
||||||
@@ -169,151 +175,161 @@ fun ChessBoardView(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
) {
|
.drawWithCache {
|
||||||
val cell = size.width / 8f
|
// Sizes and text metrics change only with the board size.
|
||||||
val lastFrom = if (showLastMove) (lastMove?.from ?: -1) else -1
|
val cell = size.width / 8f
|
||||||
val lastTo = if (showLastMove) (lastMove?.to ?: -1) else -1
|
val pieceSize = cell * 0.86f
|
||||||
val selected = selectedSquare ?: -1
|
val inset = (cell - pieceSize) / 2f
|
||||||
val checkSquare = if (showCheck) (kingInCheckSquare ?: -1) else -1
|
val pieceDst = IntSize(pieceSize.roundToInt(), pieceSize.roundToInt())
|
||||||
val hint = hintSquare ?: -1
|
|
||||||
val flash = flashSquare ?: -1
|
|
||||||
|
|
||||||
val dSq = dragSquare
|
|
||||||
val dPos = dragPos
|
|
||||||
val liftedSq = if (dSq != null && dPos != null && selected == dSq) dSq else -1
|
|
||||||
val liftedAt: Offset? = if (liftedSq >= 0) dPos else null
|
|
||||||
|
|
||||||
for (row in 0 until 8) {
|
|
||||||
for (col in 0 until 8) {
|
|
||||||
val displayRank = if (flipped) row else 7 - row
|
|
||||||
val displayFile = if (flipped) 7 - col else col
|
|
||||||
val sqIndex = displayRank * 8 + displayFile
|
|
||||||
val isLight = (displayRank + displayFile) % 2 == 1
|
|
||||||
var color = if (isLight) theme.light else theme.dark
|
|
||||||
if (sqIndex == lastFrom || sqIndex == lastTo) color = HighlightLastMove
|
|
||||||
if (sqIndex == hint) color = HighlightHint
|
|
||||||
if (sqIndex == selected) color = HighlightMove
|
|
||||||
if (sqIndex == checkSquare) color = HighlightCheck
|
|
||||||
drawRect(
|
|
||||||
color = color,
|
|
||||||
topLeft = Offset(col * cell, row * cell),
|
|
||||||
size = Size(cell, cell)
|
|
||||||
)
|
|
||||||
if (sqIndex == flash) {
|
|
||||||
drawRect(color = flashColor, topLeft = Offset(col * cell, row * cell), size = Size(cell, cell))
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showCoords) {
|
|
||||||
val labelColor = if (isLight) theme.dark else theme.light
|
|
||||||
if (row == 7) {
|
|
||||||
drawCoordinate(
|
|
||||||
('a' + displayFile).toString(),
|
|
||||||
Offset(col * cell + cell * 0.78f, row * cell + cell * 0.80f),
|
|
||||||
cell, labelColor, coordPaint
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (col == 0) {
|
|
||||||
drawCoordinate(
|
|
||||||
(displayRank + 1).toString(),
|
|
||||||
Offset(col * cell + cell * 0.10f, row * cell + cell * 0.22f),
|
|
||||||
cell, labelColor, coordPaint
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ((targetMask shr sqIndex) and 1L != 0L) {
|
|
||||||
drawCircle(
|
|
||||||
color = HighlightMove,
|
|
||||||
radius = cell * 0.14f,
|
|
||||||
center = Offset(col * cell + cell / 2, row * cell + cell / 2)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val pieceSize = cell * 0.86f
|
|
||||||
val inset = (cell - pieceSize) / 2f
|
|
||||||
val pieceDst = IntSize(pieceSize.roundToInt(), pieceSize.roundToInt())
|
|
||||||
if (pieceImages == null) {
|
|
||||||
glyphPaint.textSize = cell * 0.62f
|
|
||||||
glyphPaint.color = GLYPH_COLOR
|
|
||||||
}
|
|
||||||
for (row in 0 until 8) {
|
|
||||||
for (col in 0 until 8) {
|
|
||||||
val displayRank = if (flipped) row else 7 - row
|
|
||||||
val displayFile = if (flipped) 7 - col else col
|
|
||||||
val pieceSq = displayRank * 8 + displayFile
|
|
||||||
if (pieceSq == liftedSq) continue
|
|
||||||
val piece = board.pieceAt(pieceSq) ?: continue
|
|
||||||
if (pieceImages != null) {
|
|
||||||
drawImage(
|
|
||||||
image = pieceImages[PieceImages.indexOf(piece)],
|
|
||||||
dstOffset = IntOffset(
|
|
||||||
(col * cell + inset).roundToInt(),
|
|
||||||
(row * cell + inset).roundToInt()
|
|
||||||
),
|
|
||||||
dstSize = pieceDst,
|
|
||||||
filterQuality = FilterQuality.Medium
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
val metrics = glyphPaint.fontMetrics
|
|
||||||
drawContext.canvas.nativeCanvas.drawText(
|
|
||||||
piece.unicode(),
|
|
||||||
col * cell + cell / 2f,
|
|
||||||
row * cell + cell / 2f - (metrics.ascent + metrics.descent) / 2f,
|
|
||||||
glyphPaint
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (liftedAt != null) {
|
|
||||||
val liftedPiece = board.pieceAt(liftedSq)
|
|
||||||
if (liftedPiece != null) {
|
|
||||||
val hover = squareAt(liftedAt.x, liftedAt.y, size.width, flipped)
|
|
||||||
if (hover >= 0 && ((targetMask shr hover) and 1L) != 0L) {
|
|
||||||
val hRank = hover / 8
|
|
||||||
val hFile = hover % 8
|
|
||||||
val hRow = if (flipped) hRank else 7 - hRank
|
|
||||||
val hCol = if (flipped) 7 - hFile else hFile
|
|
||||||
drawRect(
|
|
||||||
color = Color.White.copy(alpha = 0.75f),
|
|
||||||
topLeft = Offset(hCol * cell, hRow * cell),
|
|
||||||
size = Size(cell, cell),
|
|
||||||
style = Stroke(width = cell * 0.07f)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
val liftedSize = pieceSize * LIFT_SCALE
|
val liftedSize = pieceSize * LIFT_SCALE
|
||||||
val cx = liftedAt.x
|
val liftedDst = IntSize(liftedSize.roundToInt(), liftedSize.roundToInt())
|
||||||
val cy = liftedAt.y - cell * 0.55f
|
val hoverStroke = Stroke(width = cell * 0.07f)
|
||||||
drawOval(
|
val glyphSize = cell * 0.62f
|
||||||
color = Color.Black.copy(alpha = 0.30f),
|
glyphPaint.textSize = glyphSize
|
||||||
topLeft = Offset(liftedAt.x - liftedSize * 0.36f, liftedAt.y + cell * 0.05f),
|
val glyphMetrics = glyphPaint.fontMetrics
|
||||||
size = Size(liftedSize * 0.72f, liftedSize * 0.28f)
|
val glyphShift = (glyphMetrics.ascent + glyphMetrics.descent) / 2f
|
||||||
)
|
glyphPaint.textSize = glyphSize * LIFT_SCALE
|
||||||
if (pieceImages != null) {
|
val liftedMetrics = glyphPaint.fontMetrics
|
||||||
val liftedDst = IntSize(liftedSize.roundToInt(), liftedSize.roundToInt())
|
val liftedGlyphShift = (liftedMetrics.ascent + liftedMetrics.descent) / 2f
|
||||||
drawImage(
|
onDrawBehind {
|
||||||
image = pieceImages[PieceImages.indexOf(liftedPiece)],
|
val lastFrom = if (showLastMove) (lastMove?.from ?: -1) else -1
|
||||||
dstOffset = IntOffset(
|
val lastTo = if (showLastMove) (lastMove?.to ?: -1) else -1
|
||||||
(cx - liftedSize / 2f).roundToInt(),
|
val selected = selectedSquare ?: -1
|
||||||
(cy - liftedSize / 2f).roundToInt()
|
val checkSquare = if (showCheck) (kingInCheckSquare ?: -1) else -1
|
||||||
),
|
val hint = hintSquare ?: -1
|
||||||
dstSize = liftedDst,
|
val flash = flashSquare ?: -1
|
||||||
filterQuality = FilterQuality.Medium
|
|
||||||
)
|
val dSq = dragSquare
|
||||||
} else {
|
val dPos = dragPos
|
||||||
glyphPaint.textSize = cell * 0.62f * LIFT_SCALE
|
val liftedSq = if (dSq != null && dPos != null && selected == dSq) dSq else -1
|
||||||
val metrics = glyphPaint.fontMetrics
|
val liftedAt: Offset? = if (liftedSq >= 0) dPos else null
|
||||||
drawContext.canvas.nativeCanvas.drawText(
|
|
||||||
liftedPiece.unicode(),
|
for (row in 0 until 8) {
|
||||||
cx,
|
for (col in 0 until 8) {
|
||||||
cy - (metrics.ascent + metrics.descent) / 2f,
|
val displayRank = if (flipped) row else 7 - row
|
||||||
glyphPaint
|
val displayFile = if (flipped) 7 - col else col
|
||||||
)
|
val sqIndex = displayRank * 8 + displayFile
|
||||||
|
val isLight = (displayRank + displayFile) % 2 == 1
|
||||||
|
var color = if (isLight) theme.light else theme.dark
|
||||||
|
if (sqIndex == lastFrom || sqIndex == lastTo) color = HighlightLastMove
|
||||||
|
if (sqIndex == hint) color = HighlightHint
|
||||||
|
if (sqIndex == selected) color = HighlightMove
|
||||||
|
if (sqIndex == checkSquare) color = HighlightCheck
|
||||||
|
drawRect(
|
||||||
|
color = color,
|
||||||
|
topLeft = Offset(col * cell, row * cell),
|
||||||
|
size = Size(cell, cell)
|
||||||
|
)
|
||||||
|
if (sqIndex == flash) {
|
||||||
|
drawRect(color = flashColor, topLeft = Offset(col * cell, row * cell), size = Size(cell, cell))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showCoords) {
|
||||||
|
val labelColor = if (isLight) theme.dark else theme.light
|
||||||
|
if (row == 7) {
|
||||||
|
drawCoordinate(
|
||||||
|
FILE_LABELS[displayFile],
|
||||||
|
Offset(col * cell + cell * 0.78f, row * cell + cell * 0.80f),
|
||||||
|
cell, labelColor, coordPaint
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (col == 0) {
|
||||||
|
drawCoordinate(
|
||||||
|
RANK_LABELS[displayRank],
|
||||||
|
Offset(col * cell + cell * 0.10f, row * cell + cell * 0.22f),
|
||||||
|
cell, labelColor, coordPaint
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((targetMask shr sqIndex) and 1L != 0L) {
|
||||||
|
drawCircle(
|
||||||
|
color = HighlightMove,
|
||||||
|
radius = cell * 0.14f,
|
||||||
|
center = Offset(col * cell + cell / 2, row * cell + cell / 2)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pieceImages == null) {
|
||||||
|
glyphPaint.textSize = glyphSize
|
||||||
|
glyphPaint.color = GLYPH_COLOR
|
||||||
|
}
|
||||||
|
for (row in 0 until 8) {
|
||||||
|
for (col in 0 until 8) {
|
||||||
|
val displayRank = if (flipped) row else 7 - row
|
||||||
|
val displayFile = if (flipped) 7 - col else col
|
||||||
|
val pieceSq = displayRank * 8 + displayFile
|
||||||
|
if (pieceSq == liftedSq) continue
|
||||||
|
val piece = board.pieceAt(pieceSq) ?: continue
|
||||||
|
if (pieceImages != null) {
|
||||||
|
drawImage(
|
||||||
|
image = pieceImages[PieceImages.indexOf(piece.type, piece.color)],
|
||||||
|
dstOffset = IntOffset(
|
||||||
|
(col * cell + inset).roundToInt(),
|
||||||
|
(row * cell + inset).roundToInt()
|
||||||
|
),
|
||||||
|
dstSize = pieceDst,
|
||||||
|
filterQuality = FilterQuality.Medium
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
drawContext.canvas.nativeCanvas.drawText(
|
||||||
|
piece.unicode(),
|
||||||
|
col * cell + cell / 2f,
|
||||||
|
row * cell + cell / 2f - glyphShift,
|
||||||
|
glyphPaint
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (liftedAt != null) {
|
||||||
|
val liftedPiece = board.pieceAt(liftedSq)
|
||||||
|
if (liftedPiece != null) {
|
||||||
|
val hover = squareAt(liftedAt.x, liftedAt.y, size.width, flipped)
|
||||||
|
if (hover >= 0 && ((targetMask shr hover) and 1L) != 0L) {
|
||||||
|
val hRank = hover / 8
|
||||||
|
val hFile = hover % 8
|
||||||
|
val hRow = if (flipped) hRank else 7 - hRank
|
||||||
|
val hCol = if (flipped) 7 - hFile else hFile
|
||||||
|
drawRect(
|
||||||
|
color = Color.White.copy(alpha = 0.75f),
|
||||||
|
topLeft = Offset(hCol * cell, hRow * cell),
|
||||||
|
size = Size(cell, cell),
|
||||||
|
style = hoverStroke
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val cx = liftedAt.x
|
||||||
|
val cy = liftedAt.y - cell * 0.55f
|
||||||
|
drawOval(
|
||||||
|
color = Color.Black.copy(alpha = 0.30f),
|
||||||
|
topLeft = Offset(liftedAt.x - liftedSize * 0.36f, liftedAt.y + cell * 0.05f),
|
||||||
|
size = Size(liftedSize * 0.72f, liftedSize * 0.28f)
|
||||||
|
)
|
||||||
|
if (pieceImages != null) {
|
||||||
|
drawImage(
|
||||||
|
image = pieceImages[PieceImages.indexOf(liftedPiece.type, liftedPiece.color)],
|
||||||
|
dstOffset = IntOffset(
|
||||||
|
(cx - liftedSize / 2f).roundToInt(),
|
||||||
|
(cy - liftedSize / 2f).roundToInt()
|
||||||
|
),
|
||||||
|
dstSize = liftedDst,
|
||||||
|
filterQuality = FilterQuality.Medium
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
glyphPaint.textSize = glyphSize * LIFT_SCALE
|
||||||
|
drawContext.canvas.nativeCanvas.drawText(
|
||||||
|
liftedPiece.unicode(),
|
||||||
|
cx,
|
||||||
|
cy - liftedGlyphShift,
|
||||||
|
glyphPaint
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val LIFT_SCALE = 1.6f
|
private const val LIFT_SCALE = 1.6f
|
||||||
@@ -330,6 +346,9 @@ private fun squareAt(x: Float, y: Float, boardPx: Float, flipped: Boolean): Int
|
|||||||
|
|
||||||
private val GLYPH_COLOR = Color(0xFF1B1B1B).toArgb()
|
private val GLYPH_COLOR = Color(0xFF1B1B1B).toArgb()
|
||||||
|
|
||||||
|
private val FILE_LABELS = Array(8) { ('a' + it).toString() }
|
||||||
|
private val RANK_LABELS = Array(8) { (it + 1).toString() }
|
||||||
|
|
||||||
private fun DrawScope.drawCoordinate(
|
private fun DrawScope.drawCoordinate(
|
||||||
text: String,
|
text: String,
|
||||||
position: Offset,
|
position: Offset,
|
||||||
|
|||||||
@@ -7,11 +7,9 @@ import androidx.compose.animation.core.spring
|
|||||||
import androidx.compose.foundation.LocalIndication
|
import androidx.compose.foundation.LocalIndication
|
||||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
import androidx.compose.runtime.CompositionLocalProvider
|
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import cc.skysparkle.matewave.ui.theme.LocalInk
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
@@ -30,7 +28,6 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.layout.widthIn
|
import androidx.compose.foundation.layout.widthIn
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
@@ -41,82 +38,74 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.alpha
|
import androidx.compose.ui.draw.alpha
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.Shape
|
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
|
import cc.skysparkle.matewave.ui.theme.GlassShape
|
||||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||||
import cc.skysparkle.matewave.ui.theme.PanelFill
|
import cc.skysparkle.matewave.ui.theme.PanelFill
|
||||||
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
||||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
|
||||||
import cc.skysparkle.matewave.ui.theme.glass
|
import cc.skysparkle.matewave.ui.theme.glass
|
||||||
|
|
||||||
private val UiShape: Shape = RoundedCornerShape(UiCornerRadius)
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun GlassScaffold(
|
fun GlassScaffold(
|
||||||
title: String,
|
title: String,
|
||||||
onBack: (() -> Unit)? = null,
|
onBack: (() -> Unit)? = null,
|
||||||
actions: @Composable RowScope.() -> Unit = {},
|
actions: @Composable RowScope.() -> Unit = {},
|
||||||
scrollable: Boolean = true,
|
|
||||||
|
|
||||||
bottomBar: (@Composable () -> Unit)? = null,
|
bottomBar: (@Composable () -> Unit)? = null,
|
||||||
/** Replaces the plain title, e.g. with the opening name and its status badge. */
|
/** Replaces the plain title, e.g. with the opening name and its status badge. */
|
||||||
titleContent: (@Composable RowScope.() -> Unit)? = null,
|
titleContent: (@Composable RowScope.() -> Unit)? = null,
|
||||||
content: @Composable ColumnScope.() -> Unit
|
content: @Composable ColumnScope.() -> Unit
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
||||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
|
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
||||||
Column(modifier = Modifier.fillMaxSize().widthIn(max = TabletMaxContentWidth)) {
|
Row(
|
||||||
Row(
|
modifier = Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 4.dp, vertical = 4.dp),
|
||||||
modifier = Modifier.fillMaxWidth().statusBarsPadding().padding(horizontal = 4.dp, vertical = 4.dp),
|
verticalAlignment = Alignment.CenterVertically
|
||||||
verticalAlignment = Alignment.CenterVertically
|
) {
|
||||||
) {
|
if (onBack != null) {
|
||||||
if (onBack != null) {
|
IconButton(onClick = onBack) {
|
||||||
IconButton(onClick = onBack) {
|
AppIcon(
|
||||||
AppIcon(
|
R.drawable.ic_arrow_back,
|
||||||
R.drawable.ic_arrow_back,
|
size = 24.dp,
|
||||||
size = 24.dp,
|
contentDescription = stringResource(R.string.back)
|
||||||
contentDescription = stringResource(R.string.back)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Spacer(Modifier.width(48.dp))
|
|
||||||
}
|
|
||||||
if (titleContent != null) {
|
|
||||||
Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, content = titleContent)
|
|
||||||
} else {
|
|
||||||
Text(
|
|
||||||
title,
|
|
||||||
color = ink,
|
|
||||||
style = MaterialTheme.typography.titleLarge,
|
|
||||||
modifier = Modifier.weight(1f)
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
actions()
|
} else {
|
||||||
|
Spacer(Modifier.width(48.dp))
|
||||||
}
|
}
|
||||||
|
if (titleContent != null) {
|
||||||
val scrollState = rememberScrollState()
|
Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, content = titleContent)
|
||||||
|
} else {
|
||||||
val contentModifier = Modifier
|
Text(
|
||||||
.fillMaxWidth()
|
title,
|
||||||
.weight(1f)
|
color = ink,
|
||||||
.padding(horizontal = 16.dp)
|
style = MaterialTheme.typography.titleLarge,
|
||||||
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
|
modifier = Modifier.weight(1f)
|
||||||
.then(if (bottomBar == null) Modifier.navigationBarsPadding() else Modifier)
|
)
|
||||||
.padding(bottom = 16.dp)
|
|
||||||
|
|
||||||
Column(
|
|
||||||
modifier = contentModifier,
|
|
||||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
|
||||||
content = content
|
|
||||||
)
|
|
||||||
|
|
||||||
if (bottomBar != null) {
|
|
||||||
Box(modifier = Modifier.navigationBarsPadding()) { bottomBar() }
|
|
||||||
}
|
}
|
||||||
|
actions()
|
||||||
|
}
|
||||||
|
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
|
||||||
|
val contentModifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.weight(1f)
|
||||||
|
.padding(horizontal = 16.dp)
|
||||||
|
.verticalScroll(scrollState)
|
||||||
|
.then(if (bottomBar == null) Modifier.navigationBarsPadding() else Modifier)
|
||||||
|
.padding(bottom = 16.dp)
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = contentModifier,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
content = content
|
||||||
|
)
|
||||||
|
|
||||||
|
if (bottomBar != null) {
|
||||||
|
Box(modifier = Modifier.navigationBarsPadding()) { bottomBar() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,44 +130,12 @@ fun GlassButton(
|
|||||||
content: @Composable RowScope.() -> Unit
|
content: @Composable RowScope.() -> Unit
|
||||||
) {
|
) {
|
||||||
val interaction = remember { MutableInteractionSource() }
|
val interaction = remember { MutableInteractionSource() }
|
||||||
|
|
||||||
CompositionLocalProvider(LocalInk provides Color.White) {
|
|
||||||
Row(
|
|
||||||
modifier = modifier
|
|
||||||
.pressScale(interaction)
|
|
||||||
.alpha(if (enabled) 1f else 0.4f)
|
|
||||||
.clip(UiShape)
|
|
||||||
.background(ChessGreen)
|
|
||||||
.then(
|
|
||||||
if (enabled) Modifier.clickable(
|
|
||||||
interactionSource = interaction,
|
|
||||||
indication = LocalIndication.current,
|
|
||||||
onClick = onClick
|
|
||||||
) else Modifier
|
|
||||||
)
|
|
||||||
.padding(horizontal = 20.dp, vertical = 14.dp),
|
|
||||||
horizontalArrangement = Arrangement.Center,
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
content = content
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun GlassOutlinedButton(
|
|
||||||
onClick: () -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
enabled: Boolean = true,
|
|
||||||
content: @Composable RowScope.() -> Unit
|
|
||||||
) {
|
|
||||||
val interaction = remember { MutableInteractionSource() }
|
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.pressScale(interaction)
|
.pressScale(interaction)
|
||||||
.alpha(if (enabled) 1f else 0.4f)
|
.alpha(if (enabled) 1f else 0.4f)
|
||||||
.clip(UiShape)
|
.clip(GlassShape)
|
||||||
.background(PanelFill)
|
.background(ChessGreen)
|
||||||
.border(1.dp, PanelBorder, UiShape)
|
|
||||||
.then(
|
.then(
|
||||||
if (enabled) Modifier.clickable(
|
if (enabled) Modifier.clickable(
|
||||||
interactionSource = interaction,
|
interactionSource = interaction,
|
||||||
@@ -194,11 +151,40 @@ fun GlassOutlinedButton(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun GlassCard(modifier: Modifier = Modifier, shape: Shape = UiShape, content: @Composable ColumnScope.() -> Unit) {
|
fun GlassOutlinedButton(
|
||||||
|
onClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
enabled: Boolean = true,
|
||||||
|
content: @Composable RowScope.() -> Unit
|
||||||
|
) {
|
||||||
|
val interaction = remember { MutableInteractionSource() }
|
||||||
|
Row(
|
||||||
|
modifier = modifier
|
||||||
|
.pressScale(interaction)
|
||||||
|
.alpha(if (enabled) 1f else 0.4f)
|
||||||
|
.clip(GlassShape)
|
||||||
|
.background(PanelFill)
|
||||||
|
.border(1.dp, PanelBorder, GlassShape)
|
||||||
|
.then(
|
||||||
|
if (enabled) Modifier.clickable(
|
||||||
|
interactionSource = interaction,
|
||||||
|
indication = LocalIndication.current,
|
||||||
|
onClick = onClick
|
||||||
|
) else Modifier
|
||||||
|
)
|
||||||
|
.padding(horizontal = 20.dp, vertical = 14.dp),
|
||||||
|
horizontalArrangement = Arrangement.Center,
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
content = content
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun GlassCard(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||||
Column(
|
Column(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.glass(shape)
|
.glass()
|
||||||
.border(1.dp, PanelBorder, shape)
|
.border(1.dp, PanelBorder, GlassShape)
|
||||||
.padding(14.dp),
|
.padding(14.dp),
|
||||||
content = content
|
content = content
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
|||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -22,28 +21,22 @@ import androidx.compose.ui.graphics.Color
|
|||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
|
||||||
import cc.skysparkle.matewave.ui.theme.glass
|
import cc.skysparkle.matewave.ui.theme.glass
|
||||||
import cc.skysparkle.matewave.ui.theme.ink
|
import cc.skysparkle.matewave.ui.theme.ink
|
||||||
|
|
||||||
/** Small uppercase caption above a group. */
|
/** Small uppercase caption above a group. */
|
||||||
@Composable
|
@Composable
|
||||||
fun SectionCaption(text: String, modifier: Modifier = Modifier) {
|
fun SectionCaption(text: String) {
|
||||||
Text(
|
SetupSectionLabel(text, Modifier.padding(start = 4.dp, top = 6.dp))
|
||||||
text.uppercase(),
|
|
||||||
color = ink.copy(alpha = 0.5f),
|
|
||||||
style = MaterialTheme.typography.labelMedium,
|
|
||||||
modifier = modifier.padding(start = 4.dp, top = 6.dp)
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Rows of one kind in a single block, instead of a card per row. Separate rows with [ListDivider]. */
|
/** Rows of one kind in a single block, instead of a card per row. Separate rows with [ListDivider]. */
|
||||||
@Composable
|
@Composable
|
||||||
fun ListGroup(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
|
fun ListGroup(content: @Composable ColumnScope.() -> Unit) {
|
||||||
Column(
|
Column(
|
||||||
modifier = modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.glass(RoundedCornerShape(UiCornerRadius))
|
.glass()
|
||||||
.padding(vertical = 2.dp),
|
.padding(vertical = 2.dp),
|
||||||
content = content
|
content = content
|
||||||
)
|
)
|
||||||
@@ -67,11 +60,9 @@ fun ListDivider(inset: Int = 52) {
|
|||||||
@Composable
|
@Composable
|
||||||
fun ListRow(
|
fun ListRow(
|
||||||
title: String,
|
title: String,
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
subtitle: String? = null,
|
subtitle: String? = null,
|
||||||
icon: Int? = null,
|
icon: Int? = null,
|
||||||
iconTint: Color = ink,
|
iconTint: Color = ink,
|
||||||
titleColor: Color = ink,
|
|
||||||
subtitleColor: Color = ink.copy(alpha = 0.6f),
|
subtitleColor: Color = ink.copy(alpha = 0.6f),
|
||||||
value: String? = null,
|
value: String? = null,
|
||||||
valueColor: Color = ink.copy(alpha = 0.55f),
|
valueColor: Color = ink.copy(alpha = 0.55f),
|
||||||
@@ -81,7 +72,7 @@ fun ListRow(
|
|||||||
onClick: (() -> Unit)? = null
|
onClick: (() -> Unit)? = null
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||||
@@ -92,7 +83,7 @@ fun ListRow(
|
|||||||
icon != null -> { AppIcon(icon, size = 22.dp, tint = iconTint); Spacer(Modifier.width(14.dp)) }
|
icon != null -> { AppIcon(icon, size = 22.dp, tint = iconTint); Spacer(Modifier.width(14.dp)) }
|
||||||
}
|
}
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(title, color = titleColor, style = MaterialTheme.typography.bodyLarge, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
Text(title, color = ink, style = MaterialTheme.typography.bodyLarge, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
if (subtitle != null) {
|
if (subtitle != null) {
|
||||||
Text(subtitle, color = subtitleColor, style = MaterialTheme.typography.bodySmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
Text(subtitle, color = subtitleColor, style = MaterialTheme.typography.bodySmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
}
|
}
|
||||||
@@ -107,7 +98,7 @@ fun ListRow(
|
|||||||
}
|
}
|
||||||
if (chevron) {
|
if (chevron) {
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
AppIcon(R.drawable.ic_arrow_forward, size = 16.dp, tint = ink.copy(alpha = 0.5f))
|
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.7f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package cc.skysparkle.matewave.ui.components
|
package cc.skysparkle.matewave.ui.components
|
||||||
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
@@ -10,7 +9,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
|||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.lazy.LazyRow
|
import androidx.compose.foundation.lazy.LazyRow
|
||||||
import androidx.compose.foundation.lazy.itemsIndexed
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
@@ -34,25 +33,15 @@ import cc.skysparkle.matewave.ui.theme.ink
|
|||||||
private data class MoveToken(val text: String, val moveIndex: Int?)
|
private data class MoveToken(val text: String, val moveIndex: Int?)
|
||||||
|
|
||||||
private val BookTint = androidx.compose.ui.graphics.Color(0xFF93DBA3)
|
private val BookTint = androidx.compose.ui.graphics.Color(0xFF93DBA3)
|
||||||
private val OutOfBookTint = androidx.compose.ui.graphics.Color(0xFFFFB86B)
|
|
||||||
|
|
||||||
/**
|
/** Compact move list that scrolls to the last move, with the opening name underneath. */
|
||||||
* Compact move list that scrolls to the current move, with the opening name underneath.
|
|
||||||
* [currentIndex] is the number of moves played to reach the shown position.
|
|
||||||
*/
|
|
||||||
@Composable
|
@Composable
|
||||||
fun MovesBar(
|
fun MovesBar(
|
||||||
sans: List<String>,
|
sans: List<String>,
|
||||||
startBoard: Board,
|
startBoard: Board,
|
||||||
currentIndex: Int,
|
|
||||||
opening: OpeningName?,
|
opening: OpeningName?,
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
/** Leading moves that are opening theory; they are tinted in the list. */
|
/** Leading moves that are opening theory; they are tinted in the list. */
|
||||||
bookPlies: Int = 0,
|
bookPlies: Int = 0
|
||||||
/** "Theory" or "Out of book from move N"; null hides the status. */
|
|
||||||
bookStatus: String? = null,
|
|
||||||
inBook: Boolean = true,
|
|
||||||
onMoveClick: ((Int) -> Unit)? = null
|
|
||||||
) {
|
) {
|
||||||
if (sans.isEmpty() && opening == null) return
|
if (sans.isEmpty() && opening == null) return
|
||||||
val tokens = remember(sans, startBoard) {
|
val tokens = remember(sans, startBoard) {
|
||||||
@@ -67,15 +56,15 @@ fun MovesBar(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
val listState = rememberLazyListState()
|
val listState = rememberLazyListState()
|
||||||
LaunchedEffect(currentIndex, tokens.size) {
|
LaunchedEffect(sans.size, tokens.size) {
|
||||||
val target = tokens.indexOfFirst { it.moveIndex == currentIndex - 1 }
|
val target = tokens.indexOfFirst { it.moveIndex == sans.size - 1 }
|
||||||
if (target >= 0) listState.animateScrollToItem(maxOf(0, target - 3))
|
if (target >= 0) listState.animateScrollToItem(maxOf(0, target - 3))
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
if (sans.isNotEmpty()) {
|
if (sans.isNotEmpty()) {
|
||||||
LazyRow(state = listState, horizontalArrangement = Arrangement.spacedBy(2.dp)) {
|
LazyRow(state = listState, horizontalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||||
itemsIndexed(tokens) { _, token ->
|
items(tokens) { token ->
|
||||||
val index = token.moveIndex
|
val index = token.moveIndex
|
||||||
if (index == null) {
|
if (index == null) {
|
||||||
Text(
|
Text(
|
||||||
@@ -85,7 +74,7 @@ fun MovesBar(
|
|||||||
modifier = Modifier.padding(start = 6.dp, top = 4.dp, bottom = 4.dp)
|
modifier = Modifier.padding(start = 6.dp, top = 4.dp, bottom = 4.dp)
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
val current = index == currentIndex - 1
|
val current = index == sans.size - 1
|
||||||
Text(
|
Text(
|
||||||
token.text,
|
token.text,
|
||||||
color = if (index < bookPlies) BookTint else ink,
|
color = if (index < bookPlies) BookTint else ink,
|
||||||
@@ -94,38 +83,24 @@ fun MovesBar(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.clip(RoundedCornerShape(8.dp))
|
.clip(RoundedCornerShape(8.dp))
|
||||||
.then(if (current) Modifier.background(ChessGreen.copy(alpha = 0.45f)) else Modifier)
|
.then(if (current) Modifier.background(ChessGreen.copy(alpha = 0.45f)) else Modifier)
|
||||||
.then(if (onMoveClick != null) Modifier.clickable { onMoveClick(index + 1) } else Modifier)
|
|
||||||
.padding(horizontal = 6.dp, vertical = 4.dp)
|
.padding(horizontal = 6.dp, vertical = 4.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (opening != null || bookStatus != null) {
|
if (opening != null) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
AppIcon(R.drawable.ic_book, size = 14.dp, tint = if (inBook) BookTint else ink.copy(alpha = 0.5f))
|
AppIcon(R.drawable.ic_book, size = 16.dp, tint = BookTint)
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text(
|
Text(
|
||||||
opening?.let { "${it.eco} · ${it.name}" } ?: "",
|
"${opening.eco} · ${opening.name}",
|
||||||
color = ink.copy(alpha = 0.85f),
|
color = ink.copy(alpha = 0.85f),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
modifier = Modifier.weight(1f, fill = false)
|
modifier = Modifier.weight(1f, fill = false)
|
||||||
)
|
)
|
||||||
if (bookStatus != null) {
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
Text(
|
|
||||||
bookStatus,
|
|
||||||
color = if (inBook) BookTint else OutOfBookTint,
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
maxLines = 1,
|
|
||||||
modifier = Modifier
|
|
||||||
.clip(RoundedCornerShape(6.dp))
|
|
||||||
.background((if (inBook) BookTint else OutOfBookTint).copy(alpha = 0.15f))
|
|
||||||
.padding(horizontal = 6.dp, vertical = 2.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,14 +15,13 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.res.painterResource
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
import androidx.compose.ui.semantics.semantics
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
import cc.skysparkle.matewave.engine.Piece
|
|
||||||
import cc.skysparkle.matewave.engine.PieceColor
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
import cc.skysparkle.matewave.engine.PieceType
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||||
@@ -32,6 +31,7 @@ import cc.skysparkle.matewave.ui.theme.ink
|
|||||||
/** The four promotion pieces, drawn with the same images as the board. */
|
/** The four promotion pieces, drawn with the same images as the board. */
|
||||||
@Composable
|
@Composable
|
||||||
fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss: () -> Unit) {
|
fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
AppDialog(
|
AppDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
title = stringResource(R.string.promotion_title),
|
title = stringResource(R.string.promotion_title),
|
||||||
@@ -63,7 +63,7 @@ fun PromotionDialog(color: PieceColor, onChoose: (PieceType) -> Unit, onDismiss:
|
|||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
Image(
|
Image(
|
||||||
painter = painterResource(Piece(type, color).drawableRes()),
|
bitmap = PieceImages.of(context, type, color),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.fillMaxWidth().aspectRatio(1f)
|
modifier = Modifier.fillMaxWidth().aspectRatio(1f)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -20,10 +20,10 @@ import cc.skysparkle.matewave.ui.theme.ink
|
|||||||
|
|
||||||
/** Small, quiet spectator counter for the top bar: an eye and "7" or "7/20". */
|
/** Small, quiet spectator counter for the top bar: an eye and "7" or "7/20". */
|
||||||
@Composable
|
@Composable
|
||||||
fun SpectatorBadge(count: Int, max: Int? = null, modifier: Modifier = Modifier) {
|
fun SpectatorBadge(count: Int, max: Int? = null) {
|
||||||
val description = stringResource(R.string.spectators_description, count)
|
val description = stringResource(R.string.spectators_description, count)
|
||||||
Row(
|
Row(
|
||||||
modifier = modifier
|
modifier = Modifier
|
||||||
.padding(end = 12.dp)
|
.padding(end = 12.dp)
|
||||||
.clip(RoundedCornerShape(50))
|
.clip(RoundedCornerShape(50))
|
||||||
.background(ink.copy(alpha = 0.10f))
|
.background(ink.copy(alpha = 0.10f))
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ import cc.skysparkle.matewave.ui.components.AppBottomBar
|
|||||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||||
import cc.skysparkle.matewave.data.ProfileStore
|
import cc.skysparkle.matewave.data.ProfileStore
|
||||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||||
|
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||||
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
import cc.skysparkle.matewave.ui.components.rememberChatImage
|
import cc.skysparkle.matewave.ui.components.rememberChatImage
|
||||||
@@ -136,7 +137,6 @@ fun AccountScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
androidx.compose.runtime.CompositionLocalProvider(cc.skysparkle.matewave.ui.theme.LocalInk provides Color.White) {
|
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -239,7 +239,6 @@ fun AccountScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (profile.avatarBase64 != null || profile.backgroundBase64 != null) {
|
if (profile.avatarBase64 != null || profile.backgroundBase64 != null) {
|
||||||
Text(
|
Text(
|
||||||
@@ -247,7 +246,7 @@ fun AccountScreen(
|
|||||||
color = ink.copy(alpha = 0.55f),
|
color = ink.copy(alpha = 0.55f),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
modifier = Modifier.clickable {
|
modifier = Modifier.clickable {
|
||||||
ProfileStore.resetAvatarToDefault()
|
ProfileStore.setAvatar(null)
|
||||||
ProfileStore.setBackground(null)
|
ProfileStore.setBackground(null)
|
||||||
profile = ProfileStore.get()
|
profile = ProfileStore.get()
|
||||||
}
|
}
|
||||||
@@ -256,6 +255,7 @@ fun AccountScreen(
|
|||||||
|
|
||||||
if (!profile.levelChosen) {
|
if (!profile.levelChosen) {
|
||||||
GlassOutlinedButton(onClick = { showLevelPicker = true }, modifier = Modifier.fillMaxWidth()) {
|
GlassOutlinedButton(onClick = { showLevelPicker = true }, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
ButtonIcon(R.drawable.ic_speed)
|
||||||
Text(stringResource(R.string.account_choose_level), color = ink)
|
Text(stringResource(R.string.account_choose_level), color = ink)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,7 +266,7 @@ fun AccountScreen(
|
|||||||
val curve = remember(profile.elo) { cc.skysparkle.matewave.stats.Stats.ratingCurve(profile.elo) }
|
val curve = remember(profile.elo) { cc.skysparkle.matewave.stats.Stats.ratingCurve(profile.elo) }
|
||||||
ListRow(
|
ListRow(
|
||||||
title = stringResource(R.string.account_rating_row),
|
title = stringResource(R.string.account_rating_row),
|
||||||
icon = R.drawable.ic_license,
|
icon = R.drawable.ic_rating,
|
||||||
iconTint = ChessGreen,
|
iconTint = ChessGreen,
|
||||||
value = "${profile.elo}",
|
value = "${profile.elo}",
|
||||||
valueColor = ink,
|
valueColor = ink,
|
||||||
@@ -277,7 +277,7 @@ fun AccountScreen(
|
|||||||
ListDivider()
|
ListDivider()
|
||||||
ListRow(
|
ListRow(
|
||||||
title = stringResource(R.string.study_title),
|
title = stringResource(R.string.study_title),
|
||||||
icon = R.drawable.ic_crown,
|
icon = R.drawable.ic_study,
|
||||||
value = "${study.learnedCount}/${study.courses.size} · ★${study.masteredCount}",
|
value = "${study.learnedCount}/${study.courses.size} · ★${study.masteredCount}",
|
||||||
chevron = true,
|
chevron = true,
|
||||||
onClick = onStudyClick
|
onClick = onStudyClick
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ import cc.skysparkle.matewave.settings.BoardAppearance
|
|||||||
import cc.skysparkle.matewave.settings.BoardTheme
|
import cc.skysparkle.matewave.settings.BoardTheme
|
||||||
import cc.skysparkle.matewave.ui.components.GlassCard
|
import cc.skysparkle.matewave.ui.components.GlassCard
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
import cc.skysparkle.matewave.ui.theme.GlassBorder
|
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun AppearanceScreen(onBack: () -> Unit) {
|
fun AppearanceScreen(onBack: () -> Unit) {
|
||||||
@@ -125,7 +125,7 @@ fun AppearanceScreen(onBack: () -> Unit) {
|
|||||||
@Composable
|
@Composable
|
||||||
private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
private fun ThemePreview(theme: BoardTheme, showPieces: Boolean) {
|
||||||
val shape = RoundedCornerShape(6.dp)
|
val shape = RoundedCornerShape(6.dp)
|
||||||
Column(modifier = Modifier.size(56.dp).clip(shape).border(1.dp, GlassBorder, shape)) {
|
Column(modifier = Modifier.size(56.dp).clip(shape).border(1.dp, PanelBorder, shape)) {
|
||||||
repeat(2) { row ->
|
repeat(2) { row ->
|
||||||
Row(modifier = Modifier.weight(1f)) {
|
Row(modifier = Modifier.weight(1f)) {
|
||||||
repeat(2) { col ->
|
repeat(2) { col ->
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import androidx.compose.runtime.remember
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.drawWithCache
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
@@ -175,7 +176,8 @@ fun ConnectionScreen(
|
|||||||
Text(stringResource(R.string.nearby_create), color = ink, style = MaterialTheme.typography.titleMedium, maxLines = 1)
|
Text(stringResource(R.string.nearby_create), color = ink, style = MaterialTheme.typography.titleMedium, maxLines = 1)
|
||||||
}
|
}
|
||||||
GlassOutlinedButton(onClick = { pickTime = true }) {
|
GlassOutlinedButton(onClick = { pickTime = true }) {
|
||||||
Text(timeControl.shortLabel() + " ▾", color = ink, maxLines = 1)
|
Text(timeControl.shortLabel(), color = ink, maxLines = 1)
|
||||||
|
AppIcon(R.drawable.ic_expand, size = 20.dp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -294,18 +296,26 @@ private fun SearchPulse() {
|
|||||||
)
|
)
|
||||||
Column(modifier = Modifier.fillMaxWidth().padding(top = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
Column(modifier = Modifier.fillMaxWidth().padding(top = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
Box(modifier = Modifier.size(120.dp), contentAlignment = Alignment.Center) {
|
Box(modifier = Modifier.size(120.dp), contentAlignment = Alignment.Center) {
|
||||||
androidx.compose.foundation.Canvas(modifier = Modifier.size(120.dp)) {
|
Spacer(
|
||||||
for (k in 0 until 3) {
|
modifier = Modifier.size(120.dp).drawWithCache {
|
||||||
val p = (phase + k / 3f) % 1f
|
val ring = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.dp.toPx())
|
||||||
drawCircle(
|
// The phase is read while drawing: the pulse redraws without recomposing.
|
||||||
color = ChessGreen.copy(alpha = (1f - p) * 0.45f),
|
onDrawBehind {
|
||||||
radius = size.minDimension / 2f * (0.3f + 0.7f * p),
|
for (k in 0 until 3) {
|
||||||
style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2.dp.toPx())
|
val p = (phase + k / 3f) % 1f
|
||||||
)
|
drawCircle(
|
||||||
|
color = ChessGreen.copy(alpha = (1f - p) * 0.45f),
|
||||||
|
radius = size.minDimension / 2f * (0.3f + 0.7f * p),
|
||||||
|
style = ring
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
)
|
||||||
androidx.compose.foundation.Image(
|
androidx.compose.foundation.Image(
|
||||||
painter = androidx.compose.ui.res.painterResource(R.drawable.piece_white_knight),
|
bitmap = cc.skysparkle.matewave.ui.components.PieceImages.of(
|
||||||
|
LocalContext.current, cc.skysparkle.matewave.engine.PieceType.KNIGHT, cc.skysparkle.matewave.engine.PieceColor.WHITE
|
||||||
|
),
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(40.dp)
|
modifier = Modifier.size(40.dp)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ import cc.skysparkle.matewave.data.FriendsStore
|
|||||||
import cc.skysparkle.matewave.presence.LocalPresence
|
import cc.skysparkle.matewave.presence.LocalPresence
|
||||||
import cc.skysparkle.matewave.ui.components.AppBottomBar
|
import cc.skysparkle.matewave.ui.components.AppBottomBar
|
||||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||||
|
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
@@ -128,6 +129,7 @@ fun FriendsScreen(
|
|||||||
Text(stringResource(R.string.friends_nobody_title), color = ink, style = MaterialTheme.typography.titleMedium)
|
Text(stringResource(R.string.friends_nobody_title), color = ink, style = MaterialTheme.typography.titleMedium)
|
||||||
Text(stringResource(R.string.friends_nobody_hint), color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodyMedium)
|
Text(stringResource(R.string.friends_nobody_hint), color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodyMedium)
|
||||||
GlassButton(onClick = onPlay, modifier = Modifier.fillMaxWidth()) {
|
GlassButton(onClick = onPlay, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
ButtonIcon(R.drawable.ic_play)
|
||||||
Text(stringResource(R.string.friends_play_nearby), color = ink)
|
Text(stringResource(R.string.friends_play_nearby), color = ink)
|
||||||
}
|
}
|
||||||
return@GlassScaffold
|
return@GlassScaffold
|
||||||
@@ -250,7 +252,6 @@ private fun FriendCard(friend: FriendEntry, status: PresenceStatus, onDismiss: (
|
|||||||
.clip(cc.skysparkle.matewave.ui.components.DialogShape)
|
.clip(cc.skysparkle.matewave.ui.components.DialogShape)
|
||||||
.background(cc.skysparkle.matewave.ui.components.DialogSurface)
|
.background(cc.skysparkle.matewave.ui.components.DialogSurface)
|
||||||
) {
|
) {
|
||||||
androidx.compose.runtime.CompositionLocalProvider(cc.skysparkle.matewave.ui.theme.LocalInk provides Color.White) {
|
|
||||||
Box(modifier = Modifier.fillMaxWidth().height(150.dp)) {
|
Box(modifier = Modifier.fillMaxWidth().height(150.dp)) {
|
||||||
val bg = cc.skysparkle.matewave.ui.components.rememberChatImage(friend.backgroundBase64)
|
val bg = cc.skysparkle.matewave.ui.components.rememberChatImage(friend.backgroundBase64)
|
||||||
if (bg != null) {
|
if (bg != null) {
|
||||||
@@ -292,7 +293,6 @@ private fun FriendCard(friend: FriendEntry, status: PresenceStatus, onDismiss: (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
Text(
|
Text(
|
||||||
statusText(status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
statusText(status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ import androidx.compose.ui.res.stringResource
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import cc.skysparkle.matewave.R
|
import cc.skysparkle.matewave.R
|
||||||
|
import cc.skysparkle.matewave.clock.ClockState
|
||||||
import cc.skysparkle.matewave.ui.components.DialogText
|
import cc.skysparkle.matewave.ui.components.DialogText
|
||||||
import cc.skysparkle.matewave.ui.components.DialogAction
|
import cc.skysparkle.matewave.ui.components.DialogAction
|
||||||
import cc.skysparkle.matewave.ui.components.AppDialog
|
import cc.skysparkle.matewave.ui.components.AppDialog
|
||||||
@@ -51,6 +52,7 @@ import cc.skysparkle.matewave.ui.theme.ChessGreen
|
|||||||
import cc.skysparkle.matewave.viewmodel.GameMode
|
import cc.skysparkle.matewave.viewmodel.GameMode
|
||||||
import cc.skysparkle.matewave.viewmodel.GameUiState
|
import cc.skysparkle.matewave.viewmodel.GameUiState
|
||||||
import cc.skysparkle.matewave.viewmodel.GameViewModel
|
import cc.skysparkle.matewave.viewmodel.GameViewModel
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
||||||
@@ -116,11 +118,9 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
val material = remember(state.board) { cc.skysparkle.matewave.engine.Material.balance(state.board) }
|
val material = remember(state.board) { cc.skysparkle.matewave.engine.Material.balance(state.board) }
|
||||||
val bottomColor = state.myColor
|
val bottomColor = state.myColor
|
||||||
val topColor = if (bottomColor == PieceColor.WHITE) PieceColor.BLACK else PieceColor.WHITE
|
val topColor = if (bottomColor == PieceColor.WHITE) PieceColor.BLACK else PieceColor.WHITE
|
||||||
val kingInCheckSquare = if (ChessEngine.isInCheck(state.board, state.board.sideToMove)) {
|
val kingInCheckSquare = remember(state.board) { ChessEngine.checkedKingSquare(state.board) }
|
||||||
state.board.kingSquare(state.board.sideToMove)
|
|
||||||
} else null
|
|
||||||
|
|
||||||
PlayerRow(state, topColor, isMe = false, material = material)
|
PlayerRow(state, topColor, isMe = false, material = material, clock = viewModel.clockState)
|
||||||
|
|
||||||
ChessBoardView(
|
ChessBoardView(
|
||||||
board = state.board,
|
board = state.board,
|
||||||
@@ -136,14 +136,13 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
state.handshake == cc.skysparkle.matewave.viewmodel.HandshakeState.PLAYING))
|
state.handshake == cc.skysparkle.matewave.viewmodel.HandshakeState.PLAYING))
|
||||||
)
|
)
|
||||||
|
|
||||||
PlayerRow(state, bottomColor, isMe = true, material = material)
|
PlayerRow(state, bottomColor, isMe = true, material = material, clock = viewModel.clockState)
|
||||||
|
|
||||||
// The move ribbon: only moves here, the opening name lives in the top bar.
|
// The move ribbon: only moves here, the opening name lives in the top bar.
|
||||||
if (showOpening) {
|
if (showOpening) {
|
||||||
cc.skysparkle.matewave.ui.components.MovesBar(
|
cc.skysparkle.matewave.ui.components.MovesBar(
|
||||||
sans = sans,
|
sans = sans,
|
||||||
startBoard = start,
|
startBoard = start,
|
||||||
currentIndex = sans.size,
|
|
||||||
opening = null,
|
opening = null,
|
||||||
bookPlies = bookPlies
|
bookPlies = bookPlies
|
||||||
)
|
)
|
||||||
@@ -174,6 +173,7 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
enabled = !state.drawOfferSentByMe
|
enabled = !state.drawOfferSentByMe
|
||||||
) {
|
) {
|
||||||
|
ButtonIcon(R.drawable.ic_draw)
|
||||||
Text(
|
Text(
|
||||||
if (state.drawOfferSentByMe) stringResource(R.string.draw_offer_waiting) else stringResource(R.string.offer_draw),
|
if (state.drawOfferSentByMe) stringResource(R.string.draw_offer_waiting) else stringResource(R.string.offer_draw),
|
||||||
color = ink,
|
color = ink,
|
||||||
@@ -181,6 +181,7 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
GlassOutlinedButton(onClick = { confirmResign = true }, modifier = Modifier.weight(1f)) {
|
GlassOutlinedButton(onClick = { confirmResign = true }, modifier = Modifier.weight(1f)) {
|
||||||
|
ButtonIcon(R.drawable.ic_flag)
|
||||||
Text(stringResource(R.string.resign), color = ink, maxLines = 1)
|
Text(stringResource(R.string.resign), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,6 +194,7 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
// The result dialog was closed to look at the board: one tap brings it back.
|
// The result dialog was closed to look at the board: one tap brings it back.
|
||||||
if (state.status != GameStatus.ONGOING && gameOverHidden) {
|
if (state.status != GameStatus.ONGOING && gameOverHidden) {
|
||||||
GlassOutlinedButton(onClick = { gameOverHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
GlassOutlinedButton(onClick = { gameOverHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
ButtonIcon(R.drawable.ic_trophy)
|
||||||
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -439,7 +441,8 @@ private fun PlayerRow(
|
|||||||
state: GameUiState,
|
state: GameUiState,
|
||||||
side: PieceColor,
|
side: PieceColor,
|
||||||
isMe: Boolean,
|
isMe: Boolean,
|
||||||
material: cc.skysparkle.matewave.engine.MaterialBalance
|
material: cc.skysparkle.matewave.engine.MaterialBalance,
|
||||||
|
clock: StateFlow<ClockState?>
|
||||||
) {
|
) {
|
||||||
val active = state.status == GameStatus.ONGOING && state.board.sideToMove == side
|
val active = state.status == GameStatus.ONGOING && state.board.sideToMove == side
|
||||||
// Re-read after the game: the rating changes when it ends.
|
// Re-read after the game: the rating changes when it ends.
|
||||||
@@ -488,9 +491,16 @@ private fun PlayerRow(
|
|||||||
}
|
}
|
||||||
SideCaptured(material, side)
|
SideCaptured(material, side)
|
||||||
}
|
}
|
||||||
state.clockState?.let { cs ->
|
PlayerClock(clock, side, active)
|
||||||
BigClock(if (side == PieceColor.WHITE) cs.whiteMillis else cs.blackMillis, active)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Collects the clock here, so its ticks recompose only the clock. */
|
||||||
|
@Composable
|
||||||
|
private fun PlayerClock(clock: StateFlow<ClockState?>, side: PieceColor, active: Boolean) {
|
||||||
|
val clockState by clock.collectAsState()
|
||||||
|
clockState?.let { cs ->
|
||||||
|
BigClock(if (side == PieceColor.WHITE) cs.whiteMillis else cs.blackMillis, active)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ private fun LicenseCard(entry: LicenseEntry, onClick: () -> Unit) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AppIcon(R.drawable.ic_arrow_forward, size = 16.dp, tint = ink.copy(alpha = 0.6f))
|
AppIcon(R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.7f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import cc.skysparkle.matewave.ui.components.SectionCaption
|
|||||||
|
|
||||||
import cc.skysparkle.matewave.ui.theme.ink
|
import cc.skysparkle.matewave.ui.theme.ink
|
||||||
|
|
||||||
import androidx.compose.foundation.Canvas
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
@@ -42,6 +41,7 @@ import androidx.compose.runtime.remember
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.drawWithCache
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.graphics.Brush
|
import androidx.compose.ui.graphics.Brush
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
@@ -63,7 +63,7 @@ import cc.skysparkle.matewave.ui.components.AppBottomBar
|
|||||||
import cc.skysparkle.matewave.ui.components.BottomTab
|
import cc.skysparkle.matewave.ui.components.BottomTab
|
||||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
import cc.skysparkle.matewave.ui.theme.TabletMaxContentWidth
|
||||||
import cc.skysparkle.matewave.ui.theme.UiCornerRadius
|
import cc.skysparkle.matewave.ui.theme.GlassShape
|
||||||
import cc.skysparkle.matewave.ui.theme.glass
|
import cc.skysparkle.matewave.ui.theme.glass
|
||||||
import cc.skysparkle.matewave.viewmodel.GameViewModel
|
import cc.skysparkle.matewave.viewmodel.GameViewModel
|
||||||
import cc.skysparkle.matewave.viewmodel.ResumeInfo
|
import cc.skysparkle.matewave.viewmodel.ResumeInfo
|
||||||
@@ -142,7 +142,7 @@ fun MainMenuScreen(
|
|||||||
onClick = { if (profile.levelChosen) onVsAiClick() else showRatingGate = true }
|
onClick = { if (profile.levelChosen) onVsAiClick() else showRatingGate = true }
|
||||||
)
|
)
|
||||||
ModeTile(
|
ModeTile(
|
||||||
iconRes = R.drawable.ic_profile_photo,
|
iconRes = R.drawable.ic_versus,
|
||||||
title = stringResource(R.string.mode_online_title),
|
title = stringResource(R.string.mode_online_title),
|
||||||
subtitle = stringResource(R.string.mode_online_subtitle),
|
subtitle = stringResource(R.string.mode_online_subtitle),
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
@@ -180,7 +180,7 @@ fun MainMenuScreen(
|
|||||||
ListRow(
|
ListRow(
|
||||||
title = stringResource(R.string.study_title),
|
title = stringResource(R.string.study_title),
|
||||||
subtitle = stringResource(R.string.study_menu_subtitle),
|
subtitle = stringResource(R.string.study_menu_subtitle),
|
||||||
icon = R.drawable.ic_crown,
|
icon = R.drawable.ic_study,
|
||||||
chevron = true,
|
chevron = true,
|
||||||
onClick = onStudyClick
|
onClick = onStudyClick
|
||||||
)
|
)
|
||||||
@@ -248,8 +248,8 @@ private fun ContinueCard(info: ResumeInfo, onClick: () -> Unit) {
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.glass(RoundedCornerShape(UiCornerRadius))
|
.glass()
|
||||||
.border(1.dp, ChessGreen.copy(alpha = 0.6f), RoundedCornerShape(UiCornerRadius))
|
.border(1.dp, ChessGreen.copy(alpha = 0.6f), GlassShape)
|
||||||
.clickable(onClick = onClick)
|
.clickable(onClick = onClick)
|
||||||
.padding(16.dp),
|
.padding(16.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
@@ -272,7 +272,7 @@ private fun ContinueCard(info: ResumeInfo, onClick: () -> Unit) {
|
|||||||
private fun ModeTile(iconRes: Int, title: String, subtitle: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
private fun ModeTile(iconRes: Int, title: String, subtitle: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||||
Column(
|
Column(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.glass(RoundedCornerShape(UiCornerRadius))
|
.glass()
|
||||||
.clickable(onClick = onClick)
|
.clickable(onClick = onClick)
|
||||||
.padding(14.dp),
|
.padding(14.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||||
@@ -328,44 +328,49 @@ internal fun StatsDialog(onDismiss: () -> Unit) {
|
|||||||
@Composable
|
@Composable
|
||||||
internal fun MiniRatingGraph(points: List<Int>, modifier: Modifier = Modifier) {
|
internal fun MiniRatingGraph(points: List<Int>, modifier: Modifier = Modifier) {
|
||||||
val lineInk = ink
|
val lineInk = ink
|
||||||
Canvas(modifier = modifier) {
|
// Paths, gradient and stroke are built once per size and reused by every redraw.
|
||||||
if (points.size < 2) return@Canvas
|
Spacer(
|
||||||
val minV = points.min().toFloat()
|
modifier = modifier.drawWithCache {
|
||||||
val maxV = points.max().toFloat()
|
if (points.size < 2) return@drawWithCache onDrawBehind {}
|
||||||
val range = (maxV - minV).coerceAtLeast(1f)
|
val minV = points.min().toFloat()
|
||||||
val stepX = size.width / (points.size - 1)
|
val maxV = points.max().toFloat()
|
||||||
|
val range = (maxV - minV).coerceAtLeast(1f)
|
||||||
|
val stepX = size.width / (points.size - 1)
|
||||||
|
|
||||||
fun yOf(v: Int) = size.height - ((v - minV) / range) * size.height
|
fun yOf(v: Int) = size.height - ((v - minV) / range) * size.height
|
||||||
|
|
||||||
val gridLines = 4
|
// Reference line: the rating at the start of the shown history.
|
||||||
for (i in 0..gridLines) {
|
val zeroY = yOf(points.first())
|
||||||
val y = size.height / gridLines * i
|
val line = Path().apply {
|
||||||
drawLine(lineInk.copy(alpha = 0.08f), Offset(0f, y), Offset(size.width, y), strokeWidth = 1f)
|
moveTo(0f, yOf(points[0]))
|
||||||
}
|
points.forEachIndexed { i, v -> if (i > 0) lineTo(i * stepX, yOf(v)) }
|
||||||
// Reference line: the rating at the start of the shown history.
|
}
|
||||||
val zeroY = yOf(points.first())
|
val fill = Path().apply {
|
||||||
drawLine(lineInk.copy(alpha = 0.3f), Offset(0f, zeroY), Offset(size.width, zeroY), strokeWidth = 1.5f)
|
addPath(line)
|
||||||
|
lineTo(size.width, size.height)
|
||||||
|
lineTo(0f, size.height)
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
val fillBrush = Brush.verticalGradient(listOf(ChessGreen.copy(alpha = 0.35f), ChessGreen.copy(alpha = 0f)))
|
||||||
|
val lineStroke = Stroke(width = 4f, cap = StrokeCap.Round)
|
||||||
|
|
||||||
val line = Path().apply {
|
onDrawBehind {
|
||||||
moveTo(0f, yOf(points[0]))
|
val gridLines = 4
|
||||||
points.forEachIndexed { i, v -> if (i > 0) lineTo(i * stepX, yOf(v)) }
|
for (i in 0..gridLines) {
|
||||||
}
|
val y = size.height / gridLines * i
|
||||||
val fill = Path().apply {
|
drawLine(lineInk.copy(alpha = 0.08f), Offset(0f, y), Offset(size.width, y), strokeWidth = 1f)
|
||||||
addPath(line)
|
}
|
||||||
lineTo(size.width, size.height)
|
drawLine(lineInk.copy(alpha = 0.3f), Offset(0f, zeroY), Offset(size.width, zeroY), strokeWidth = 1.5f)
|
||||||
lineTo(0f, size.height)
|
|
||||||
close()
|
|
||||||
}
|
|
||||||
drawPath(
|
|
||||||
fill,
|
|
||||||
brush = Brush.verticalGradient(listOf(ChessGreen.copy(alpha = 0.35f), ChessGreen.copy(alpha = 0f)))
|
|
||||||
)
|
|
||||||
drawPath(line, color = ChessGreen, style = Stroke(width = 4f, cap = StrokeCap.Round))
|
|
||||||
|
|
||||||
points.forEachIndexed { i, v ->
|
drawPath(fill, brush = fillBrush)
|
||||||
val center = Offset(i * stepX, yOf(v))
|
drawPath(line, color = ChessGreen, style = lineStroke)
|
||||||
drawCircle(color = lineInk, radius = 5f, center = center)
|
|
||||||
drawCircle(color = ChessGreen, radius = 3f, center = center)
|
points.forEachIndexed { i, v ->
|
||||||
|
val center = Offset(i * stepX, yOf(v))
|
||||||
|
drawCircle(color = lineInk, radius = 5f, center = center)
|
||||||
|
drawCircle(color = ChessGreen, radius = 3f, center = center)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ import cc.skysparkle.matewave.openings.CourseInfo
|
|||||||
import cc.skysparkle.matewave.openings.CourseStatus
|
import cc.skysparkle.matewave.openings.CourseStatus
|
||||||
import cc.skysparkle.matewave.openings.artRes
|
import cc.skysparkle.matewave.openings.artRes
|
||||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||||
|
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||||
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
import cc.skysparkle.matewave.ui.components.GlassScaffold
|
||||||
import cc.skysparkle.matewave.ui.components.SetupSegmented
|
import cc.skysparkle.matewave.ui.components.SetupSegmented
|
||||||
@@ -148,7 +149,7 @@ private fun NextAction(overview: StudyOverview, viewModel: OpeningStudyViewModel
|
|||||||
button = stringResource(R.string.study_start_button)
|
button = stringResource(R.string.study_start_button)
|
||||||
) { if (viewModel.open(firstNew.course)) onOpenTrainer() }
|
) { if (viewModel.open(firstNew.course)) onOpenTrainer() }
|
||||||
nextDueAt != null -> Row(verticalAlignment = Alignment.CenterVertically) {
|
nextDueAt != null -> Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
AppIcon(R.drawable.ic_review, size = 16.dp, tint = ink.copy(alpha = 0.55f))
|
AppIcon(R.drawable.ic_review, size = 16.dp, tint = ink.copy(alpha = 0.7f))
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text(stringResource(R.string.study_next_review, formatDueIn(nextDueAt)), color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodyMedium)
|
Text(stringResource(R.string.study_next_review, formatDueIn(nextDueAt)), color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodyMedium)
|
||||||
}
|
}
|
||||||
@@ -160,7 +161,7 @@ private fun ActionCard(icon: Int, title: String, subtitle: String?, button: Stri
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.glass(RoundedCornerShape(UiCornerRadius))
|
.glass()
|
||||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
@@ -177,7 +178,10 @@ private fun ActionCard(icon: Int, title: String, subtitle: String?, button: Stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.width(12.dp))
|
Spacer(Modifier.width(12.dp))
|
||||||
GlassButton(onClick = onClick) { Text(button, color = ink, maxLines = 1) }
|
GlassButton(onClick = onClick) {
|
||||||
|
ButtonIcon(R.drawable.ic_play)
|
||||||
|
Text(button, color = ink, maxLines = 1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +234,7 @@ private fun CourseCard(info: CourseInfo, modifier: Modifier, onClick: () -> Unit
|
|||||||
)
|
)
|
||||||
Spacer(Modifier.height(4.dp))
|
Spacer(Modifier.height(4.dp))
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
AppIcon(R.drawable.ic_timer, size = 12.dp, tint = ink.copy(alpha = 0.55f))
|
AppIcon(R.drawable.ic_timer, size = 14.dp, tint = ink.copy(alpha = 0.7f))
|
||||||
Spacer(Modifier.width(4.dp))
|
Spacer(Modifier.width(4.dp))
|
||||||
Text(
|
Text(
|
||||||
LocalContext.current.resources.getQuantityString(R.plurals.study_moves_count, info.total, info.total),
|
LocalContext.current.resources.getQuantityString(R.plurals.study_moves_count, info.total, info.total),
|
||||||
@@ -266,7 +270,7 @@ private fun CourseCard(info: CourseInfo, modifier: Modifier, onClick: () -> Unit
|
|||||||
fun Stars(count: Int, size: androidx.compose.ui.unit.Dp = 16.dp) {
|
fun Stars(count: Int, size: androidx.compose.ui.unit.Dp = 16.dp) {
|
||||||
Row {
|
Row {
|
||||||
repeat(3) { i ->
|
repeat(3) { i ->
|
||||||
AppIcon(R.drawable.ic_star, size = size, tint = if (i < count) StarGold else ink.copy(alpha = 0.2f))
|
AppIcon(R.drawable.ic_star, size = size, tint = if (i < count) StarGold else ink.copy(alpha = 0.3f))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
|||||||
}
|
}
|
||||||
ProgressBar(state.answered.toFloat() / state.asked.size.coerceAtLeast(1))
|
ProgressBar(state.answered.toFloat() / state.asked.size.coerceAtLeast(1))
|
||||||
|
|
||||||
MovesBar(sans = sans, startBoard = startBoard, currentIndex = sans.size, opening = opening)
|
MovesBar(sans = sans, startBoard = startBoard, opening = opening)
|
||||||
|
|
||||||
ChessBoardView(
|
ChessBoardView(
|
||||||
board = state.board,
|
board = state.board,
|
||||||
@@ -142,9 +142,11 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
|||||||
}
|
}
|
||||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
GlassOutlinedButton(onClick = { viewModel.practiceAgain() }, modifier = Modifier.weight(1f)) {
|
GlassOutlinedButton(onClick = { viewModel.practiceAgain() }, modifier = Modifier.weight(1f)) {
|
||||||
|
ButtonIcon(R.drawable.ic_replay)
|
||||||
Text(stringResource(R.string.study_again), color = ink, maxLines = 1)
|
Text(stringResource(R.string.study_again), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
GlassButton(onClick = { if (!viewModel.continueStudy()) onBack() }, modifier = Modifier.weight(1f)) {
|
GlassButton(onClick = { if (!viewModel.continueStudy()) onBack() }, modifier = Modifier.weight(1f)) {
|
||||||
|
ButtonIcon(R.drawable.ic_next)
|
||||||
Text(stringResource(R.string.study_next), color = ink, maxLines = 1)
|
Text(stringResource(R.string.study_next), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,6 +168,7 @@ fun OpeningTrainerScreen(viewModel: OpeningStudyViewModel, onBack: () -> Unit) {
|
|||||||
// A review is not restarted: it would only replay the moves still due.
|
// A review is not restarted: it would only replay the moves still due.
|
||||||
if (state.mode != SessionMode.REVIEW) {
|
if (state.mode != SessionMode.REVIEW) {
|
||||||
GlassOutlinedButton(onClick = { viewModel.restart() }, modifier = Modifier.weight(1f)) {
|
GlassOutlinedButton(onClick = { viewModel.restart() }, modifier = Modifier.weight(1f)) {
|
||||||
|
ButtonIcon(R.drawable.ic_restart)
|
||||||
Text(stringResource(R.string.study_restart), color = ink, maxLines = 1)
|
Text(stringResource(R.string.study_restart), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -287,6 +287,7 @@ private fun PermissionItem(
|
|||||||
Text(subtitle, color = ink.copy(alpha = 0.75f), style = MaterialTheme.typography.bodySmall)
|
Text(subtitle, color = ink.copy(alpha = 0.75f), style = MaterialTheme.typography.bodySmall)
|
||||||
if (!granted) {
|
if (!granted) {
|
||||||
GlassOutlinedButton(onClick = onGrant, modifier = Modifier.fillMaxWidth()) {
|
GlassOutlinedButton(onClick = onGrant, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
cc.skysparkle.matewave.ui.components.ButtonIcon(R.drawable.ic_approve)
|
||||||
Text(stringResource(R.string.perm_grant), color = ink)
|
Text(stringResource(R.string.perm_grant), color = ink)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import cc.skysparkle.matewave.puzzles.PuzzleRepository
|
|||||||
import cc.skysparkle.matewave.puzzles.themeTitleRes
|
import cc.skysparkle.matewave.puzzles.themeTitleRes
|
||||||
import cc.skysparkle.matewave.stats.Stats
|
import cc.skysparkle.matewave.stats.Stats
|
||||||
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||||
|
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||||
import cc.skysparkle.matewave.ui.components.ChessBoardView
|
import cc.skysparkle.matewave.ui.components.ChessBoardView
|
||||||
import cc.skysparkle.matewave.ui.components.GlassButton
|
import cc.skysparkle.matewave.ui.components.GlassButton
|
||||||
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
|
||||||
@@ -94,9 +95,7 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
|||||||
board = state.board,
|
board = state.board,
|
||||||
selectedSquare = state.selectedSquare,
|
selectedSquare = state.selectedSquare,
|
||||||
legalTargets = state.legalTargetsFromSelected,
|
legalTargets = state.legalTargetsFromSelected,
|
||||||
kingInCheckSquare = if (ChessEngine.isInCheck(state.board, state.board.sideToMove)) {
|
kingInCheckSquare = remember(state.board) { ChessEngine.checkedKingSquare(state.board) },
|
||||||
state.board.kingSquare(state.board.sideToMove)
|
|
||||||
} else null,
|
|
||||||
flipped = state.myColor == PieceColor.BLACK,
|
flipped = state.myColor == PieceColor.BLACK,
|
||||||
onSquareClick = viewModel::onSquareClicked,
|
onSquareClick = viewModel::onSquareClicked,
|
||||||
modifier = Modifier.align(Alignment.CenterHorizontally).widthIn(max = 560.dp),
|
modifier = Modifier.align(Alignment.CenterHorizontally).widthIn(max = 560.dp),
|
||||||
@@ -109,20 +108,30 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
|||||||
|
|
||||||
// The task, in the same format as the status in a game: a dot in the side's colour.
|
// The task, in the same format as the status in a game: a dot in the side's colour.
|
||||||
val (text, color) = when {
|
val (text, color) = when {
|
||||||
state.puzzleSolved -> "✓ " + stringResource(R.string.puzzle_solved) to ChessGreen
|
state.puzzleSolved -> stringResource(R.string.puzzle_solved) to ChessGreen
|
||||||
state.puzzleFailedAttempt -> "✗ " + stringResource(R.string.puzzle_wrong_move) to WrongRed
|
state.puzzleFailedAttempt -> stringResource(R.string.puzzle_wrong_move) to WrongRed
|
||||||
state.puzzleAutoMoving -> stringResource(R.string.opponent_turn) to ink.copy(alpha = 0.7f)
|
state.puzzleAutoMoving -> stringResource(R.string.opponent_turn) to ink.copy(alpha = 0.7f)
|
||||||
state.myColor == PieceColor.WHITE -> stringResource(R.string.puzzle_find_best_white) to ink
|
state.myColor == PieceColor.WHITE -> stringResource(R.string.puzzle_find_best_white) to ink
|
||||||
else -> stringResource(R.string.puzzle_find_best_black) to ink
|
else -> stringResource(R.string.puzzle_find_best_black) to ink
|
||||||
}
|
}
|
||||||
|
// Solved and wrong show a mark instead of the dot
|
||||||
|
val mark = when {
|
||||||
|
state.puzzleSolved -> R.drawable.ic_approve
|
||||||
|
state.puzzleFailedAttempt -> R.drawable.ic_cancel
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Box(
|
if (mark != null) {
|
||||||
Modifier
|
AppIcon(mark, size = 20.dp, tint = color)
|
||||||
.size(10.dp)
|
} else {
|
||||||
.clip(CircleShape)
|
Box(
|
||||||
.background(if (state.myColor == PieceColor.WHITE) Color(0xFFF0F0F0) else Color(0xFF222222))
|
Modifier
|
||||||
.border(1.dp, ink.copy(alpha = 0.5f), CircleShape)
|
.size(10.dp)
|
||||||
)
|
.clip(CircleShape)
|
||||||
|
.background(if (state.myColor == PieceColor.WHITE) Color(0xFFF0F0F0) else Color(0xFF222222))
|
||||||
|
.border(1.dp, ink.copy(alpha = 0.5f), CircleShape)
|
||||||
|
)
|
||||||
|
}
|
||||||
Spacer(Modifier.width(10.dp))
|
Spacer(Modifier.width(10.dp))
|
||||||
Text(text, color = color, style = MaterialTheme.typography.titleMedium)
|
Text(text, color = color, style = MaterialTheme.typography.titleMedium)
|
||||||
}
|
}
|
||||||
@@ -174,6 +183,7 @@ fun PuzzleSolveScreen(viewModel: GameViewModel, onBack: () -> Unit, onNextPuzzle
|
|||||||
}
|
}
|
||||||
if (next != null) {
|
if (next != null) {
|
||||||
GlassButton(onClick = { onNextPuzzle(next) }, modifier = Modifier.fillMaxWidth()) {
|
GlassButton(onClick = { onNextPuzzle(next) }, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
ButtonIcon(R.drawable.ic_next)
|
||||||
Text(stringResource(R.string.puzzle_next), color = ink, style = MaterialTheme.typography.titleMedium)
|
Text(stringResource(R.string.puzzle_next), color = ink, style = MaterialTheme.typography.titleMedium)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ fun SettingsScreen(
|
|||||||
ListRow(
|
ListRow(
|
||||||
title = stringResource(R.string.appearance_title),
|
title = stringResource(R.string.appearance_title),
|
||||||
subtitle = stringResource(R.string.appearance_subtitle),
|
subtitle = stringResource(R.string.appearance_subtitle),
|
||||||
icon = R.drawable.ic_board_view,
|
icon = R.drawable.ic_palette,
|
||||||
chevron = true,
|
chevron = true,
|
||||||
onClick = onOpenAppearance
|
onClick = onOpenAppearance
|
||||||
)
|
)
|
||||||
@@ -260,7 +260,7 @@ private fun AboutRow(iconRes: Int, title: String, subtitle: String, onClick: ()
|
|||||||
Text(subtitle, color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodySmall)
|
Text(subtitle, color = ink.copy(alpha = 0.65f), style = MaterialTheme.typography.bodySmall)
|
||||||
}
|
}
|
||||||
cc.skysparkle.matewave.ui.components.AppIcon(
|
cc.skysparkle.matewave.ui.components.AppIcon(
|
||||||
R.drawable.ic_arrow_forward, size = 16.dp, tint = ink.copy(alpha = 0.6f)
|
R.drawable.ic_arrow_forward, size = 20.dp, tint = ink.copy(alpha = 0.7f)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,9 +101,7 @@ fun SpectatorScreen(target: SpectateTarget, onBackToFriends: () -> Unit) {
|
|||||||
|
|
||||||
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
|
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
|
||||||
val material = remember(view.board) { Material.balance(view.board) }
|
val material = remember(view.board) { Material.balance(view.board) }
|
||||||
val checkSquare = if (ChessEngine.isInCheck(view.board, view.board.sideToMove)) {
|
val checkSquare = remember(view.board) { ChessEngine.checkedKingSquare(view.board) }
|
||||||
view.board.kingSquare(view.board.sideToMove)
|
|
||||||
} else null
|
|
||||||
|
|
||||||
SpectatorPlayerRow(view, bottom.opposite(), state, material)
|
SpectatorPlayerRow(view, bottom.opposite(), state, material)
|
||||||
ChessBoardView(
|
ChessBoardView(
|
||||||
@@ -123,18 +121,18 @@ fun SpectatorScreen(target: SpectateTarget, onBackToFriends: () -> Unit) {
|
|||||||
MovesBar(
|
MovesBar(
|
||||||
sans = view.moveSans,
|
sans = view.moveSans,
|
||||||
startBoard = view.startBoard,
|
startBoard = view.startBoard,
|
||||||
currentIndex = view.moveSans.size,
|
|
||||||
opening = null,
|
opening = null,
|
||||||
bookPlies = bookPlies
|
bookPlies = bookPlies
|
||||||
)
|
)
|
||||||
|
|
||||||
GlassOutlinedButton(onClick = viewModel::flip, modifier = Modifier.fillMaxWidth()) {
|
GlassOutlinedButton(onClick = viewModel::flip, modifier = Modifier.fillMaxWidth()) {
|
||||||
ButtonIcon(R.drawable.ic_board_view)
|
ButtonIcon(R.drawable.ic_flip)
|
||||||
Text(stringResource(R.string.spectate_flip), color = ink, maxLines = 1)
|
Text(stringResource(R.string.spectate_flip), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state.phase == SpectatePhase.ENDED && resultHidden) {
|
if (state.phase == SpectatePhase.ENDED && resultHidden) {
|
||||||
GlassOutlinedButton(onClick = { resultHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
GlassOutlinedButton(onClick = { resultHidden = false }, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
ButtonIcon(R.drawable.ic_trophy)
|
||||||
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Spacer
|
|||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import cc.skysparkle.matewave.ui.components.AppIcon
|
import cc.skysparkle.matewave.ui.components.AppIcon
|
||||||
|
import cc.skysparkle.matewave.ui.components.ButtonIcon
|
||||||
import cc.skysparkle.matewave.ui.components.SectionCaption
|
import cc.skysparkle.matewave.ui.components.SectionCaption
|
||||||
import cc.skysparkle.matewave.ui.components.TimeControlGrid
|
import cc.skysparkle.matewave.ui.components.TimeControlGrid
|
||||||
import cc.skysparkle.matewave.ui.components.displayName
|
import cc.skysparkle.matewave.ui.components.displayName
|
||||||
@@ -35,6 +36,7 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
import cc.skysparkle.matewave.ui.components.SetupSegmented
|
import cc.skysparkle.matewave.ui.components.SetupSegmented
|
||||||
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
import cc.skysparkle.matewave.ui.theme.ChessGreen
|
||||||
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
import cc.skysparkle.matewave.ui.theme.PanelBorder
|
||||||
@@ -75,6 +77,7 @@ fun VsAiSetupScreen(
|
|||||||
},
|
},
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier.fillMaxWidth()
|
||||||
) {
|
) {
|
||||||
|
ButtonIcon(R.drawable.ic_play)
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.vsai_play_summary, difficultyLabel(difficulty), timeControl.displayName()),
|
stringResource(R.string.vsai_play_summary, difficultyLabel(difficulty), timeControl.displayName()),
|
||||||
color = ink,
|
color = ink,
|
||||||
@@ -124,8 +127,8 @@ fun VsAiSetupScreen(
|
|||||||
|
|
||||||
SectionCaption(stringResource(R.string.your_color))
|
SectionCaption(stringResource(R.string.your_color))
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
ColorChip(R.drawable.ic_white_colour, stringResource(R.string.color_white), color == PieceColor.WHITE) { color = PieceColor.WHITE }
|
ColorChip(R.drawable.piece_white_king, stringResource(R.string.color_white), color == PieceColor.WHITE) { color = PieceColor.WHITE }
|
||||||
ColorChip(R.drawable.ic_black_colour, stringResource(R.string.color_black), color == PieceColor.BLACK) { color = PieceColor.BLACK }
|
ColorChip(R.drawable.piece_black_king, stringResource(R.string.color_black), color == PieceColor.BLACK) { color = PieceColor.BLACK }
|
||||||
ColorChip(R.drawable.ic_random_colour, stringResource(R.string.color_random), color == null) { color = null }
|
ColorChip(R.drawable.ic_random_colour, stringResource(R.string.color_random), color == null) { color = null }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,11 +157,20 @@ private fun ColorChip(iconRes: Int, text: String, selected: Boolean, onClick: ()
|
|||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
) {
|
) {
|
||||||
Image(
|
// The king from the board's own piece set; random is half white, half black
|
||||||
painter = painterResource(iconRes),
|
Box(
|
||||||
contentDescription = null,
|
modifier = Modifier
|
||||||
modifier = Modifier.size(16.dp)
|
.size(26.dp)
|
||||||
)
|
.clip(CircleShape)
|
||||||
|
.background(Color(0xFF9AA0A8)),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(iconRes),
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(20.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
Text(text, color = ink, style = MaterialTheme.typography.bodySmall)
|
Text(text, color = ink, style = MaterialTheme.typography.bodySmall)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,12 +17,10 @@ val GlassShape: Shape = RoundedCornerShape(UiCornerRadius)
|
|||||||
|
|
||||||
val TabletMaxContentWidth = 600.dp
|
val TabletMaxContentWidth = 600.dp
|
||||||
|
|
||||||
fun Modifier.glass(shape: Shape = GlassShape): Modifier = this
|
fun Modifier.glass(): Modifier = this
|
||||||
.clip(shape)
|
.clip(GlassShape)
|
||||||
.background(PanelFill)
|
.background(PanelFill)
|
||||||
|
|
||||||
val GlassBorder = PanelBorder
|
|
||||||
|
|
||||||
val PhotoScrim = Brush.verticalGradient(
|
val PhotoScrim = Brush.verticalGradient(
|
||||||
0.00f to Color.Black.copy(alpha = 0.84f),
|
0.00f to Color.Black.copy(alpha = 0.84f),
|
||||||
0.10f to Color.Black.copy(alpha = 0.72f),
|
0.10f to Color.Black.copy(alpha = 0.72f),
|
||||||
|
|||||||
@@ -1,13 +1,6 @@
|
|||||||
package cc.skysparkle.matewave.ui.theme
|
package cc.skysparkle.matewave.ui.theme
|
||||||
|
|
||||||
import androidx.compose.runtime.Composable
|
|
||||||
import androidx.compose.runtime.ReadOnlyComposable
|
|
||||||
import androidx.compose.runtime.compositionLocalOf
|
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
val LocalInk = compositionLocalOf { Color.White }
|
/** Colour of text and icons on the app's dark background. */
|
||||||
|
val ink = Color.White
|
||||||
val ink: Color
|
|
||||||
@Composable
|
|
||||||
@ReadOnlyComposable
|
|
||||||
get() = LocalInk.current
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package cc.skysparkle.matewave.ui.theme
|
package cc.skysparkle.matewave.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.material3.LocalContentColor
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
@@ -25,7 +26,8 @@ private val DarkScheme = darkColorScheme(
|
|||||||
@Composable
|
@Composable
|
||||||
fun MatewaveTheme(content: @Composable () -> Unit) {
|
fun MatewaveTheme(content: @Composable () -> Unit) {
|
||||||
MaterialTheme(colorScheme = DarkScheme) {
|
MaterialTheme(colorScheme = DarkScheme) {
|
||||||
CompositionLocalProvider(LocalInk provides Color.White, content = content)
|
// Text and icons without their own colour are light, so nothing turns black on the dark background
|
||||||
|
CompositionLocalProvider(LocalContentColor provides Color.White, content = content)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ import kotlinx.coroutines.Job
|
|||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
@@ -69,7 +70,6 @@ data class GameUiState(
|
|||||||
|
|
||||||
val gameStarted: Boolean = false,
|
val gameStarted: Boolean = false,
|
||||||
val aiDifficulty: AiDifficulty = AiDifficulty.MEDIUM,
|
val aiDifficulty: AiDifficulty = AiDifficulty.MEDIUM,
|
||||||
val aiThinking: Boolean = false,
|
|
||||||
val puzzle: Puzzle? = null,
|
val puzzle: Puzzle? = null,
|
||||||
val puzzleMoveIndex: Int = 0,
|
val puzzleMoveIndex: Int = 0,
|
||||||
val puzzleSolved: Boolean = false,
|
val puzzleSolved: Boolean = false,
|
||||||
@@ -78,7 +78,6 @@ data class GameUiState(
|
|||||||
val puzzleAutoMoving: Boolean = false,
|
val puzzleAutoMoving: Boolean = false,
|
||||||
val puzzleHintFrom: Int? = null,
|
val puzzleHintFrom: Int? = null,
|
||||||
val puzzleSolutionRevealed: Boolean = false,
|
val puzzleSolutionRevealed: Boolean = false,
|
||||||
val clockState: ClockState? = null,
|
|
||||||
val timedOutSide: PieceColor? = null,
|
val timedOutSide: PieceColor? = null,
|
||||||
val resignedSide: PieceColor? = null,
|
val resignedSide: PieceColor? = null,
|
||||||
val connectionState: ConnectionState = ConnectionState.DISCONNECTED,
|
val connectionState: ConnectionState = ConnectionState.DISCONNECTED,
|
||||||
@@ -115,8 +114,7 @@ data class PendingPromotion(val from: Int, val to: Int)
|
|||||||
data class ChatEntry(
|
data class ChatEntry(
|
||||||
val text: String?,
|
val text: String?,
|
||||||
val imageBase64: String?,
|
val imageBase64: String?,
|
||||||
val fromMe: Boolean,
|
val fromMe: Boolean
|
||||||
val timestampMs: Long
|
|
||||||
)
|
)
|
||||||
|
|
||||||
enum class OpponentNotice { DRAW_DECLINED, REMATCH_DECLINED }
|
enum class OpponentNotice { DRAW_DECLINED, REMATCH_DECLINED }
|
||||||
@@ -148,6 +146,13 @@ class GameViewModel : ViewModel() {
|
|||||||
private val _uiState = MutableStateFlow(GameUiState())
|
private val _uiState = MutableStateFlow(GameUiState())
|
||||||
val uiState: StateFlow<GameUiState> = _uiState
|
val uiState: StateFlow<GameUiState> = _uiState
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The game's clock, kept out of [uiState] so its ticks redraw only the clocks. Cleared with
|
||||||
|
* every new game state; a new clock shows itself once set up.
|
||||||
|
*/
|
||||||
|
private val _clockState = MutableStateFlow<ClockState?>(null)
|
||||||
|
val clockState: StateFlow<ClockState?> = _clockState
|
||||||
|
|
||||||
private val _resumable = MutableStateFlow<ResumeInfo?>(null)
|
private val _resumable = MutableStateFlow<ResumeInfo?>(null)
|
||||||
|
|
||||||
/** The game against the AI that is saved and can be continued, or null. */
|
/** The game against the AI that is saved and can be continued, or null. */
|
||||||
@@ -195,7 +200,16 @@ class GameViewModel : ViewModel() {
|
|||||||
private var lastSentSpectatorCount = 0
|
private var lastSentSpectatorCount = 0
|
||||||
|
|
||||||
init {
|
init {
|
||||||
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
if (GameSaveStore.isLoaded()) {
|
||||||
|
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
||||||
|
} else {
|
||||||
|
// Not read yet: read it in the background instead of making the first screen wait.
|
||||||
|
val untouched = _uiState.value
|
||||||
|
viewModelScope.launch {
|
||||||
|
val saved = withContext(Dispatchers.IO) { GameSaveStore.load() } ?: return@launch
|
||||||
|
if (_uiState.value === untouched) restoreSaved(saved)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// region History
|
// region History
|
||||||
@@ -225,7 +239,7 @@ class GameViewModel : ViewModel() {
|
|||||||
var replayed = saved.movesUci.isNotBlank()
|
var replayed = saved.movesUci.isNotBlank()
|
||||||
if (replayed) {
|
if (replayed) {
|
||||||
for (uci in saved.movesUci.trim().split(' ')) {
|
for (uci in saved.movesUci.trim().split(' ')) {
|
||||||
val move = resolveUciAgainstLegalMoves(board, uci)
|
val move = Notation.fromUci(board, uci)
|
||||||
if (move == null) { replayed = false; break }
|
if (move == null) { replayed = false; break }
|
||||||
sans.add(Notation.toSan(board, move))
|
sans.add(Notation.toSan(board, move))
|
||||||
board = ChessEngine.applyMove(board, move)
|
board = ChessEngine.applyMove(board, move)
|
||||||
@@ -248,6 +262,7 @@ class GameViewModel : ViewModel() {
|
|||||||
fenHistory.clear(); fenHistory.addAll(keys)
|
fenHistory.clear(); fenHistory.addAll(keys)
|
||||||
moveLog.clear(); moveLog.addAll(ucis)
|
moveLog.clear(); moveLog.addAll(ucis)
|
||||||
lastVsAiSettings = Triple(difficulty, myColor, timeControl)
|
lastVsAiSettings = Triple(difficulty, myColor, timeControl)
|
||||||
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_uiState.value = GameUiState(
|
||||||
board = board,
|
board = board,
|
||||||
startBoard = start,
|
startBoard = start,
|
||||||
@@ -264,14 +279,14 @@ class GameViewModel : ViewModel() {
|
|||||||
restoreWhiteMillis = saved.whiteMillis,
|
restoreWhiteMillis = saved.whiteMillis,
|
||||||
restoreBlackMillis = saved.blackMillis
|
restoreBlackMillis = saved.blackMillis
|
||||||
)
|
)
|
||||||
clock?.pause()
|
clock?.stop()
|
||||||
_resumable.value = resumeInfoOf(_uiState.value)
|
_resumable.value = resumeInfoOf(_uiState.value)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resumeInfoOf(state: GameUiState): ResumeInfo {
|
private fun resumeInfoOf(state: GameUiState): ResumeInfo {
|
||||||
val unlimited = lastVsAiSettings?.third?.initialSeconds == Int.MAX_VALUE
|
val unlimited = lastVsAiSettings?.third?.initialSeconds == Int.MAX_VALUE
|
||||||
val millis = if (unlimited) null else (clock?.state?.value ?: state.clockState)?.let {
|
val millis = if (unlimited) null else (clock?.state?.value ?: _clockState.value)?.let {
|
||||||
if (state.myColor == PieceColor.WHITE) it.whiteMillis else it.blackMillis
|
if (state.myColor == PieceColor.WHITE) it.whiteMillis else it.blackMillis
|
||||||
}
|
}
|
||||||
return ResumeInfo(state.board.fullmoveNumber, state.board.sideToMove == state.myColor, millis)
|
return ResumeInfo(state.board.fullmoveNumber, state.board.sideToMove == state.myColor, millis)
|
||||||
@@ -279,7 +294,8 @@ class GameViewModel : ViewModel() {
|
|||||||
|
|
||||||
private fun persistIfResumable() {
|
private fun persistIfResumable() {
|
||||||
val state = _uiState.value
|
val state = _uiState.value
|
||||||
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING) return
|
// The untouched initial state is no game: saving it would offer a game nobody started.
|
||||||
|
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING || !state.gameStarted) return
|
||||||
val clockState = clock?.state?.value
|
val clockState = clock?.state?.value
|
||||||
GameSaveStore.save(
|
GameSaveStore.save(
|
||||||
SavedGame(
|
SavedGame(
|
||||||
@@ -434,12 +450,6 @@ class GameViewModel : ViewModel() {
|
|||||||
ProfileStore.applyEloDelta(ProfileStore.aiNominalElo(difficulty), result)
|
ProfileStore.applyEloDelta(ProfileStore.aiNominalElo(difficulty), result)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resolveUciAgainstLegalMoves(board: Board, uci: String): Move? {
|
|
||||||
val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null
|
|
||||||
val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to }
|
|
||||||
return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull()
|
|
||||||
}
|
|
||||||
|
|
||||||
// endregion
|
// endregion
|
||||||
|
|
||||||
// region Against the AI
|
// region Against the AI
|
||||||
@@ -456,6 +466,7 @@ class GameViewModel : ViewModel() {
|
|||||||
val start = Board.startPosition()
|
val start = Board.startPosition()
|
||||||
resetHistory(start)
|
resetHistory(start)
|
||||||
lastVsAiSettings = Triple(difficulty, myColor, timeControl)
|
lastVsAiSettings = Triple(difficulty, myColor, timeControl)
|
||||||
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_uiState.value = GameUiState(
|
||||||
board = start,
|
board = start,
|
||||||
startBoard = start,
|
startBoard = start,
|
||||||
@@ -493,7 +504,6 @@ class GameViewModel : ViewModel() {
|
|||||||
private fun cancelAi() {
|
private fun cancelAi() {
|
||||||
aiJob?.cancel()
|
aiJob?.cancel()
|
||||||
aiJob = null
|
aiJob = null
|
||||||
if (_uiState.value.aiThinking) _uiState.value = _uiState.value.copy(aiThinking = false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun triggerAiMoveIfNeeded() {
|
private fun triggerAiMoveIfNeeded() {
|
||||||
@@ -501,7 +511,6 @@ class GameViewModel : ViewModel() {
|
|||||||
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING) return
|
if (state.mode != GameMode.VS_AI || state.status != GameStatus.ONGOING) return
|
||||||
if (state.board.sideToMove == state.myColor) return
|
if (state.board.sideToMove == state.myColor) return
|
||||||
if (aiJob?.isActive == true) return
|
if (aiJob?.isActive == true) return
|
||||||
_uiState.value = state.copy(aiThinking = true)
|
|
||||||
val boardAtStart = state.board
|
val boardAtStart = state.board
|
||||||
val history = fenHistory.toSet()
|
val history = fenHistory.toSet()
|
||||||
val aiColor = boardAtStart.sideToMove
|
val aiColor = boardAtStart.sideToMove
|
||||||
@@ -511,14 +520,14 @@ class GameViewModel : ViewModel() {
|
|||||||
val incrementMillis = (lastVsAiSettings?.third?.incrementSeconds ?: 0) * 1000L
|
val incrementMillis = (lastVsAiSettings?.third?.incrementSeconds ?: 0) * 1000L
|
||||||
aiJob = viewModelScope.launch {
|
aiJob = viewModelScope.launch {
|
||||||
val move = withContext(Dispatchers.Default) {
|
val move = withContext(Dispatchers.Default) {
|
||||||
ChessAI.bestMove(boardAtStart, state.aiDifficulty, history, clockMillis, incrementMillis)
|
// Stops thinking as soon as the game is left or the move is no longer wanted.
|
||||||
|
ChessAI.bestMove(
|
||||||
|
boardAtStart, state.aiDifficulty, history, clockMillis, incrementMillis,
|
||||||
|
isCancelled = { !isActive }
|
||||||
|
)
|
||||||
}
|
}
|
||||||
val now = _uiState.value
|
val now = _uiState.value
|
||||||
if (now.board !== boardAtStart || now.mode != GameMode.VS_AI || now.status != GameStatus.ONGOING) {
|
if (now.board !== boardAtStart || now.mode != GameMode.VS_AI || now.status != GameStatus.ONGOING) return@launch
|
||||||
if (now.aiThinking) _uiState.value = now.copy(aiThinking = false)
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
_uiState.value = now.copy(aiThinking = false)
|
|
||||||
if (move != null) makeMove(move)
|
if (move != null) makeMove(move)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -532,6 +541,7 @@ class GameViewModel : ViewModel() {
|
|||||||
disposeClock()
|
disposeClock()
|
||||||
val board = runCatching { Board.fromFen(puzzle.fen) }.getOrNull() ?: return
|
val board = runCatching { Board.fromFen(puzzle.fen) }.getOrNull() ?: return
|
||||||
resetHistory(board)
|
resetHistory(board)
|
||||||
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_uiState.value = GameUiState(
|
||||||
board = board,
|
board = board,
|
||||||
startBoard = board,
|
startBoard = board,
|
||||||
@@ -587,7 +597,7 @@ class GameViewModel : ViewModel() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
val replyMove = resolveUciAgainstLegalMoves(_uiState.value.board, puzzle.solutionUci[nextIndex])
|
val replyMove = Notation.fromUci(_uiState.value.board, puzzle.solutionUci[nextIndex])
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
puzzleMoveIndex = nextIndex + 1,
|
puzzleMoveIndex = nextIndex + 1,
|
||||||
puzzleFailedAttempt = false,
|
puzzleFailedAttempt = false,
|
||||||
@@ -732,6 +742,7 @@ class GameViewModel : ViewModel() {
|
|||||||
currentPly = 0
|
currentPly = 0
|
||||||
lastOpponentRemaining = Long.MAX_VALUE
|
lastOpponentRemaining = Long.MAX_VALUE
|
||||||
|
|
||||||
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_uiState.value = GameUiState(
|
||||||
board = start,
|
board = start,
|
||||||
startBoard = start,
|
startBoard = start,
|
||||||
@@ -893,7 +904,7 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
val state = _uiState.value
|
val state = _uiState.value
|
||||||
_uiState.value = state.copy(
|
_uiState.value = state.copy(
|
||||||
chatMessages = state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false, System.currentTimeMillis()),
|
chatMessages = state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false),
|
||||||
unreadChatCount = state.unreadChatCount + 1
|
unreadChatCount = state.unreadChatCount + 1
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1036,7 +1047,7 @@ class GameViewModel : ViewModel() {
|
|||||||
val opponentColor = state.myColor.opposite()
|
val opponentColor = state.myColor.opposite()
|
||||||
if (state.board.sideToMove != opponentColor) return
|
if (state.board.sideToMove != opponentColor) return
|
||||||
|
|
||||||
val move = resolveUciAgainstLegalMoves(state.board, msg.uci) ?: return
|
val move = Notation.fromUci(state.board, msg.uci) ?: return
|
||||||
currentPly = if (msg.ply > 0) msg.ply else currentPly + 1
|
currentPly = if (msg.ply > 0) msg.ply else currentPly + 1
|
||||||
|
|
||||||
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
||||||
@@ -1164,7 +1175,7 @@ class GameViewModel : ViewModel() {
|
|||||||
|
|
||||||
if (state.mode != GameMode.VS_PLAYER_NETWORK) {
|
if (state.mode != GameMode.VS_PLAYER_NETWORK) {
|
||||||
cancelAi()
|
cancelAi()
|
||||||
clock?.pause()
|
clock?.stop()
|
||||||
persistIfResumable()
|
persistIfResumable()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1241,6 +1252,7 @@ class GameViewModel : ViewModel() {
|
|||||||
val start = Board.startPosition()
|
val start = Board.startPosition()
|
||||||
resetHistory(start)
|
resetHistory(start)
|
||||||
|
|
||||||
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_uiState.value = GameUiState(
|
||||||
board = start,
|
board = start,
|
||||||
startBoard = start,
|
startBoard = start,
|
||||||
@@ -1345,7 +1357,7 @@ class GameViewModel : ViewModel() {
|
|||||||
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
||||||
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
chatMessages = _uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true, System.currentTimeMillis())
|
chatMessages = _uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1358,7 +1370,7 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return
|
if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
chatMessages = _uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true, System.currentTimeMillis())
|
chatMessages = _uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1511,15 +1523,14 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun onClockTick(cs: ClockState) {
|
private fun onClockTick(cs: ClockState) {
|
||||||
|
_clockState.value = cs
|
||||||
val current = _uiState.value
|
val current = _uiState.value
|
||||||
|
// Spectators get the clock as before, when it was part of the game state.
|
||||||
|
if (spectatorWatcher?.isActive == true) onStateForSpectators(current)
|
||||||
val flag = cs.flagged
|
val flag = cs.flagged
|
||||||
if (flag == null || current.status != GameStatus.ONGOING) {
|
if (flag == null || current.status != GameStatus.ONGOING) return
|
||||||
_uiState.value = current.copy(clockState = cs)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
when (current.mode) {
|
when (current.mode) {
|
||||||
GameMode.VS_PLAYER_NETWORK -> {
|
GameMode.VS_PLAYER_NETWORK -> {
|
||||||
_uiState.value = current.copy(clockState = cs)
|
|
||||||
if (flag == current.myColor) {
|
if (flag == current.myColor) {
|
||||||
declareNetworkTimeout(flag, sendClaim = true)
|
declareNetworkTimeout(flag, sendClaim = true)
|
||||||
} else if (opponentFlagJob?.isActive != true) {
|
} else if (opponentFlagJob?.isActive != true) {
|
||||||
@@ -1548,12 +1559,11 @@ class GameViewModel : ViewModel() {
|
|||||||
recordAiResult(current.aiDifficulty, result)
|
recordAiResult(current.aiDifficulty, result)
|
||||||
clearSavedGame()
|
clearSavedGame()
|
||||||
_uiState.value = current.copy(
|
_uiState.value = current.copy(
|
||||||
clockState = cs,
|
|
||||||
status = if (draw) GameStatus.TIMEOUT_DRAW else GameStatus.TIMEOUT,
|
status = if (draw) GameStatus.TIMEOUT_DRAW else GameStatus.TIMEOUT,
|
||||||
timedOutSide = flag
|
timedOutSide = flag
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
GameMode.PUZZLE -> _uiState.value = current.copy(clockState = cs)
|
GameMode.PUZZLE -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cc.skysparkle.matewave.viewmodel
|
|||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
import cc.skysparkle.matewave.network.NetworkLog
|
import cc.skysparkle.matewave.network.NetworkLog
|
||||||
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
import cc.skysparkle.matewave.spectate.SpectateTarget
|
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||||
@@ -16,7 +17,6 @@ import kotlinx.coroutines.delay
|
|||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.isActive
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
enum class SpectatePhase { CONNECTING, WATCHING, ENDED, LOST, FAILED }
|
enum class SpectatePhase { CONNECTING, WATCHING, ENDED, LOST, FAILED }
|
||||||
@@ -129,16 +129,33 @@ class SpectatorViewModel : ViewModel() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
showClocks()
|
showClocks()
|
||||||
if (ticker?.isActive != true) {
|
if (clockUpdated || ticker?.isActive != true) {
|
||||||
|
ticker?.cancel()
|
||||||
ticker = viewModelScope.launch {
|
ticker = viewModelScope.launch {
|
||||||
while (isActive) {
|
while (true) {
|
||||||
delay(TICK_MS)
|
delay(untilShownSecondChanges() ?: break)
|
||||||
if (_uiState.value.phase == SpectatePhase.WATCHING) showClocks()
|
if (_uiState.value.phase != SpectatePhase.WATCHING) break
|
||||||
|
showClocks()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Milliseconds until the running clock shows the next second; null while nothing counts down. */
|
||||||
|
private fun untilShownSecondChanges(): Long? {
|
||||||
|
if (_uiState.value.phase != SpectatePhase.WATCHING) return null
|
||||||
|
val view = game.view ?: return null
|
||||||
|
val clock = view.clock ?: return null
|
||||||
|
if (view.result != null) return null
|
||||||
|
val shown = clock.advancedBy((System.nanoTime() - clockAtNanos) / 1_000_000L)
|
||||||
|
val left = when (clock.running) {
|
||||||
|
PieceColor.WHITE -> shown.whiteMs
|
||||||
|
PieceColor.BLACK -> shown.blackMs
|
||||||
|
null -> return null
|
||||||
|
}
|
||||||
|
return if (left > 0) left % 1_000 + 1 else null
|
||||||
|
}
|
||||||
|
|
||||||
/** Clocks count down locally between the host's updates. */
|
/** Clocks count down locally between the host's updates. */
|
||||||
private fun showClocks() {
|
private fun showClocks() {
|
||||||
val view = game.view ?: return
|
val view = game.view ?: return
|
||||||
@@ -167,8 +184,4 @@ class SpectatorViewModel : ViewModel() {
|
|||||||
events.close()
|
events.close()
|
||||||
super.onCleared()
|
super.onCleared()
|
||||||
}
|
}
|
||||||
|
|
||||||
private companion object {
|
|
||||||
const val TICK_MS = 250L
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 4.1 KiB |
|
Before Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 5.4 KiB |
|
Before Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 7.3 KiB |
|
Before Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 6.1 KiB |
|
Before Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 5.7 KiB |
|
Before Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 7.8 KiB |
|
Before Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 5.1 KiB |