Watch friends' LAN games from the Friends section

This commit is contained in:
2026-10-25 10:42:39 +02:00
parent fb58dfb4ae
commit f59e461405
20 changed files with 973 additions and 55 deletions
@@ -12,7 +12,9 @@ import androidx.activity.compose.setContent
import cc.skysparkle.matewave.audio.SoundManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
@@ -110,6 +112,10 @@ private fun AppNavHost() {
// Presence is shared with the background service, so the lists stay the same in both.
val presence = remember { PresenceHub.get(context) }
var spectateTarget by androidx.compose.runtime.saveable.rememberSaveable(saver = SpectateTargetSaver) {
androidx.compose.runtime.mutableStateOf<cc.skysparkle.matewave.spectate.SpectateTarget?>(null)
}
androidx.compose.runtime.DisposableEffect(Unit) {
if (cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled) {
cc.skysparkle.matewave.presence.PresenceService.start(context)
@@ -231,6 +237,10 @@ private fun AppNavHost() {
FriendsScreen(
presence = presence,
onPlay = { navController.navigate("connectionNearby") },
onWatch = { target ->
spectateTarget = target
navController.navigate("spectate")
},
onHomeClick = { navController.popBackStack("menu", inclusive = false) },
onSettingsClick = {
navController.popBackStack("menu", inclusive = false)
@@ -243,6 +253,19 @@ private fun AppNavHost() {
)
}
composable("spectate") {
val target = spectateTarget
val backToFriends: () -> Unit = {
if (!navController.popBackStack("friends", inclusive = false)) navController.popBackStack()
}
if (target == null) {
LaunchedEffect(Unit) { backToFriends() }
} else {
PlayScreenMusic()
cc.skysparkle.matewave.ui.screens.SpectatorScreen(target = target, onBackToFriends = backToFriends)
}
}
composable("vsAiSetup") {
VsAiSetupScreen(
onBack = { navController.popBackStack() },
@@ -324,6 +347,18 @@ private fun AppNavHost() {
}
}
private val SpectateTargetSaver = androidx.compose.runtime.saveable.Saver<
androidx.compose.runtime.MutableState<cc.skysparkle.matewave.spectate.SpectateTarget?>, List<Any>
>(
save = { state -> state.value?.let { arrayListOf<Any>(it.host, it.port, it.gameTag) } },
restore = { saved ->
val target = if (saved.size == 3) {
cc.skysparkle.matewave.spectate.SpectateTarget(saved[0] as String, saved[1] as Int, saved[2] as String)
} else null
androidx.compose.runtime.mutableStateOf(target)
}
)
private val TAB_ROUTES = setOf("menu", "friends", "settings", "account")
private fun isTabSwitch(from: String?, to: String?): Boolean =
@@ -67,6 +67,9 @@ sealed class GameMessage {
val newGameId: String = ""
) : GameMessage()
/** Host to guest: how many spectators watch. Older versions skip it as an unknown type. */
data class SpectatorCountMsg(val count: Int, val gameId: String = "") : GameMessage()
fun toJson(): String {
val o = JSONObject()
when (this) {
@@ -99,6 +102,7 @@ sealed class GameMessage {
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
}
is SpectatorCountMsg -> { o.put("type", "spectators"); o.put("n", count); o.put("gameId", gameId) }
is ProfileMsg -> {
o.put("type", "profile")
o.put("userId", userId)
@@ -154,6 +158,7 @@ sealed class GameMessage {
o.optString("gameId", ""),
o.optString("newGameId", "")
)
"spectators" -> SpectatorCountMsg(o.getInt("n"), o.optString("gameId", ""))
"profile" -> ProfileMsg(
userId = o.optString("userId", "").ifBlank { o.getString("name") },
@@ -30,7 +30,11 @@ data class LanPeer(
val signature: String = "",
/** Raw NSD service name, used to remove the peer when the service is lost. */
val serviceName: String = ""
val serviceName: String = "",
/** Tag of the LAN game the peer plays, empty when not in one. */
val gameTag: String = "",
/** Spectator port when the peer hosts a watchable game, otherwise 0. */
val spectatePort: Int = 0
) {
val id: String get() = "$host:$port"
}
@@ -224,6 +228,7 @@ class LanTransport(
cc.skysparkle.matewave.security.DeviceKeys.sign(
context, presencePayload(profile.userId, shownName, profile.elo)
)?.let { setAttribute("sig", it) }
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
}
}
val listener = object : NsdManager.RegistrationListener {
@@ -353,6 +358,7 @@ class LanTransport(
fun attr(key: String): String = runCatching {
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
}.getOrDefault("")
val game = cc.skysparkle.matewave.spectate.SpectatorAdvert.parse(::attr)
return LanPeer(
name = displayNameOf(info.serviceName),
host = host,
@@ -363,7 +369,9 @@ class LanTransport(
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
signature = attr("sig"),
serviceName = info.serviceName ?: ""
serviceName = info.serviceName ?: "",
gameTag = game.gameTag,
spectatePort = game.spectatePort
)
}
@@ -517,7 +525,7 @@ class LanTransport(
try {
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
while (true) {
val read = readBoundedLine(reader)
val read = readBoundedLine(reader, MAX_MESSAGE_CHARS)
if (read is LineResult.EndOfStream) break
if (sock !== socket) break
if (read is LineResult.TooLong) {
@@ -577,27 +585,6 @@ class LanTransport(
}
}
private sealed class LineResult {
data class Line(val text: String) : LineResult()
object TooLong : LineResult()
object EndOfStream : LineResult()
}
private fun readBoundedLine(reader: BufferedReader): LineResult {
val builder = StringBuilder()
while (true) {
val ch = reader.read()
if (ch == -1) {
return if (builder.isEmpty()) LineResult.EndOfStream
else LineResult.Line(builder.toString())
}
if (ch == '\n'.code) return LineResult.Line(builder.toString())
if (ch == '\r'.code) continue
if (builder.length >= MAX_MESSAGE_CHARS) return LineResult.TooLong
builder.append(ch.toChar())
}
}
override fun send(message: GameMessage) {
val json = message.toJson()
val size = json.length
@@ -19,7 +19,10 @@ data class DiscoveredPeer(
val elo: Int,
val fingerprint: String,
val address: String
val address: String,
val host: String = "",
val gameTag: String = "",
val spectatePort: Int = 0
)
/**
@@ -159,7 +162,10 @@ class LocalPresence(
name = peer.displayName.ifEmpty { peer.name },
elo = peer.elo,
fingerprint = peer.fingerprint,
address = peer.id
address = peer.id,
host = peer.host,
gameTag = peer.gameTag,
spectatePort = peer.spectatePort
)
}
_peers.value = result
@@ -78,14 +78,16 @@ fun ChessBoardView(
interactionEnabled: Boolean = true,
/** A square briefly tinted to confirm or reject a move (puzzles). */
flashSquare: Int? = null,
flashColor: Color = Color.Transparent
flashColor: Color = Color.Transparent,
/** Overrides the last-move setting; null follows it. */
highlightLastMove: Boolean? = null
) {
val context = LocalContext.current
val appearance = remember { BoardAppearance(context) }
val theme = appearance.theme
val showCoords = appearance.showCoordinates
val imagePieces = appearance.useImagePieces
val showLastMove = appearance.showLastMove
val showLastMove = highlightLastMove ?: appearance.showLastMove
val showCheck = appearance.showCheckHighlight
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
@@ -0,0 +1,42 @@
package cc.skysparkle.matewave.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import cc.skysparkle.matewave.R
import cc.skysparkle.matewave.ui.theme.ink
/** Small, quiet spectator counter for the top bar: an eye and "7" or "7/20". */
@Composable
fun SpectatorBadge(count: Int, max: Int? = null, modifier: Modifier = Modifier) {
val description = stringResource(R.string.spectators_description, count)
Row(
modifier = modifier
.padding(end = 12.dp)
.clip(RoundedCornerShape(50))
.background(ink.copy(alpha = 0.10f))
.padding(horizontal = 10.dp, vertical = 4.dp)
.clearAndSetSemantics { contentDescription = description },
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
AppIcon(R.drawable.ic_spectators, size = 16.dp, tint = ink.copy(alpha = 0.7f))
Text(
if (max != null) "$count/$max" else count.toString(),
color = ink.copy(alpha = 0.8f),
style = MaterialTheme.typography.labelMedium
)
}
}
@@ -46,6 +46,15 @@ import cc.skysparkle.matewave.ui.components.AppIcon
import cc.skysparkle.matewave.ui.components.BottomTab
import cc.skysparkle.matewave.ui.components.GlassScaffold
import cc.skysparkle.matewave.ui.theme.ChessGreen
import cc.skysparkle.matewave.spectate.FriendGameStatus
import cc.skysparkle.matewave.spectate.FriendStatusResolver
import cc.skysparkle.matewave.spectate.NearbyPlayerGame
import cc.skysparkle.matewave.spectate.PresenceStatus
import cc.skysparkle.matewave.spectate.SpectateTarget
import cc.skysparkle.matewave.spectate.SpectatorMessage
import cc.skysparkle.matewave.spectate.SpectatorProbe
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
@Composable
fun FriendsScreen(
@@ -53,7 +62,8 @@ fun FriendsScreen(
onHomeClick: () -> Unit,
onSettingsClick: () -> Unit,
onAccountClick: () -> Unit,
onPlay: () -> Unit = {}
onPlay: () -> Unit = {},
onWatch: (SpectateTarget) -> Unit = {}
) {
var onlineOnly by remember { mutableStateOf(false) }
var version by remember { mutableStateOf(0) }
@@ -64,6 +74,28 @@ fun FriendsScreen(
val peers by presence.peers.collectAsState()
val friends = remember(peers, version) { FriendsStore.list() }
// Who plays a LAN game, and live spectator counts from each host while the list is open.
val nearbyGames = remember(peers) {
peers.values.associate { it.playerId to NearbyPlayerGame(it.playerId, it.host, it.gameTag, it.spectatePort) }
}
val hosts = remember(nearbyGames) { FriendStatusResolver.targets(nearbyGames.values) }
var probes by remember { mutableStateOf<Map<SpectateTarget, SpectatorMessage.Status>>(emptyMap()) }
androidx.compose.runtime.LaunchedEffect(hosts) {
if (hosts.isEmpty()) {
probes = emptyMap()
return@LaunchedEffect
}
while (true) {
probes = kotlinx.coroutines.coroutineScope {
hosts.map { host ->
async(kotlinx.coroutines.Dispatchers.IO) { SpectatorProbe.query(host.host, host.port)?.let { host to it } }
}.awaitAll().filterNotNull().toMap()
}
kotlinx.coroutines.delay(PROBE_INTERVAL_MS)
}
}
val statusOf: (String) -> FriendGameStatus = { id -> FriendStatusResolver.resolve(id, nearbyGames, probes) }
// Fresh search on opening, then refresh "5 min ago" labels while the screen is visible.
androidx.compose.runtime.LaunchedEffect(Unit) {
presence.refresh()
@@ -115,18 +147,20 @@ fun FriendsScreen(
FriendGroup(
title = stringResource(R.string.friends_group_favorites),
list = favorites,
isOnline = presence::isOnline,
statusOf = statusOf,
onOpen = { opened = it },
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
onPlay = onPlay
onPlay = onPlay,
onWatch = onWatch
)
FriendGroup(
title = if (favorites.isNotEmpty()) stringResource(R.string.friends_group_others) else null,
list = others,
isOnline = presence::isOnline,
statusOf = statusOf,
onOpen = { opened = it },
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
onPlay = onPlay
onPlay = onPlay,
onWatch = onWatch
)
if (strangers.isNotEmpty()) {
@@ -134,11 +168,13 @@ fun FriendsScreen(
ListGroup {
strangers.sortedBy { it.name }.forEachIndexed { index, peer ->
if (index > 0) ListDivider(inset = 68)
val status = statusOf(peer.playerId)
ListRow(
title = displayName(peer.name, peer.playerId),
subtitle = stringResource(R.string.friends_rating, peer.elo),
subtitle = stringResource(R.string.friends_rating, peer.elo) + " · " + statusText(status.status, 0),
subtitleColor = statusColor(status.status),
leading = { AvatarCircle(base64 = null, size = 40.dp) },
trailing = { PlayChip(onPlay) }
trailing = { StatusAction(status, onPlay, onWatch) }
)
}
}
@@ -149,7 +185,7 @@ fun FriendsScreen(
}
opened?.let { friend ->
FriendCard(friend = friend, online = presence.isOnline(friend.userId), onDismiss = { opened = null })
FriendCard(friend = friend, status = statusOf(friend.userId).status, onDismiss = { opened = null })
}
}
}
@@ -158,10 +194,11 @@ fun FriendsScreen(
private fun FriendGroup(
title: String?,
list: List<FriendEntry>,
isOnline: (String) -> Boolean,
statusOf: (String) -> FriendGameStatus,
onOpen: (FriendEntry) -> Unit,
onToggleFavorite: (FriendEntry) -> Unit,
onPlay: () -> Unit
onPlay: () -> Unit,
onWatch: (SpectateTarget) -> Unit
) {
if (list.isEmpty()) return
if (title != null) SectionCaption(title)
@@ -170,10 +207,11 @@ private fun FriendGroup(
if (index > 0) ListDivider(inset = 68)
FriendRow(
friend = friend,
online = isOnline(friend.userId),
status = statusOf(friend.userId),
onOpen = { onOpen(friend) },
onToggleFavorite = { onToggleFavorite(friend) },
onPlay = onPlay
onPlay = onPlay,
onWatch = onWatch
)
}
}
@@ -205,7 +243,7 @@ private fun PlayChip(onClick: () -> Unit) {
}
@Composable
private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Unit) {
private fun FriendCard(friend: FriendEntry, status: PresenceStatus, onDismiss: () -> Unit) {
Dialog(onDismissRequest = onDismiss) {
Column(
modifier = Modifier
@@ -257,9 +295,12 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
}
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
if (online) stringResource(R.string.friends_online)
else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
color = if (online) Color(0xFF7BE495) else ink.copy(alpha = 0.6f),
statusText(status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
color = when (status) {
PresenceStatus.ONLINE -> Color(0xFF7BE495)
PresenceStatus.IN_GAME -> InGameColor
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.6f)
},
style = MaterialTheme.typography.bodyMedium
)
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
@@ -276,32 +317,33 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
@Composable
private fun FriendRow(
friend: FriendEntry,
online: Boolean,
status: FriendGameStatus,
onOpen: () -> Unit,
onToggleFavorite: () -> Unit,
onPlay: () -> Unit
onPlay: () -> Unit,
onWatch: (SpectateTarget) -> Unit
) {
ListRow(
title = displayName(friend.name, friend.userId),
subtitle = stringResource(R.string.friends_rating, friend.elo) + " · " +
(if (online) stringResource(R.string.friends_online) else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs))),
subtitleColor = if (online) ChessGreen else ink.copy(alpha = 0.55f),
statusText(status.status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
subtitleColor = statusColor(status.status),
leading = {
Box {
AvatarCircle(base64 = friend.avatarBase64, size = 40.dp)
if (online) {
if (status.status != PresenceStatus.OFFLINE) {
Box(
Modifier
.align(Alignment.BottomEnd)
.size(11.dp)
.clip(CircleShape)
.background(ChessGreen)
.background(if (status.status == PresenceStatus.IN_GAME) InGameColor else ChessGreen)
)
}
}
},
trailing = {
if (online) PlayChip(onPlay)
StatusAction(status, onPlay, onWatch)
AppIcon(
R.drawable.ic_star,
size = 20.dp,
@@ -317,6 +359,58 @@ private fun FriendRow(
)
}
private val InGameColor = Color(0xFFFFB86B)
private const val PROBE_INTERVAL_MS = 3_000L
/** Play for someone who is free, Watch (with the live count) for someone in a LAN game. */
@Composable
private fun StatusAction(status: FriendGameStatus, onPlay: () -> Unit, onWatch: (SpectateTarget) -> Unit) {
when (status.status) {
PresenceStatus.ONLINE -> PlayChip(onPlay)
PresenceStatus.IN_GAME -> status.target?.let { target -> WatchChip(status) { onWatch(target) } }
PresenceStatus.OFFLINE -> Unit
}
}
@Composable
private fun WatchChip(status: FriendGameStatus, onClick: () -> Unit) {
val enabled = !status.full
val spectators = status.spectators
val label = when {
status.full -> stringResource(R.string.friends_watch_full)
spectators != null -> stringResource(R.string.friends_watch_count, spectators, status.max)
else -> stringResource(R.string.friends_watch)
}
Text(
label,
color = if (enabled) Color.White else ink.copy(alpha = 0.5f),
style = MaterialTheme.typography.labelLarge,
maxLines = 1,
modifier = Modifier
.clip(RoundedCornerShape(50))
.background(if (enabled) ChessGreen else ink.copy(alpha = 0.12f))
.then(if (enabled) Modifier.clickable(onClick = onClick) else Modifier)
.padding(horizontal = 14.dp, vertical = 6.dp)
)
}
@Composable
private fun statusText(status: PresenceStatus, lastSeenMs: Long): String = when (status) {
PresenceStatus.ONLINE -> stringResource(R.string.friends_online)
PresenceStatus.IN_GAME -> stringResource(R.string.friends_in_game)
PresenceStatus.OFFLINE ->
if (lastSeenMs <= 0) stringResource(R.string.friends_offline)
else stringResource(R.string.friends_offline) + " · " + lastSeenText(lastSeenMs)
}
@Composable
private fun statusColor(status: PresenceStatus): Color = when (status) {
PresenceStatus.ONLINE -> ChessGreen
PresenceStatus.IN_GAME -> InGameColor
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.55f)
}
@Composable
private fun lastSeenText(lastSeenMs: Long): String {
if (lastSeenMs <= 0) return stringResource(R.string.friends_offline)
@@ -101,6 +101,11 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
GlassScaffold(
title = "",
onBack = requestExit,
actions = {
if (state.mode == GameMode.VS_PLAYER_NETWORK && state.spectatorCount > 0) {
cc.skysparkle.matewave.ui.components.SpectatorBadge(state.spectatorCount)
}
},
titleContent = if (showOpening && opening != null) {
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
} else null
@@ -490,7 +495,7 @@ private fun PlayerRow(
}
@Composable
private fun BigClock(millis: Long, active: Boolean) {
internal fun BigClock(millis: Long, active: Boolean) {
val totalSeconds = millis / 1000
val low = active && totalSeconds < 20
val color = when {
@@ -0,0 +1,269 @@
package cc.skysparkle.matewave.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import cc.skysparkle.matewave.R
import cc.skysparkle.matewave.data.FriendsStore
import cc.skysparkle.matewave.engine.ChessEngine
import cc.skysparkle.matewave.engine.Material
import cc.skysparkle.matewave.engine.PieceColor
import cc.skysparkle.matewave.engine.opposite
import cc.skysparkle.matewave.network.NetworkRequirements
import cc.skysparkle.matewave.openings.OpeningBook
import cc.skysparkle.matewave.spectate.SpectateTarget
import cc.skysparkle.matewave.spectate.SpectatorClient
import cc.skysparkle.matewave.spectate.SpectatorOutcome
import cc.skysparkle.matewave.spectate.SpectatorResult
import cc.skysparkle.matewave.spectate.SpectatorView
import cc.skysparkle.matewave.ui.components.AppDialog
import cc.skysparkle.matewave.ui.components.ButtonIcon
import cc.skysparkle.matewave.ui.components.CapturedPiecesRow
import cc.skysparkle.matewave.ui.components.ChessBoardView
import cc.skysparkle.matewave.ui.components.DialogAction
import cc.skysparkle.matewave.ui.components.DialogText
import cc.skysparkle.matewave.ui.components.GlassOutlinedButton
import cc.skysparkle.matewave.ui.components.GlassScaffold
import cc.skysparkle.matewave.ui.components.MovesBar
import cc.skysparkle.matewave.ui.components.SpectatorBadge
import cc.skysparkle.matewave.ui.theme.ChessGreen
import cc.skysparkle.matewave.ui.theme.ink
import cc.skysparkle.matewave.viewmodel.SpectatePhase
import cc.skysparkle.matewave.viewmodel.SpectateUiState
import cc.skysparkle.matewave.viewmodel.SpectatorViewModel
import kotlinx.coroutines.delay
/** Read-only view of a friend's LAN game. */
@Composable
fun SpectatorScreen(target: SpectateTarget, onBackToFriends: () -> Unit) {
val viewModel: SpectatorViewModel = viewModel()
LaunchedEffect(target) { viewModel.start(target) }
val state by viewModel.uiState.collectAsState()
val context = LocalContext.current
var left by remember { mutableStateOf(false) }
val backToFriends: () -> Unit = {
if (!left) {
left = true
onBackToFriends()
}
}
androidx.activity.compose.BackHandler(onBack = backToFriends)
// Wi-Fi switched off here: say so at once instead of waiting for the connection to time out.
LaunchedEffect(Unit) {
while (true) {
delay(WIFI_CHECK_MS)
if (!NetworkRequirements.check(context).wifiConnected) viewModel.onNetworkLost()
}
}
val view = state.view
var resultHidden by remember(view?.gameId, state.phase) { mutableStateOf(false) }
GlassScaffold(
title = stringResource(R.string.spectate_title),
onBack = backToFriends,
actions = { if (view != null) SpectatorBadge(state.spectators, state.max) }
) {
if (state.phase == SpectatePhase.CONNECTING) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CircularProgressIndicator(color = ink, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
Text(stringResource(R.string.spectate_joining), color = ink, style = MaterialTheme.typography.bodyMedium)
}
}
if (view == null) return@GlassScaffold
val bottom = if (state.flipped) PieceColor.BLACK else PieceColor.WHITE
val material = remember(view.board) { Material.balance(view.board) }
val checkSquare = if (ChessEngine.isInCheck(view.board, view.board.sideToMove)) {
view.board.kingSquare(view.board.sideToMove)
} else null
SpectatorPlayerRow(view, bottom.opposite(), state, material)
ChessBoardView(
board = view.board,
selectedSquare = null,
legalTargets = emptyList(),
kingInCheckSquare = checkSquare,
flipped = state.flipped,
onSquareClick = {},
lastMove = view.lastMove,
interactionEnabled = false,
highlightLastMove = true
)
SpectatorPlayerRow(view, bottom, state, material)
val bookPlies = remember(view.moveSans) { OpeningBook.bookDepth(view.moveSans) }
MovesBar(
sans = view.moveSans,
startBoard = view.startBoard,
currentIndex = view.moveSans.size,
opening = null,
bookPlies = bookPlies
)
GlassOutlinedButton(onClick = viewModel::flip, modifier = Modifier.fillMaxWidth()) {
ButtonIcon(R.drawable.ic_board_view)
Text(stringResource(R.string.spectate_flip), color = ink, maxLines = 1)
}
if (state.phase == SpectatePhase.ENDED && resultHidden) {
GlassOutlinedButton(onClick = { resultHidden = false }, modifier = Modifier.fillMaxWidth()) {
Text(stringResource(R.string.game_over_title), color = ink, maxLines = 1)
}
}
}
when (state.phase) {
SpectatePhase.ENDED -> {
val result = view?.result
if (result != null && !resultHidden) {
AppDialog(
onDismissRequest = { resultHidden = true },
title = stringResource(R.string.game_over_title),
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
) {
DialogText(resultText(result))
}
}
}
SpectatePhase.LOST -> {
LaunchedEffect(Unit) {
delay(LOST_RETURN_MS)
backToFriends()
}
AppDialog(
onDismissRequest = backToFriends,
title = stringResource(R.string.connection_lost),
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
) {
DialogText(stringResource(R.string.spectate_lost_text))
}
}
SpectatePhase.FAILED -> {
val (title, text) = failureTexts(state.failure, state.max)
AppDialog(
onDismissRequest = backToFriends,
title = title,
actions = { DialogAction(stringResource(R.string.spectate_back_to_friends), backToFriends) }
) {
DialogText(text)
}
}
else -> Unit
}
}
@Composable
private fun failureTexts(failure: SpectatorClient.Failure?, max: Int): Pair<String, String> = when (failure) {
SpectatorClient.Failure.FULL ->
stringResource(R.string.spectate_full_title) to stringResource(R.string.spectate_full_text, max)
SpectatorClient.Failure.UPDATE_THIS_APP ->
stringResource(R.string.spectate_update_title) to stringResource(R.string.spectate_update_this)
SpectatorClient.Failure.UPDATE_HOST_APP ->
stringResource(R.string.spectate_update_title) to stringResource(R.string.spectate_update_host)
SpectatorClient.Failure.NO_GAME ->
stringResource(R.string.spectate_failed_title) to stringResource(R.string.spectate_no_game)
SpectatorClient.Failure.UNREACHABLE, null ->
stringResource(R.string.spectate_failed_title) to stringResource(R.string.spectate_unreachable)
}
@Composable
private fun resultText(result: SpectatorResult): String {
val white = stringResource(R.string.color_white)
val black = stringResource(R.string.color_black)
val winner = result.winner
fun name(side: PieceColor) = if (side == PieceColor.WHITE) white else black
return when (result.outcome) {
SpectatorOutcome.CHECKMATE -> winner?.let { stringResource(R.string.checkmate_winner, name(it)) }
SpectatorOutcome.TIMEOUT -> winner?.let { stringResource(R.string.timeout_winner, name(it)) }
SpectatorOutcome.RESIGNATION -> winner?.let { stringResource(R.string.resignation_winner, name(it)) }
SpectatorOutcome.LEFT -> winner?.let { stringResource(R.string.spectate_left_win, name(it.opposite()), name(it)) }
SpectatorOutcome.STALEMATE -> stringResource(R.string.stalemate)
SpectatorOutcome.FIFTY_MOVES -> stringResource(R.string.draw_50_moves)
SpectatorOutcome.REPETITION -> stringResource(R.string.draw_repetition)
SpectatorOutcome.INSUFFICIENT_MATERIAL -> stringResource(R.string.draw_material)
SpectatorOutcome.TIMEOUT_DRAW -> stringResource(R.string.timeout_draw)
SpectatorOutcome.AGREEMENT -> stringResource(R.string.draw_agreement)
SpectatorOutcome.INTERRUPTED -> stringResource(R.string.spectate_interrupted)
SpectatorOutcome.UNKNOWN -> null
} ?: stringResource(R.string.game_over_title)
}
@Composable
private fun SpectatorPlayerRow(
view: SpectatorView,
side: PieceColor,
state: SpectateUiState,
material: cc.skysparkle.matewave.engine.MaterialBalance
) {
val player = if (side == PieceColor.WHITE) view.white else view.black
val active = view.result == null && view.board.sideToMove == side
// Known friends get their saved avatar; nothing large travels to spectators.
val avatar = remember(player.id) {
if (player.id.isEmpty()) null else FriendsStore.list().firstOrNull { it.userId == player.id }?.avatarBase64
}
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Box(
modifier = Modifier
.size(8.dp)
.clip(CircleShape)
.background(if (active) ChessGreen else ink.copy(alpha = 0.15f))
)
Spacer(Modifier.width(10.dp))
AvatarCircle(base64 = avatar, size = 34.dp)
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
player.name.ifBlank { stringResource(R.string.player_default_name) },
color = if (active) ink else ink.copy(alpha = 0.75f),
style = MaterialTheme.typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
if (player.elo > 0) {
Text(
stringResource(R.string.friends_elo_value, player.elo),
color = ink.copy(alpha = 0.55f),
style = MaterialTheme.typography.labelSmall
)
}
CapturedPiecesRow(
captured = if (side == PieceColor.WHITE) material.capturedByWhite else material.capturedByBlack,
capturedColor = side.opposite(),
advantage = if (side == PieceColor.WHITE) material.advantage else -material.advantage
)
}
val millis = if (side == PieceColor.WHITE) state.whiteMs else state.blackMs
if (millis != null) BigClock(millis, active)
}
}
private const val WIFI_CHECK_MS = 2_000L
private const val LOST_RETURN_MS = 4_000L
@@ -33,6 +33,15 @@ import cc.skysparkle.matewave.security.KnownPeers
import cc.skysparkle.matewave.security.SessionAuth
import cc.skysparkle.matewave.security.TrustResult
import cc.skysparkle.matewave.settings.Haptics
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
import cc.skysparkle.matewave.spectate.SpectatorAdvert
import cc.skysparkle.matewave.spectate.SpectatorBroadcaster
import cc.skysparkle.matewave.spectate.SpectatorClock
import cc.skysparkle.matewave.spectate.SpectatorHub
import cc.skysparkle.matewave.spectate.SpectatorPlayer
import cc.skysparkle.matewave.spectate.SpectatorResult
import cc.skysparkle.matewave.spectate.SpectatorResults
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
import cc.skysparkle.matewave.stats.Stats
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -95,7 +104,10 @@ data class GameUiState(
val opponentLeftMidGame: Boolean = false,
val rematchOfferFromOpponent: Boolean = false,
val activeTransport: TransportType? = null
val activeTransport: TransportType? = null,
/** Spectators watching this LAN game, shown to both players. */
val spectatorCount: Int = 0
)
data class PendingPromotion(val from: Int, val to: Int)
@@ -172,6 +184,16 @@ class GameViewModel : ViewModel() {
private var currentPly: Int = 0
private var lastOpponentRemaining: Long = Long.MAX_VALUE
// Spectating: the host serves spectators, both players announce the game's tag.
private var spectators: SpectatorBroadcaster? = null
private var spectatorWatcher: Job? = null
private var spectatorCountJob: Job? = null
private var spectatingDecided = false
private var spectateTag: String = ""
private var spectatorPlayers: Pair<SpectatorPlayer, SpectatorPlayer>? = null
private var spectatorPlayersKey: String = ""
private var lastSentSpectatorCount = 0
init {
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
}
@@ -689,6 +711,7 @@ class GameViewModel : ViewModel() {
pendingLeave = null
handshakeTimeoutJob?.cancel()
handshakeTimeoutJob = null
stopSpectating()
cancelAi()
// A paused game against the AI stays saved and can be continued later.
persistIfResumable()
@@ -729,6 +752,8 @@ class GameViewModel : ViewModel() {
heartbeat?.stop()
heartbeat = cc.skysparkle.matewave.network.Heartbeat(viewModelScope, transport).also { it.start() }
spectatorWatcher = viewModelScope.launch { _uiState.collect { onStateForSpectators(it) } }
var profileSent = false
var connectedOnce = false
val connectStartedAt = System.currentTimeMillis()
@@ -965,6 +990,10 @@ class GameViewModel : ViewModel() {
)
}
is GameMessage.PingMsg -> Unit
is GameMessage.SpectatorCountMsg -> {
if (isNetworkHost) return
_uiState.value = _uiState.value.copy(spectatorCount = msg.count.coerceIn(0, MAX_SPECTATORS))
}
is GameMessage.TimeoutMsg -> {
if (!belongsToCurrentGame(msg.gameId)) return
val state = _uiState.value
@@ -1113,6 +1142,9 @@ class GameViewModel : ViewModel() {
}
private fun endNetworkSession() {
val state = _uiState.value
// The players lost each other: spectators see the game end as interrupted.
stopSpectating(if (state.status == GameStatus.ONGOING) SpectatorResults.interrupted else null)
opponentFlagJob?.cancel()
opponentFlagJob = null
clock?.stop()
@@ -1137,7 +1169,9 @@ class GameViewModel : ViewModel() {
return
}
if (state.status == GameStatus.ONGOING && state.handshake == HandshakeState.PLAYING) {
val leftMidGame = state.status == GameStatus.ONGOING && state.handshake == HandshakeState.PLAYING
stopSpectating(if (leftMidGame) SpectatorResults.leftBy(state.myColor) else null)
if (leftMidGame) {
applyNetworkResultElo(0.0)
}
opponentFlagJob?.cancel()
@@ -1218,7 +1252,8 @@ class GameViewModel : ViewModel() {
handshake = state.handshake,
activeTransport = state.activeTransport,
opponentUnverified = state.opponentUnverified,
chatMessages = state.chatMessages
chatMessages = state.chatMessages,
spectatorCount = state.spectatorCount
)
setupClock(timeControl)
}
@@ -1333,6 +1368,119 @@ class GameViewModel : ViewModel() {
// endregion
// region Spectators
/**
* Once a LAN game is under way, the host opens its spectator socket and both players announce
* the game's tag; players who chose not to be visible on the network are not watchable.
*/
private fun onStateForSpectators(state: GameUiState) {
if (state.mode != GameMode.VS_PLAYER_NETWORK) return
spectators?.update(spectatorSnapshot(state))
if (spectatingDecided) return
val live = state.handshake == HandshakeState.PLAYING &&
state.connectionState == ConnectionState.CONNECTED &&
state.activeTransport == TransportType.LAN
if (!live) return
val ctx = appContext ?: return
spectatingDecided = true
if (!cc.skysparkle.matewave.presence.PresenceSettings(ctx).announceEnabled) return
spectateTag = SpectatorAdvert.tagOf(networkGameId)
if (spectateTag.isEmpty()) return
if (isNetworkHost) startSpectatorHub(ctx) else advertiseGame(ctx, SpectatorAdvert.State(spectateTag, 0))
}
private fun startSpectatorHub(ctx: android.content.Context) {
val generation = sessionGeneration
val hub = SpectatorHub(log = { NetworkLog.log("SPECTATE", it) })
viewModelScope.launch {
var serving = false
try {
val port = withContext(Dispatchers.IO) { runCatching { hub.start() }.getOrNull() }
if (port == null) NetworkLog.log("SPECTATE", "Could not open the spectator port")
// The game may have ended while the port was opening.
if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch
val broadcaster = SpectatorBroadcaster(hub)
broadcaster.update(spectatorSnapshot(_uiState.value))
spectators = broadcaster
serving = true
spectatorCountJob = viewModelScope.launch { hub.count.collect { onSpectatorCount(it) } }
advertiseGame(ctx, SpectatorAdvert.State(spectateTag, port))
NetworkLog.log("SPECTATE", "Spectators can join on port $port")
} finally {
if (!serving) hub.close()
}
}
}
private fun onSpectatorCount(count: Int) {
if (_uiState.value.spectatorCount != count) {
_uiState.value = _uiState.value.copy(spectatorCount = count)
}
if (count != lastSentSpectatorCount && canSendGameMessages() &&
sendGameMessage(GameMessage.SpectatorCountMsg(count, networkGameId))
) {
lastSentSpectatorCount = count
}
}
private fun advertiseGame(ctx: android.content.Context, state: SpectatorAdvert.State) {
if (SpectatorAdvert.update(state)) cc.skysparkle.matewave.network.Transports.lan(ctx).republishProfile()
}
/** Ends spectating for this session; [final] tells spectators how a game cut short ended. */
private fun stopSpectating(final: SpectatorResult? = null) {
spectatorWatcher?.cancel()
spectatorWatcher = null
spectatorCountJob?.cancel()
spectatorCountJob = null
spectators?.let { broadcaster ->
val last = final?.let { spectatorSnapshot(_uiState.value).copy(result = it) }
broadcaster.close(last)
}
spectators = null
spectatingDecided = false
spectateTag = ""
spectatorPlayers = null
spectatorPlayersKey = ""
lastSentSpectatorCount = 0
appContext?.let { ctx ->
if (SpectatorAdvert.clear()) cc.skysparkle.matewave.network.Transports.lan(ctx).republishProfile()
}
if (_uiState.value.spectatorCount != 0) {
_uiState.value = _uiState.value.copy(spectatorCount = 0)
}
}
private fun spectatorSnapshot(state: GameUiState): SpectatorSnapshot {
val opponent = state.opponentProfile
val key = networkGameId + "|" + (opponent?.userId ?: "")
val players = spectatorPlayers?.takeIf { spectatorPlayersKey == key } ?: run {
val me = ProfileStore.get()
val mine = SpectatorPlayer(me.userId, me.name, me.elo)
val theirs = SpectatorPlayer(opponent?.userId ?: "", opponent?.name ?: "", opponent?.elo ?: 0)
(if (state.myColor == PieceColor.WHITE) mine to theirs else theirs to mine).also {
spectatorPlayers = it
spectatorPlayersKey = key
}
}
val timeControl = lastNetworkTimeControl
return SpectatorSnapshot(
gameId = networkGameId,
white = players.first,
black = players.second,
movesUci = moveLog.toList(),
initialSeconds = timeControl?.initialSeconds ?: 0,
incrementSeconds = timeControl?.incrementSeconds ?: 0,
clock = clock?.state?.value?.let { SpectatorClock(it.whiteMillis, it.blackMillis, it.running) },
result = SpectatorResults.of(
state.status, state.board.sideToMove, state.timedOutSide, state.resignedSide, state.opponentLeftMidGame
)
)
}
// endregion
// region Clock
private fun disposeClock() {
@@ -1418,6 +1566,7 @@ class GameViewModel : ViewModel() {
pendingLeave?.first?.cancel()
pendingLeave?.second?.disconnect()
pendingLeave = null
stopSpectating()
persistIfResumable()
clock?.stop()
@@ -0,0 +1,174 @@
package cc.skysparkle.matewave.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cc.skysparkle.matewave.network.NetworkLog
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
import cc.skysparkle.matewave.spectate.SpectateTarget
import cc.skysparkle.matewave.spectate.SpectatorClient
import cc.skysparkle.matewave.spectate.SpectatorGame
import cc.skysparkle.matewave.spectate.SpectatorMessage
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
import cc.skysparkle.matewave.spectate.SpectatorView
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
enum class SpectatePhase { CONNECTING, WATCHING, ENDED, LOST, FAILED }
data class SpectateUiState(
val phase: SpectatePhase = SpectatePhase.CONNECTING,
val failure: SpectatorClient.Failure? = null,
val view: SpectatorView? = null,
val whiteMs: Long? = null,
val blackMs: Long? = null,
val spectators: Int = 0,
val max: Int = MAX_SPECTATORS,
/** Board turned for this spectator only. */
val flipped: Boolean = false
)
/** Watches one LAN game read-only. Nothing here can reach the players. */
class SpectatorViewModel : ViewModel() {
private val _uiState = MutableStateFlow(SpectateUiState())
val uiState: StateFlow<SpectateUiState> = _uiState
private val game = SpectatorGame()
private val events = Channel<SpectatorClient.Event>(Channel.UNLIMITED)
private var client: SpectatorClient? = null
private var target: SpectateTarget? = null
private var clockAtNanos = 0L
private var ticker: Job? = null
init {
viewModelScope.launch { for (event in events) handle(event) }
}
fun start(target: SpectateTarget) {
if (this.target == target) return
this.target = target
client?.stop()
_uiState.value = SpectateUiState(flipped = _uiState.value.flipped)
client = SpectatorClient(target.host, target.port, { events.trySend(it) }).also { it.start() }
}
fun flip() {
_uiState.update { it.copy(flipped = !it.flipped) }
}
/** Wi-Fi went away on this device: no need to wait for the connection to time out. */
fun onNetworkLost() {
when (_uiState.value.phase) {
SpectatePhase.CONNECTING -> fail(SpectatorClient.Failure.UNREACHABLE)
SpectatePhase.WATCHING -> lose()
else -> Unit
}
}
private fun handle(event: SpectatorClient.Event) {
when (event) {
is SpectatorClient.Event.Joined -> {
_uiState.update { it.copy(spectators = event.welcome.count, max = event.welcome.max) }
load(event.welcome.game)
}
is SpectatorClient.Event.Received -> onMessage(event.message)
is SpectatorClient.Event.JoinFailed -> fail(event.failure)
is SpectatorClient.Event.Disconnected -> {
// After the result the host may leave; the result stays on screen.
if (_uiState.value.phase != SpectatePhase.ENDED) lose()
}
}
}
private fun onMessage(message: SpectatorMessage) {
val phase = _uiState.value.phase
if (phase == SpectatePhase.LOST || phase == SpectatePhase.FAILED) return
when (message) {
is SpectatorMessage.MovePlayed -> applied(game.onMove(message))
is SpectatorMessage.GameOver -> applied(game.onGameOver(message))
is SpectatorMessage.NewGame -> load(message.game)
is SpectatorMessage.Count -> _uiState.update { it.copy(spectators = message.count, max = message.max) }
is SpectatorMessage.Ping -> {
game.onClock(message.clock)
publish(clockUpdated = message.clock != null)
}
else -> Unit
}
}
private fun applied(result: SpectatorGame.Applied) {
when (result) {
SpectatorGame.Applied.APPLIED -> publish(clockUpdated = true)
SpectatorGame.Applied.NEEDS_RESYNC -> client?.requestResync()
SpectatorGame.Applied.IGNORED -> Unit
}
}
private fun load(snapshot: SpectatorSnapshot) {
if (game.load(snapshot)) {
publish(clockUpdated = true)
} else {
NetworkLog.log("SPECTATE", "Received game could not be replayed")
lose()
}
}
private fun publish(clockUpdated: Boolean) {
val view = game.view ?: return
if (clockUpdated) clockAtNanos = System.nanoTime()
_uiState.update {
it.copy(
phase = if (view.result != null) SpectatePhase.ENDED else SpectatePhase.WATCHING,
failure = null,
view = view
)
}
showClocks()
if (ticker?.isActive != true) {
ticker = viewModelScope.launch {
while (isActive) {
delay(TICK_MS)
if (_uiState.value.phase == SpectatePhase.WATCHING) showClocks()
}
}
}
}
/** Clocks count down locally between the host's updates. */
private fun showClocks() {
val view = game.view ?: return
val clock = view.clock
if (clock == null) {
_uiState.update { it.copy(whiteMs = null, blackMs = null) }
return
}
val shown = if (view.result == null) clock.advancedBy((System.nanoTime() - clockAtNanos) / 1_000_000L) else clock
_uiState.update { it.copy(whiteMs = shown.whiteMs, blackMs = shown.blackMs) }
}
private fun lose() {
client?.stop()
_uiState.update { it.copy(phase = SpectatePhase.LOST) }
}
private fun fail(failure: SpectatorClient.Failure) {
client?.stop()
_uiState.update { it.copy(phase = SpectatePhase.FAILED, failure = failure) }
}
override fun onCleared() {
client?.stop()
client = null
events.close()
super.onCleared()
}
private companion object {
const val TICK_MS = 250L
}
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M2,12C4.5,7.5 8,5.5 12,5.5C16,5.5 19.5,7.5 22,12C19.5,16.5 16,18.5 12,18.5C8,18.5 4.5,16.5 2,12Z"
android:strokeWidth="2"
android:strokeColor="#FFFFFFFF"
android:strokeLineJoin="round"
android:fillColor="#00000000" />
<path
android:pathData="M8.8,12a3.2,3.2 0,1 0,6.4 0a3.2,3.2 0,1 0,-6.4 0Z"
android:fillColor="#FFFFFFFF" />
</vector>
+22
View File
@@ -358,4 +358,26 @@
<string name="piece_rook">Turm</string>
<string name="piece_bishop">Läufer</string>
<string name="piece_knight">Springer</string>
<!-- Spectators -->
<string name="friends_in_game">Im Spiel</string>
<string name="friends_watch">Zuschauen</string>
<string name="friends_watch_count">Zuschauen · %1$d/%2$d</string>
<string name="friends_watch_full">Voll</string>
<string name="spectators_description">Zuschauer: %1$d</string>
<string name="spectate_title">Zuschauen</string>
<string name="spectate_joining">Verbinde mit der Partie…</string>
<string name="spectate_flip">Brett drehen</string>
<string name="spectate_back_to_friends">Zurück zu Freunden</string>
<string name="spectate_lost_text">Das Gerät, auf dem die Partie läuft, ist nicht mehr erreichbar.</string>
<string name="spectate_full_title">Partie ist voll</string>
<string name="spectate_full_text">Diese Partie hat bereits die maximale Zahl von %1$d Zuschauern. Versuch es später noch einmal.</string>
<string name="spectate_update_title">Update erforderlich</string>
<string name="spectate_update_this">Aktualisiere Matewave, um diese Partie anzusehen.</string>
<string name="spectate_update_host">Der Spieler, der diese Partie ausrichtet, muss Matewave aktualisieren, bevor man zuschauen kann.</string>
<string name="spectate_failed_title">Zuschauen nicht möglich</string>
<string name="spectate_no_game">Diese Partie ist nicht mehr verfügbar.</string>
<string name="spectate_unreachable">Das Gerät, auf dem die Partie läuft, ist nicht erreichbar. Achte darauf, dass du im selben WLAN bist.</string>
<string name="spectate_left_win">%1$s hat die Partie verlassen. %2$s gewinnt.</string>
<string name="spectate_interrupted">Partie unterbrochen: Die Spieler haben die Verbindung verloren.</string>
</resources>
+22
View File
@@ -357,4 +357,26 @@
<string name="piece_rook">ルーク</string>
<string name="piece_bishop">ビショップ</string>
<string name="piece_knight">ナイト</string>
<!-- Spectators -->
<string name="friends_in_game">対局中</string>
<string name="friends_watch">観戦</string>
<string name="friends_watch_count">観戦 · %1$d/%2$d</string>
<string name="friends_watch_full">満員</string>
<string name="spectators_description">観戦者: %1$d人</string>
<string name="spectate_title">観戦</string>
<string name="spectate_joining">対局に接続中…</string>
<string name="spectate_flip">盤を反転</string>
<string name="spectate_back_to_friends">フレンドに戻る</string>
<string name="spectate_lost_text">対局をホストしている端末に接続できなくなりました。</string>
<string name="spectate_full_title">満員です</string>
<string name="spectate_full_text">この対局の観戦者はすでに上限の%1$d人です。しばらくしてからもう一度お試しください。</string>
<string name="spectate_update_title">アップデートが必要です</string>
<string name="spectate_update_this">この対局を観戦するには Matewave をアップデートしてください。</string>
<string name="spectate_update_host">この対局を観戦するには、対局をホストしているプレイヤーが Matewave をアップデートする必要があります。</string>
<string name="spectate_failed_title">観戦できません</string>
<string name="spectate_no_game">この対局はもう観戦できません。</string>
<string name="spectate_unreachable">対局をホストしている端末に接続できません。同じWi-Fiネットワークに接続しているか確認してください。</string>
<string name="spectate_left_win">%1$sが対局から退出しました。%2$sの勝ち</string>
<string name="spectate_interrupted">対局が中断されました。プレイヤー間の接続が切れました。</string>
</resources>
+22
View File
@@ -360,4 +360,26 @@
<string name="piece_rook">Bokštas</string>
<string name="piece_bishop">Rikis</string>
<string name="piece_knight">Žirgas</string>
<!-- Spectators -->
<string name="friends_in_game">Žaidžia</string>
<string name="friends_watch">Stebėti</string>
<string name="friends_watch_count">Stebėti · %1$d/%2$d</string>
<string name="friends_watch_full">Pilna</string>
<string name="spectators_description">Žiūrovų: %1$d</string>
<string name="spectate_title">Partijos stebėjimas</string>
<string name="spectate_joining">Jungiamasi prie partijos…</string>
<string name="spectate_flip">Apversti lentą</string>
<string name="spectate_back_to_friends">Atgal į draugus</string>
<string name="spectate_lost_text">Įrenginio, kuriame vyksta partija, nebepavyksta pasiekti.</string>
<string name="spectate_full_title">Vietų nebėra</string>
<string name="spectate_full_text">Šią partiją jau stebi didžiausias leidžiamas žiūrovų skaičius (%1$d). Pabandykite vėliau.</string>
<string name="spectate_update_title">Reikia atnaujinti</string>
<string name="spectate_update_this">Atnaujinkite Matewave, kad galėtumėte stebėti šią partiją.</string>
<string name="spectate_update_host">Partiją rengiantis žaidėjas turi atnaujinti Matewave, kad ją būtų galima stebėti.</string>
<string name="spectate_failed_title">Šios partijos stebėti negalima</string>
<string name="spectate_no_game">Ši partija nebepasiekiama.</string>
<string name="spectate_unreachable">Nepavyksta pasiekti įrenginio, kuriame vyksta partija. Įsitikinkite, kad esate prisijungę prie to paties „Wi-Fi“ tinklo.</string>
<string name="spectate_left_win">%1$s paliko partiją. Laimėjo %2$s.</string>
<string name="spectate_interrupted">Partija nutraukta: žaidėjų ryšys nutrūko.</string>
</resources>
+22
View File
@@ -366,4 +366,26 @@
<string name="piece_rook">Ладья</string>
<string name="piece_bishop">Слон</string>
<string name="piece_knight">Конь</string>
<!-- Spectators -->
<string name="friends_in_game">В игре</string>
<string name="friends_watch">Смотреть</string>
<string name="friends_watch_count">Смотреть · %1$d/%2$d</string>
<string name="friends_watch_full">Мест нет</string>
<string name="spectators_description">Зрителей: %1$d</string>
<string name="spectate_title">Просмотр партии</string>
<string name="spectate_joining">Подключение к партии…</string>
<string name="spectate_flip">Перевернуть доску</string>
<string name="spectate_back_to_friends">Назад к друзьям</string>
<string name="spectate_lost_text">Устройство, на котором идёт партия, больше недоступно.</string>
<string name="spectate_full_title">Мест нет</string>
<string name="spectate_full_text">У этой партии уже максимум зрителей (%1$d). Попробуйте позже.</string>
<string name="spectate_update_title">Требуется обновление</string>
<string name="spectate_update_this">Обновите Matewave, чтобы смотреть эту партию.</string>
<string name="spectate_update_host">Игроку, который проводит эту партию, нужно обновить Matewave, чтобы её можно было смотреть.</string>
<string name="spectate_failed_title">Не удаётся посмотреть партию</string>
<string name="spectate_no_game">Эта партия больше недоступна.</string>
<string name="spectate_unreachable">Устройство, на котором идёт партия, недоступно. Убедитесь, что вы подключены к той же сети Wi-Fi.</string>
<string name="spectate_left_win">%1$s покинули партию. Победили %2$s.</string>
<string name="spectate_interrupted">Партия прервана: игроки потеряли связь.</string>
</resources>
+22
View File
@@ -357,4 +357,26 @@
<string name="piece_rook">车</string>
<string name="piece_bishop">象</string>
<string name="piece_knight">马</string>
<!-- Spectators -->
<string name="friends_in_game">对局中</string>
<string name="friends_watch">观战</string>
<string name="friends_watch_count">观战 · %1$d/%2$d</string>
<string name="friends_watch_full">已满</string>
<string name="spectators_description">观战人数:%1$d</string>
<string name="spectate_title">观战</string>
<string name="spectate_joining">正在加入对局…</string>
<string name="spectate_flip">翻转棋盘</string>
<string name="spectate_back_to_friends">返回好友</string>
<string name="spectate_lost_text">无法再连接到主持对局的设备。</string>
<string name="spectate_full_title">观战人数已满</string>
<string name="spectate_full_text">此对局的观战人数已达上限(%1$d 人),请稍后再试。</string>
<string name="spectate_update_title">需要更新</string>
<string name="spectate_update_this">请更新 Matewave 以观看此对局。</string>
<string name="spectate_update_host">主持此对局的玩家需要更新 Matewave 后才能观战。</string>
<string name="spectate_failed_title">无法观看此对局</string>
<string name="spectate_no_game">此对局已不可观看。</string>
<string name="spectate_unreachable">无法连接到主持对局的设备。请确认你们连接的是同一个 Wi-Fi 网络。</string>
<string name="spectate_left_win">%1$s离开了对局,%2$s获胜。</string>
<string name="spectate_interrupted">对局中断:玩家之间的连接已断开。</string>
</resources>
+22
View File
@@ -358,4 +358,26 @@
<string name="piece_rook">Rook</string>
<string name="piece_bishop">Bishop</string>
<string name="piece_knight">Knight</string>
<!-- Spectators -->
<string name="friends_in_game">In game</string>
<string name="friends_watch">Watch</string>
<string name="friends_watch_count">Watch · %1$d/%2$d</string>
<string name="friends_watch_full">Full</string>
<string name="spectators_description">Spectators: %1$d</string>
<string name="spectate_title">Watching</string>
<string name="spectate_joining">Joining the game…</string>
<string name="spectate_flip">Flip board</string>
<string name="spectate_back_to_friends">Back to Friends</string>
<string name="spectate_lost_text">The host\'s device can no longer be reached.</string>
<string name="spectate_full_title">Game is full</string>
<string name="spectate_full_text">This game already has the maximum of %1$d spectators. Try again later.</string>
<string name="spectate_update_title">Update required</string>
<string name="spectate_update_this">Update Matewave to watch this game.</string>
<string name="spectate_update_host">The player hosting this game needs to update Matewave before it can be watched.</string>
<string name="spectate_failed_title">Can\'t watch this game</string>
<string name="spectate_no_game">This game is no longer available.</string>
<string name="spectate_unreachable">The host\'s device can\'t be reached. Make sure you\'re on the same Wi-Fi network.</string>
<string name="spectate_left_win">%1$s left the game. %2$s wins.</string>
<string name="spectate_interrupted">Game interrupted: the players lost their connection.</string>
</resources>
@@ -18,6 +18,7 @@ class GameMessageTest {
@Test fun signed() = roundTrip(GameMessage.SignedMsg("abc", "tag", 7))
@Test fun rematch() = roundTrip(GameMessage.RematchMsg("accept", "g1", "g2"))
@Test fun images() = roundTrip(GameMessage.ProfileImagesMsg("a", null, "g1"))
@Test fun spectatorCount() = roundTrip(GameMessage.SpectatorCountMsg(7, "g1"))
@Test
fun profileCarriesGameIdAndVersion() {