mirror of
https://github.com/kalarina-bit/Matewave.git
synced 2026-11-22 08:06:09 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6137923ca1 | ||
|
|
f59e461405 | ||
|
|
fb58dfb4ae | ||
|
|
2d0e605dfa | ||
|
|
0eb407ead5 |
@@ -28,12 +28,16 @@
|
|||||||
<img src="assets/screenshots/2-keep-growing.png" width="160" alt="Keep growing">
|
<img src="assets/screenshots/2-keep-growing.png" width="160" alt="Keep growing">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> If you find Matewave useful, please consider giving it a ⭐ — it helps others discover the project.
|
||||||
|
|
||||||
## ✨ Features
|
## ✨ Features
|
||||||
|
|
||||||
- 🤖 **AI opponent** with adjustable difficulty
|
- 🤖 **AI opponent** with adjustable difficulty
|
||||||
- 🧩 **Puzzles** and tactical training
|
- 🧩 **Puzzles** and tactical training
|
||||||
- 📖 **Opening trainer** — learn and practice opening lines and their variations
|
- 📖 **Opening trainer** — learn and practice opening lines and their variations
|
||||||
- 📶 **Local multiplayer** over Bluetooth or Wi-Fi/LAN, with nearby player discovery
|
- 📶 **Local multiplayer** over Bluetooth or Wi-Fi/LAN, with nearby player discovery
|
||||||
|
- 👀 **Watch friends play** — up to 20 spectators on the same Wi-Fi can follow a live LAN game
|
||||||
- 📲 **Share the app** with a nearby friend via QR code over the local network
|
- 📲 **Share the app** with a nearby friend via QR code over the local network
|
||||||
- 🎷 **Optional jazz radio**
|
- 🎷 **Optional jazz radio**
|
||||||
- 🌙 **Dark theme**
|
- 🌙 **Dark theme**
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ android {
|
|||||||
applicationId = "cc.skysparkle.matewave"
|
applicationId = "cc.skysparkle.matewave"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 3
|
versionCode = 4
|
||||||
versionName = "1.0.45"
|
versionName = "1.0.46"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import androidx.activity.compose.setContent
|
|||||||
import cc.skysparkle.matewave.audio.SoundManager
|
import cc.skysparkle.matewave.audio.SoundManager
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
import androidx.navigation.compose.composable
|
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.
|
// Presence is shared with the background service, so the lists stay the same in both.
|
||||||
val presence = remember { PresenceHub.get(context) }
|
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) {
|
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||||
if (cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled) {
|
if (cc.skysparkle.matewave.presence.PresenceSettings(context).backgroundEnabled) {
|
||||||
cc.skysparkle.matewave.presence.PresenceService.start(context)
|
cc.skysparkle.matewave.presence.PresenceService.start(context)
|
||||||
@@ -231,6 +237,10 @@ private fun AppNavHost() {
|
|||||||
FriendsScreen(
|
FriendsScreen(
|
||||||
presence = presence,
|
presence = presence,
|
||||||
onPlay = { navController.navigate("connectionNearby") },
|
onPlay = { navController.navigate("connectionNearby") },
|
||||||
|
onWatch = { target ->
|
||||||
|
spectateTarget = target
|
||||||
|
navController.navigate("spectate")
|
||||||
|
},
|
||||||
onHomeClick = { navController.popBackStack("menu", inclusive = false) },
|
onHomeClick = { navController.popBackStack("menu", inclusive = false) },
|
||||||
onSettingsClick = {
|
onSettingsClick = {
|
||||||
navController.popBackStack("menu", inclusive = false)
|
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") {
|
composable("vsAiSetup") {
|
||||||
VsAiSetupScreen(
|
VsAiSetupScreen(
|
||||||
onBack = { navController.popBackStack() },
|
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 val TAB_ROUTES = setOf("menu", "friends", "settings", "account")
|
||||||
|
|
||||||
private fun isTabSwitch(from: String?, to: String?): Boolean =
|
private fun isTabSwitch(from: String?, to: String?): Boolean =
|
||||||
|
|||||||
@@ -67,6 +67,9 @@ sealed class GameMessage {
|
|||||||
val newGameId: String = ""
|
val newGameId: String = ""
|
||||||
) : GameMessage()
|
) : 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 {
|
fun toJson(): String {
|
||||||
val o = JSONObject()
|
val o = JSONObject()
|
||||||
when (this) {
|
when (this) {
|
||||||
@@ -99,6 +102,7 @@ sealed class GameMessage {
|
|||||||
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
|
o.put("type", "rematch"); o.put("action", action); o.put("gameId", gameId)
|
||||||
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
|
if (newGameId.isNotEmpty()) o.put("newGameId", newGameId)
|
||||||
}
|
}
|
||||||
|
is SpectatorCountMsg -> { o.put("type", "spectators"); o.put("n", count); o.put("gameId", gameId) }
|
||||||
is ProfileMsg -> {
|
is ProfileMsg -> {
|
||||||
o.put("type", "profile")
|
o.put("type", "profile")
|
||||||
o.put("userId", userId)
|
o.put("userId", userId)
|
||||||
@@ -154,6 +158,7 @@ sealed class GameMessage {
|
|||||||
o.optString("gameId", ""),
|
o.optString("gameId", ""),
|
||||||
o.optString("newGameId", "")
|
o.optString("newGameId", "")
|
||||||
)
|
)
|
||||||
|
"spectators" -> SpectatorCountMsg(o.getInt("n"), o.optString("gameId", ""))
|
||||||
"profile" -> ProfileMsg(
|
"profile" -> ProfileMsg(
|
||||||
|
|
||||||
userId = o.optString("userId", "").ifBlank { o.getString("name") },
|
userId = o.optString("userId", "").ifBlank { o.getString("name") },
|
||||||
|
|||||||
@@ -30,7 +30,11 @@ data class LanPeer(
|
|||||||
|
|
||||||
val signature: String = "",
|
val signature: String = "",
|
||||||
/** Raw NSD service name, used to remove the peer when the service is lost. */
|
/** 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"
|
val id: String get() = "$host:$port"
|
||||||
}
|
}
|
||||||
@@ -224,6 +228,7 @@ class LanTransport(
|
|||||||
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
cc.skysparkle.matewave.security.DeviceKeys.sign(
|
||||||
context, presencePayload(profile.userId, shownName, profile.elo)
|
context, presencePayload(profile.userId, shownName, profile.elo)
|
||||||
)?.let { setAttribute("sig", it) }
|
)?.let { setAttribute("sig", it) }
|
||||||
|
cc.skysparkle.matewave.spectate.SpectatorAdvert.attributes().forEach { (key, value) -> setAttribute(key, value) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val listener = object : NsdManager.RegistrationListener {
|
val listener = object : NsdManager.RegistrationListener {
|
||||||
@@ -353,6 +358,7 @@ class LanTransport(
|
|||||||
fun attr(key: String): String = runCatching {
|
fun attr(key: String): String = runCatching {
|
||||||
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
|
info.attributes[key]?.toString(Charsets.UTF_8) ?: ""
|
||||||
}.getOrDefault("")
|
}.getOrDefault("")
|
||||||
|
val game = cc.skysparkle.matewave.spectate.SpectatorAdvert.parse(::attr)
|
||||||
return LanPeer(
|
return LanPeer(
|
||||||
name = displayNameOf(info.serviceName),
|
name = displayNameOf(info.serviceName),
|
||||||
host = host,
|
host = host,
|
||||||
@@ -363,7 +369,9 @@ class LanTransport(
|
|||||||
|
|
||||||
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
fingerprint = attr("fp").ifEmpty { fingerprintFromServiceName(info.serviceName ?: "") ?: "" },
|
||||||
signature = attr("sig"),
|
signature = attr("sig"),
|
||||||
serviceName = info.serviceName ?: ""
|
serviceName = info.serviceName ?: "",
|
||||||
|
gameTag = game.gameTag,
|
||||||
|
spectatePort = game.spectatePort
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -517,7 +525,7 @@ class LanTransport(
|
|||||||
try {
|
try {
|
||||||
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
|
val reader = BufferedReader(InputStreamReader(sock.getInputStream(), Charsets.UTF_8))
|
||||||
while (true) {
|
while (true) {
|
||||||
val read = readBoundedLine(reader)
|
val read = readBoundedLine(reader, MAX_MESSAGE_CHARS)
|
||||||
if (read is LineResult.EndOfStream) break
|
if (read is LineResult.EndOfStream) break
|
||||||
if (sock !== socket) break
|
if (sock !== socket) break
|
||||||
if (read is LineResult.TooLong) {
|
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) {
|
override fun send(message: GameMessage) {
|
||||||
val json = message.toJson()
|
val json = message.toJson()
|
||||||
val size = json.length
|
val size = json.length
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package cc.skysparkle.matewave.network
|
||||||
|
|
||||||
|
import java.io.Reader
|
||||||
|
|
||||||
|
/** Result of reading one newline-delimited message from a socket. */
|
||||||
|
sealed class LineResult {
|
||||||
|
data class Line(val text: String) : LineResult()
|
||||||
|
object TooLong : LineResult()
|
||||||
|
object EndOfStream : LineResult()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads one line of at most [maxChars] characters; longer lines are reported, not buffered. */
|
||||||
|
fun readBoundedLine(reader: Reader, maxChars: Int): 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 >= maxChars) return LineResult.TooLong
|
||||||
|
builder.append(ch.toChar())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,10 @@ data class DiscoveredPeer(
|
|||||||
val elo: Int,
|
val elo: Int,
|
||||||
val fingerprint: String,
|
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 },
|
name = peer.displayName.ifEmpty { peer.name },
|
||||||
elo = peer.elo,
|
elo = peer.elo,
|
||||||
fingerprint = peer.fingerprint,
|
fingerprint = peer.fingerprint,
|
||||||
address = peer.id
|
address = peer.id,
|
||||||
|
host = peer.host,
|
||||||
|
gameTag = peer.gameTag,
|
||||||
|
spectatePort = peer.spectatePort
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
_peers.value = result
|
_peers.value = result
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
enum class PresenceStatus { ONLINE, IN_GAME, OFFLINE }
|
||||||
|
|
||||||
|
/** Where to watch a game: the host's address and spectator port. */
|
||||||
|
data class SpectateTarget(val host: String, val port: Int, val gameTag: String)
|
||||||
|
|
||||||
|
/** A player seen on the network, reduced to what spectating needs. */
|
||||||
|
data class NearbyPlayerGame(
|
||||||
|
val playerId: String,
|
||||||
|
val host: String,
|
||||||
|
val gameTag: String,
|
||||||
|
val spectatePort: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
data class FriendGameStatus(
|
||||||
|
val status: PresenceStatus,
|
||||||
|
val target: SpectateTarget? = null,
|
||||||
|
/** Live count from the host, null until it has answered. */
|
||||||
|
val spectators: Int? = null,
|
||||||
|
val max: Int = MAX_SPECTATORS
|
||||||
|
) {
|
||||||
|
val full: Boolean get() = spectators != null && spectators >= max
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Online, In game or Offline for one player, and where to watch. Both players of a game announce
|
||||||
|
* the same tag, but only the host serves spectators, so the guest's game is watched through the
|
||||||
|
* host. A host that says its game has ended overrides an announcement that is not updated yet.
|
||||||
|
*/
|
||||||
|
object FriendStatusResolver {
|
||||||
|
fun resolve(
|
||||||
|
playerId: String,
|
||||||
|
nearby: Map<String, NearbyPlayerGame>,
|
||||||
|
probes: Map<SpectateTarget, SpectatorMessage.Status>
|
||||||
|
): FriendGameStatus {
|
||||||
|
val player = nearby[playerId] ?: return FriendGameStatus(PresenceStatus.OFFLINE)
|
||||||
|
if (player.gameTag.isEmpty()) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||||
|
val host = hostOf(player, nearby) ?: return FriendGameStatus(PresenceStatus.IN_GAME)
|
||||||
|
val target = SpectateTarget(host.host, host.spectatePort, host.gameTag)
|
||||||
|
val probe = probes[target]
|
||||||
|
if (probe != null && !probe.inGame) return FriendGameStatus(PresenceStatus.ONLINE)
|
||||||
|
return FriendGameStatus(PresenceStatus.IN_GAME, target, probe?.count, probe?.max ?: MAX_SPECTATORS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every host worth asking for a live spectator count. */
|
||||||
|
fun targets(nearby: Collection<NearbyPlayerGame>): Set<SpectateTarget> =
|
||||||
|
nearby.filter { it.gameTag.isNotEmpty() && it.spectatePort > 0 && it.host.isNotEmpty() }
|
||||||
|
.map { SpectateTarget(it.host, it.spectatePort, it.gameTag) }
|
||||||
|
.toSet()
|
||||||
|
|
||||||
|
private fun hostOf(player: NearbyPlayerGame, nearby: Map<String, NearbyPlayerGame>): NearbyPlayerGame? {
|
||||||
|
if (player.spectatePort > 0 && player.host.isNotEmpty()) return player
|
||||||
|
return nearby.values.firstOrNull {
|
||||||
|
it.playerId != player.playerId && it.gameTag == player.gameTag && it.spectatePort > 0 && it.host.isNotEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* ignore these attributes.
|
||||||
|
*/
|
||||||
|
object SpectatorAdvert {
|
||||||
|
const val KEY_GAME = "g"
|
||||||
|
const val KEY_PORT = "sp"
|
||||||
|
|
||||||
|
data class State(val gameTag: String = "", val spectatePort: Int = 0)
|
||||||
|
|
||||||
|
@Volatile var current = State()
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** Returns true when the announcement has to be published again. */
|
||||||
|
@Synchronized
|
||||||
|
fun update(state: State): Boolean {
|
||||||
|
if (state == current) return false
|
||||||
|
current = state
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear(): Boolean = update(State())
|
||||||
|
|
||||||
|
fun attributes(state: State = current): Map<String, String> = buildMap {
|
||||||
|
if (state.gameTag.isNotEmpty()) put(KEY_GAME, state.gameTag)
|
||||||
|
if (state.gameTag.isNotEmpty() && state.spectatePort > 0) put(KEY_PORT, state.spectatePort.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads the attributes of a discovered player; anything malformed counts as absent. */
|
||||||
|
fun parse(attribute: (String) -> String): State {
|
||||||
|
val tag = attribute(KEY_GAME).takeIf { TAG_PATTERN.matches(it) } ?: return State()
|
||||||
|
val port = attribute(KEY_PORT).toIntOrNull()?.takeIf { it in 1..65_535 } ?: 0
|
||||||
|
return State(tag, port)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Short tag of a game id, so the game id itself is not announced. */
|
||||||
|
fun tagOf(gameId: String): String {
|
||||||
|
if (gameId.isEmpty()) return ""
|
||||||
|
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8))
|
||||||
|
return digest.take(4).joinToString("") { "%02x".format(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private val TAG_PATTERN = Regex("^[0-9a-f]{8}$")
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.network.LineResult
|
||||||
|
import cc.skysparkle.matewave.network.readBoundedLine
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.RejectedExecutionException
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One spectator's connection to a hosted game. Events arrive on a background thread, in order.
|
||||||
|
* Silence longer than [Timing.silenceTimeoutMs] (the host pings every few seconds) means the host
|
||||||
|
* is gone, which also covers Wi-Fi switching off on either side.
|
||||||
|
*/
|
||||||
|
class SpectatorClient(
|
||||||
|
private val host: String,
|
||||||
|
private val port: Int,
|
||||||
|
private val onEvent: (Event) -> Unit,
|
||||||
|
private val timing: Timing = Timing(),
|
||||||
|
private val version: Int = SpectatorProtocol.VERSION,
|
||||||
|
private val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||||
|
) {
|
||||||
|
data class Timing(val connectTimeoutMs: Int = 5_000, val silenceTimeoutMs: Int = 15_000)
|
||||||
|
|
||||||
|
enum class Failure { UNREACHABLE, FULL, NO_GAME, UPDATE_THIS_APP, UPDATE_HOST_APP }
|
||||||
|
|
||||||
|
sealed class Event {
|
||||||
|
data class Joined(val welcome: SpectatorMessage.Welcome) : Event()
|
||||||
|
data class Received(val message: SpectatorMessage) : Event()
|
||||||
|
data class JoinFailed(val failure: Failure) : Event()
|
||||||
|
|
||||||
|
/** The connection ended after joining; [hostClosed] is true when the host said goodbye. */
|
||||||
|
data class Disconnected(val hostClosed: Boolean) : Event()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile private var socket: Socket? = null
|
||||||
|
@Volatile private var output: BufferedWriter? = null
|
||||||
|
@Volatile private var stopped = false
|
||||||
|
private val writer = Executors.newSingleThreadExecutor { r ->
|
||||||
|
Thread(r, "spectator-send").apply { isDaemon = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
Thread({ run() }, "spectator-receive").apply { isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestResync() = send(SpectatorMessage.Resync)
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
if (stopped) return
|
||||||
|
stopped = true
|
||||||
|
try {
|
||||||
|
writer.execute {
|
||||||
|
writeLine(SpectatorMessage.Leave)
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
writer.shutdown()
|
||||||
|
// A send stuck on a dead connection must not keep the socket open.
|
||||||
|
Thread({
|
||||||
|
try { Thread.sleep(STOP_GRACE_MS) } catch (_: InterruptedException) {}
|
||||||
|
closeSocket()
|
||||||
|
}, "spectator-stop").apply { isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun run() {
|
||||||
|
val s = Socket()
|
||||||
|
socket = s
|
||||||
|
val reader: BufferedReader
|
||||||
|
try {
|
||||||
|
if (stopped) throw IOException("Stopped")
|
||||||
|
s.tcpNoDelay = true
|
||||||
|
s.connect(InetSocketAddress(host, port), timing.connectTimeoutMs)
|
||||||
|
s.soTimeout = timing.silenceTimeoutMs
|
||||||
|
output = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
} catch (e: IOException) {
|
||||||
|
closeSocket()
|
||||||
|
emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
send(SpectatorMessage.Hello(minVersion))
|
||||||
|
|
||||||
|
var joined = false
|
||||||
|
var hostClosed = false
|
||||||
|
try {
|
||||||
|
while (!stopped) {
|
||||||
|
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||||
|
if (read !is LineResult.Line) break
|
||||||
|
val envelope = SpectatorProtocol.decode(read.text) ?: continue
|
||||||
|
val message = envelope.message
|
||||||
|
if (!joined) {
|
||||||
|
// reject keeps its shape across versions, so read it before the version gate.
|
||||||
|
if (message is SpectatorMessage.Reject) {
|
||||||
|
emit(Event.JoinFailed(failureOf(message)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (envelope.version < minVersion) {
|
||||||
|
emit(Event.JoinFailed(Failure.UPDATE_HOST_APP))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (message is SpectatorMessage.Welcome) {
|
||||||
|
joined = true
|
||||||
|
emit(Event.Joined(message))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
when (message) {
|
||||||
|
null -> Unit
|
||||||
|
SpectatorMessage.Closing -> hostClosed = true
|
||||||
|
is SpectatorMessage.Ping -> {
|
||||||
|
send(SpectatorMessage.Pong)
|
||||||
|
emit(Event.Received(message))
|
||||||
|
}
|
||||||
|
else -> emit(Event.Received(message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Silence timeout or connection reset.
|
||||||
|
} finally {
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
if (joined) emit(Event.Disconnected(hostClosed)) else emit(Event.JoinFailed(Failure.UNREACHABLE))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failureOf(reject: SpectatorMessage.Reject): Failure = when (reject.reason) {
|
||||||
|
RejectReason.FULL -> Failure.FULL
|
||||||
|
RejectReason.NO_GAME -> Failure.NO_GAME
|
||||||
|
RejectReason.UPDATE_REQUIRED ->
|
||||||
|
if (version < reject.minVersion) Failure.UPDATE_THIS_APP else Failure.UPDATE_HOST_APP
|
||||||
|
RejectReason.OTHER -> Failure.UNREACHABLE
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun emit(event: Event) {
|
||||||
|
if (!stopped) onEvent(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun send(message: SpectatorMessage) {
|
||||||
|
try {
|
||||||
|
writer.execute { writeLine(message) }
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
// Stopped.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeLine(message: SpectatorMessage) {
|
||||||
|
val out = output ?: return
|
||||||
|
try {
|
||||||
|
out.write(SpectatorProtocol.encode(message, version))
|
||||||
|
out.write("\n")
|
||||||
|
out.flush()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
closeSocket()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeSocket() {
|
||||||
|
try { socket?.close() } catch (_: IOException) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val STOP_GRACE_MS = 500L
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One-shot status query, used to show live spectator counts in the Friends list. */
|
||||||
|
object SpectatorProbe {
|
||||||
|
fun query(host: String, port: Int, timeoutMs: Int = 2_000): SpectatorMessage.Status? = try {
|
||||||
|
Socket().use { s ->
|
||||||
|
s.connect(InetSocketAddress(host, port), timeoutMs)
|
||||||
|
s.soTimeout = timeoutMs
|
||||||
|
val out = s.getOutputStream()
|
||||||
|
out.write((SpectatorProtocol.encode(SpectatorMessage.StatusQuery) + "\n").toByteArray(Charsets.UTF_8))
|
||||||
|
out.flush()
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||||
|
(read as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text)?.message as? SpectatorMessage.Status }
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.Board
|
||||||
|
import cc.skysparkle.matewave.engine.ChessEngine
|
||||||
|
import cc.skysparkle.matewave.engine.GameStatus
|
||||||
|
import cc.skysparkle.matewave.engine.Move
|
||||||
|
import cc.skysparkle.matewave.engine.Notation
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.opposite
|
||||||
|
|
||||||
|
/** What a spectator sees of a game. */
|
||||||
|
data class SpectatorView(
|
||||||
|
val gameId: String,
|
||||||
|
val white: SpectatorPlayer,
|
||||||
|
val black: SpectatorPlayer,
|
||||||
|
val startBoard: Board,
|
||||||
|
val board: Board,
|
||||||
|
val movesUci: List<String>,
|
||||||
|
val moveSans: List<String>,
|
||||||
|
val lastMove: Move?,
|
||||||
|
val initialSeconds: Int,
|
||||||
|
val incrementSeconds: Int,
|
||||||
|
val clock: SpectatorClock?,
|
||||||
|
val result: SpectatorResult?
|
||||||
|
) {
|
||||||
|
val ply: Int get() = movesUci.size
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The spectator's copy of the game, rebuilt from a snapshot and moved forward by live moves. Moves
|
||||||
|
* are checked against the rules; anything that does not follow on asks for a fresh snapshot.
|
||||||
|
*/
|
||||||
|
class SpectatorGame {
|
||||||
|
enum class Applied { APPLIED, IGNORED, NEEDS_RESYNC }
|
||||||
|
|
||||||
|
var view: SpectatorView? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
fun load(snapshot: SpectatorSnapshot): Boolean {
|
||||||
|
val start = Board.startPosition()
|
||||||
|
var board = start
|
||||||
|
val sans = ArrayList<String>(snapshot.movesUci.size)
|
||||||
|
var last: Move? = null
|
||||||
|
for (uci in snapshot.movesUci) {
|
||||||
|
val move = resolve(board, uci) ?: return false
|
||||||
|
sans.add(Notation.toSan(board, move))
|
||||||
|
board = ChessEngine.applyMove(board, move)
|
||||||
|
last = move
|
||||||
|
}
|
||||||
|
view = SpectatorView(
|
||||||
|
gameId = snapshot.gameId,
|
||||||
|
white = snapshot.white,
|
||||||
|
black = snapshot.black,
|
||||||
|
startBoard = start,
|
||||||
|
board = board,
|
||||||
|
movesUci = snapshot.movesUci,
|
||||||
|
moveSans = sans,
|
||||||
|
lastMove = last,
|
||||||
|
initialSeconds = snapshot.initialSeconds,
|
||||||
|
incrementSeconds = snapshot.incrementSeconds,
|
||||||
|
clock = snapshot.clock,
|
||||||
|
result = snapshot.result
|
||||||
|
)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onMove(message: SpectatorMessage.MovePlayed): Applied {
|
||||||
|
val current = view ?: 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 (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC
|
||||||
|
val move = resolve(current.board, message.uci) ?: return Applied.NEEDS_RESYNC
|
||||||
|
view = current.copy(
|
||||||
|
board = ChessEngine.applyMove(current.board, move),
|
||||||
|
movesUci = current.movesUci + move.toUci(),
|
||||||
|
moveSans = current.moveSans + Notation.toSan(current.board, move),
|
||||||
|
lastMove = move,
|
||||||
|
clock = message.clock ?: current.clock
|
||||||
|
)
|
||||||
|
return Applied.APPLIED
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onGameOver(message: SpectatorMessage.GameOver): Applied {
|
||||||
|
val current = view ?: return Applied.NEEDS_RESYNC
|
||||||
|
if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC
|
||||||
|
view = current.copy(
|
||||||
|
result = message.result,
|
||||||
|
clock = (message.clock ?: current.clock)?.copy(running = null)
|
||||||
|
)
|
||||||
|
return Applied.APPLIED
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onClock(clock: SpectatorClock?) {
|
||||||
|
val current = view ?: return
|
||||||
|
if (clock == null || current.result != null) return
|
||||||
|
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. */
|
||||||
|
object SpectatorDiff {
|
||||||
|
fun between(old: SpectatorSnapshot?, new: SpectatorSnapshot): List<SpectatorMessage> {
|
||||||
|
if (old == null) return emptyList()
|
||||||
|
if (old.gameId != new.gameId || old.white != new.white || old.black != new.black) {
|
||||||
|
return listOf(SpectatorMessage.NewGame(new))
|
||||||
|
}
|
||||||
|
val events = ArrayList<SpectatorMessage>()
|
||||||
|
val before = old.movesUci
|
||||||
|
val after = new.movesUci
|
||||||
|
if (after != before) {
|
||||||
|
if (after.size <= before.size || after.subList(0, before.size) != before) {
|
||||||
|
return listOf(SpectatorMessage.NewGame(new))
|
||||||
|
}
|
||||||
|
for (i in before.size until after.size) {
|
||||||
|
val isLast = i == after.lastIndex
|
||||||
|
events += SpectatorMessage.MovePlayed(new.gameId, i + 1, after[i], if (isLast) new.clock else null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
old.result == null && new.result != null -> events += SpectatorMessage.GameOver(new.gameId, new.result, new.clock)
|
||||||
|
old.result != null && new.result != old.result -> return listOf(SpectatorMessage.NewGame(new))
|
||||||
|
}
|
||||||
|
return events
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Result of a finished game as spectators are told it. */
|
||||||
|
object SpectatorResults {
|
||||||
|
fun of(
|
||||||
|
status: GameStatus,
|
||||||
|
sideToMove: PieceColor,
|
||||||
|
timedOutSide: PieceColor?,
|
||||||
|
resignedSide: PieceColor?,
|
||||||
|
leftMidGame: Boolean
|
||||||
|
): SpectatorResult? = when (status) {
|
||||||
|
GameStatus.ONGOING -> null
|
||||||
|
GameStatus.CHECKMATE -> SpectatorResult(SpectatorOutcome.CHECKMATE, sideToMove.opposite())
|
||||||
|
GameStatus.STALEMATE -> SpectatorResult(SpectatorOutcome.STALEMATE, null)
|
||||||
|
GameStatus.DRAW_50_MOVES -> SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null)
|
||||||
|
GameStatus.DRAW_REPETITION -> SpectatorResult(SpectatorOutcome.REPETITION, null)
|
||||||
|
GameStatus.DRAW_MATERIAL -> SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null)
|
||||||
|
GameStatus.TIMEOUT -> SpectatorResult(SpectatorOutcome.TIMEOUT, timedOutSide?.opposite())
|
||||||
|
GameStatus.TIMEOUT_DRAW -> SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null)
|
||||||
|
GameStatus.RESIGNATION -> SpectatorResult(
|
||||||
|
if (leftMidGame) SpectatorOutcome.LEFT else SpectatorOutcome.RESIGNATION,
|
||||||
|
resignedSide?.opposite()
|
||||||
|
)
|
||||||
|
GameStatus.DRAW_AGREEMENT -> SpectatorResult(SpectatorOutcome.AGREEMENT, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun leftBy(side: PieceColor) = SpectatorResult(SpectatorOutcome.LEFT, side.opposite())
|
||||||
|
|
||||||
|
val interrupted = SpectatorResult(SpectatorOutcome.INTERRUPTED, null)
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.network.LineResult
|
||||||
|
import cc.skysparkle.matewave.network.readBoundedLine
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.Closeable
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.ServerSocket
|
||||||
|
import java.net.Socket
|
||||||
|
import java.net.SocketTimeoutException
|
||||||
|
import java.util.concurrent.ArrayBlockingQueue
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import java.util.concurrent.RejectedExecutionException
|
||||||
|
import java.util.concurrent.ThreadFactory
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs on the host player's device and streams the game to up to [maxSpectators] spectators on
|
||||||
|
* its own listening socket; the players' connection is never touched. Each spectator gets its own
|
||||||
|
* bounded queue and writer thread, so a slow or vanished spectator is dropped without delaying
|
||||||
|
* the game or anyone else. Spectators can only listen: anything they send besides keepalives and
|
||||||
|
* resync requests is ignored.
|
||||||
|
*/
|
||||||
|
class SpectatorHub(
|
||||||
|
private val maxSpectators: Int = MAX_SPECTATORS,
|
||||||
|
private val timing: Timing = Timing(),
|
||||||
|
private val log: (String) -> Unit = {}
|
||||||
|
) {
|
||||||
|
data class Timing(
|
||||||
|
val helloTimeoutMs: Int = 5_000,
|
||||||
|
val pingIntervalMs: Long = 5_000,
|
||||||
|
/** A spectator that answers no ping for this long is gone (e.g. its Wi-Fi went off). */
|
||||||
|
val silenceTimeoutMs: Int = 20_000,
|
||||||
|
val queueCapacity: Int = 512
|
||||||
|
)
|
||||||
|
|
||||||
|
private val lock = Any()
|
||||||
|
private val spectators = LinkedHashSet<Spectator>()
|
||||||
|
private var latest: SpectatorSnapshot? = null
|
||||||
|
private var latestAtNanos = 0L
|
||||||
|
private var closed = false
|
||||||
|
private var server: ServerSocket? = null
|
||||||
|
private val handshaking = AtomicInteger()
|
||||||
|
|
||||||
|
private val threads = Executors.newCachedThreadPool(daemonThreads("spectator"))
|
||||||
|
private val ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("spectator-ping"))
|
||||||
|
|
||||||
|
private val _count = MutableStateFlow(0)
|
||||||
|
val count: StateFlow<Int> = _count
|
||||||
|
|
||||||
|
val port: Int get() = server?.localPort ?: 0
|
||||||
|
|
||||||
|
/** Opens the spectator socket on [bindAddress] (all interfaces by default) and returns its port. */
|
||||||
|
fun start(bindAddress: InetAddress? = null): Int {
|
||||||
|
val socket = synchronized(lock) {
|
||||||
|
check(!closed) { "Hub is closed" }
|
||||||
|
server?.let { return it.localPort }
|
||||||
|
ServerSocket().also {
|
||||||
|
it.reuseAddress = true
|
||||||
|
it.bind(InetSocketAddress(bindAddress, 0))
|
||||||
|
server = it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
threads.execute { acceptLoop(socket) }
|
||||||
|
ticker.scheduleAtFixedRate(
|
||||||
|
{ runCatching { sendPings() } },
|
||||||
|
timing.pingIntervalMs, timing.pingIntervalMs, TimeUnit.MILLISECONDS
|
||||||
|
)
|
||||||
|
return socket.localPort
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces the current game state and sends [events] to every spectator, atomically. */
|
||||||
|
fun publish(snapshot: SpectatorSnapshot, events: List<SpectatorMessage> = emptyList()) {
|
||||||
|
synchronized(lock) {
|
||||||
|
if (closed) return
|
||||||
|
latest = snapshot
|
||||||
|
latestAtNanos = System.nanoTime()
|
||||||
|
if (events.isEmpty() || spectators.isEmpty()) return
|
||||||
|
val targets = spectators.toList()
|
||||||
|
events.forEach { deliver(targets, SpectatorProtocol.encode(it)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sends [finalEvents] and a goodbye to everyone, then stops accepting and closes. */
|
||||||
|
fun close(finalEvents: List<SpectatorMessage> = emptyList()) {
|
||||||
|
val targets = synchronized(lock) {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
spectators.toList().also { spectators.clear() }
|
||||||
|
}
|
||||||
|
_count.value = 0
|
||||||
|
val lines = finalEvents.map { SpectatorProtocol.encode(it) } + SpectatorProtocol.encode(SpectatorMessage.Closing)
|
||||||
|
targets.forEach { spectator ->
|
||||||
|
lines.forEach { spectator.offer(it) }
|
||||||
|
spectator.finish()
|
||||||
|
}
|
||||||
|
closeQuietly(server)
|
||||||
|
ticker.shutdownNow()
|
||||||
|
threads.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun acceptLoop(socket: ServerSocket) {
|
||||||
|
while (!socket.isClosed) {
|
||||||
|
val client = try {
|
||||||
|
socket.accept()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
if (socket.isClosed) return
|
||||||
|
log("Spectator accept failed: ${e.message}")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (handshaking.incrementAndGet() > MAX_HANDSHAKING) {
|
||||||
|
handshaking.decrementAndGet()
|
||||||
|
closeQuietly(client)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
threads.execute { serve(client) }
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
handshaking.decrementAndGet()
|
||||||
|
closeQuietly(client)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun serve(client: Socket) {
|
||||||
|
var spectator: Spectator? = null
|
||||||
|
var reader: BufferedReader? = null
|
||||||
|
try {
|
||||||
|
client.tcpNoDelay = true
|
||||||
|
client.soTimeout = timing.helloTimeoutMs
|
||||||
|
reader = BufferedReader(InputStreamReader(client.getInputStream(), Charsets.UTF_8))
|
||||||
|
val first = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||||
|
val envelope = (first as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text) }
|
||||||
|
when (envelope?.message) {
|
||||||
|
SpectatorMessage.StatusQuery -> reply(client, status())
|
||||||
|
is SpectatorMessage.Hello -> {
|
||||||
|
if (envelope.version < SpectatorProtocol.MIN_COMPATIBLE_VERSION) {
|
||||||
|
log("Spectator with protocol ${envelope.version} told to update")
|
||||||
|
reply(client, SpectatorMessage.Reject(RejectReason.UPDATE_REQUIRED, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||||
|
} else {
|
||||||
|
spectator = admit(client)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Timed out or closed before saying hello.
|
||||||
|
} finally {
|
||||||
|
handshaking.decrementAndGet()
|
||||||
|
if (spectator == null) closeQuietly(client)
|
||||||
|
}
|
||||||
|
val admitted = spectator ?: return
|
||||||
|
listen(admitted, reader ?: return)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun admit(client: Socket): Spectator? {
|
||||||
|
var reject: RejectReason? = null
|
||||||
|
var spectator: Spectator? = null
|
||||||
|
synchronized(lock) {
|
||||||
|
val game = latest
|
||||||
|
when {
|
||||||
|
closed || game == null -> reject = RejectReason.NO_GAME
|
||||||
|
spectators.size >= maxSpectators -> reject = RejectReason.FULL
|
||||||
|
else -> {
|
||||||
|
val joined = Spectator(client, timing.queueCapacity)
|
||||||
|
val others = spectators.toList()
|
||||||
|
spectators.add(joined)
|
||||||
|
val n = spectators.size
|
||||||
|
_count.value = n
|
||||||
|
joined.offer(SpectatorProtocol.encode(SpectatorMessage.Welcome(n, maxSpectators, liveSnapshot(game))))
|
||||||
|
deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(n, maxSpectators)))
|
||||||
|
spectator = joined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reject?.let {
|
||||||
|
reply(client, SpectatorMessage.Reject(it, SpectatorProtocol.MIN_COMPATIBLE_VERSION))
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val joined = spectator ?: return null
|
||||||
|
try {
|
||||||
|
threads.execute { write(joined) }
|
||||||
|
} catch (e: RejectedExecutionException) {
|
||||||
|
drop(joined)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return joined
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun listen(spectator: Spectator, reader: BufferedReader) {
|
||||||
|
try {
|
||||||
|
spectator.socket.soTimeout = timing.silenceTimeoutMs
|
||||||
|
while (true) {
|
||||||
|
val read = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS)
|
||||||
|
if (read !is LineResult.Line) break
|
||||||
|
when (SpectatorProtocol.decode(read.text)?.message) {
|
||||||
|
SpectatorMessage.Resync -> synchronized(lock) {
|
||||||
|
val game = latest
|
||||||
|
if (game != null && !closed) {
|
||||||
|
deliver(listOf(spectator), SpectatorProtocol.encode(SpectatorMessage.NewGame(liveSnapshot(game))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SpectatorMessage.Leave -> break
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: SocketTimeoutException) {
|
||||||
|
log("Spectator silent for ${timing.silenceTimeoutMs / 1000} s, dropped")
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Connection reset.
|
||||||
|
} finally {
|
||||||
|
drop(spectator)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun write(spectator: Spectator) {
|
||||||
|
try {
|
||||||
|
val out = BufferedWriter(OutputStreamWriter(spectator.socket.getOutputStream(), Charsets.UTF_8))
|
||||||
|
while (true) {
|
||||||
|
val item = spectator.queue.take()
|
||||||
|
if (item === POISON) break
|
||||||
|
out.write(item as String)
|
||||||
|
out.write("\n")
|
||||||
|
if (spectator.queue.isEmpty()) out.flush()
|
||||||
|
}
|
||||||
|
out.flush()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Spectator went away.
|
||||||
|
} catch (e: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
} finally {
|
||||||
|
drop(spectator)
|
||||||
|
closeQuietly(spectator.socket)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendPings() {
|
||||||
|
val line: String
|
||||||
|
val targets: List<Spectator>
|
||||||
|
synchronized(lock) {
|
||||||
|
if (closed || spectators.isEmpty()) return
|
||||||
|
line = SpectatorProtocol.encode(SpectatorMessage.Ping(liveClock()))
|
||||||
|
targets = spectators.toList()
|
||||||
|
}
|
||||||
|
deliver(targets, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun deliver(targets: List<Spectator>, line: String) {
|
||||||
|
for (spectator in targets) {
|
||||||
|
if (!spectator.offer(line)) {
|
||||||
|
log("Spectator too slow, dropped")
|
||||||
|
drop(spectator)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun drop(spectator: Spectator) {
|
||||||
|
val others: List<Spectator>
|
||||||
|
val remaining: Int
|
||||||
|
synchronized(lock) {
|
||||||
|
// Already dropped, or the hub is closing and its writer is flushing the goodbye.
|
||||||
|
if (!spectators.remove(spectator)) return
|
||||||
|
remaining = spectators.size
|
||||||
|
_count.value = remaining
|
||||||
|
others = spectators.toList()
|
||||||
|
}
|
||||||
|
spectator.shutdown()
|
||||||
|
if (!closed) deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(remaining, maxSpectators)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun status(): SpectatorMessage.Status = synchronized(lock) {
|
||||||
|
val game = latest
|
||||||
|
SpectatorMessage.Status(
|
||||||
|
inGame = !closed && game != null && game.result == null,
|
||||||
|
count = spectators.size,
|
||||||
|
max = maxSpectators,
|
||||||
|
minVersion = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun elapsedMs(): Long = (System.nanoTime() - latestAtNanos) / 1_000_000L
|
||||||
|
|
||||||
|
private fun liveClock(): SpectatorClock? = latest?.clock?.advancedBy(elapsedMs())
|
||||||
|
|
||||||
|
private fun liveSnapshot(game: SpectatorSnapshot): SpectatorSnapshot =
|
||||||
|
if (game.clock == null) game else game.copy(clock = game.clock.advancedBy(elapsedMs()))
|
||||||
|
|
||||||
|
private fun reply(client: Socket, message: SpectatorMessage) {
|
||||||
|
try {
|
||||||
|
val out = client.getOutputStream()
|
||||||
|
out.write((SpectatorProtocol.encode(message) + "\n").toByteArray(Charsets.UTF_8))
|
||||||
|
out.flush()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// Nothing more to tell a peer that is gone.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One spectator's outgoing queue; one slot is kept free for the end marker. */
|
||||||
|
private class Spectator(val socket: Socket, private val capacity: Int) {
|
||||||
|
val queue = ArrayBlockingQueue<Any>(capacity + 1)
|
||||||
|
private var open = true
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun offer(line: String): Boolean = open && queue.size < capacity && queue.offer(line)
|
||||||
|
|
||||||
|
/** Lets the writer send what is queued, then close. */
|
||||||
|
@Synchronized
|
||||||
|
fun finish() {
|
||||||
|
if (!open) return
|
||||||
|
open = false
|
||||||
|
queue.offer(POISON)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops at once, discarding anything unsent. */
|
||||||
|
@Synchronized
|
||||||
|
fun shutdown() {
|
||||||
|
open = false
|
||||||
|
queue.clear()
|
||||||
|
queue.offer(POISON)
|
||||||
|
closeQuietly(socket)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
val POISON = Any()
|
||||||
|
|
||||||
|
/** Connections allowed to sit in the hello phase at once. */
|
||||||
|
const val MAX_HANDSHAKING = 32
|
||||||
|
|
||||||
|
fun closeQuietly(c: Closeable?) {
|
||||||
|
try { c?.close() } catch (_: IOException) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun daemonThreads(name: String): ThreadFactory {
|
||||||
|
val n = AtomicInteger()
|
||||||
|
return ThreadFactory { r -> Thread(r, "$name-${n.incrementAndGet()}").apply { isDaemon = true } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Feeds a hub from the host's game: each new snapshot becomes the messages spectators need. */
|
||||||
|
class SpectatorBroadcaster(val hub: SpectatorHub) {
|
||||||
|
private var last: SpectatorSnapshot? = null
|
||||||
|
|
||||||
|
fun update(snapshot: SpectatorSnapshot) {
|
||||||
|
val events = SpectatorDiff.between(last, snapshot)
|
||||||
|
last = snapshot
|
||||||
|
hub.publish(snapshot, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops spectating; [final] is the last state, e.g. the result of a game left midway. */
|
||||||
|
fun close(final: SpectatorSnapshot? = null) {
|
||||||
|
val events = if (final != null) SpectatorDiff.between(last, final) else emptyList()
|
||||||
|
hub.close(events)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
package cc.skysparkle.matewave.spectate
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/** Most spectators one hosted game accepts at the same time. */
|
||||||
|
const val MAX_SPECTATORS = 20
|
||||||
|
|
||||||
|
data class SpectatorPlayer(val id: String, val name: String, val elo: Int)
|
||||||
|
|
||||||
|
data class SpectatorClock(val whiteMs: Long, val blackMs: Long, val running: PieceColor?) {
|
||||||
|
/** The same clock [elapsedMs] later. */
|
||||||
|
fun advancedBy(elapsedMs: Long): SpectatorClock {
|
||||||
|
if (elapsedMs <= 0) return this
|
||||||
|
return when (running) {
|
||||||
|
PieceColor.WHITE -> copy(whiteMs = (whiteMs - elapsedMs).coerceAtLeast(0))
|
||||||
|
PieceColor.BLACK -> copy(blackMs = (blackMs - elapsedMs).coerceAtLeast(0))
|
||||||
|
null -> this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class SpectatorOutcome(val wire: String) {
|
||||||
|
CHECKMATE("checkmate"),
|
||||||
|
STALEMATE("stalemate"),
|
||||||
|
FIFTY_MOVES("fifty"),
|
||||||
|
REPETITION("repetition"),
|
||||||
|
INSUFFICIENT_MATERIAL("material"),
|
||||||
|
TIMEOUT("timeout"),
|
||||||
|
TIMEOUT_DRAW("timeout_draw"),
|
||||||
|
RESIGNATION("resign"),
|
||||||
|
AGREEMENT("agreement"),
|
||||||
|
LEFT("left"),
|
||||||
|
INTERRUPTED("interrupted"),
|
||||||
|
UNKNOWN("unknown");
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromWire(value: String): SpectatorOutcome = entries.firstOrNull { it.wire == value } ?: UNKNOWN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How a game ended; [winner] is null for draws and interrupted games. */
|
||||||
|
data class SpectatorResult(val outcome: SpectatorOutcome, val winner: PieceColor?)
|
||||||
|
|
||||||
|
/** Everything a spectator needs to show a game from any point: players, moves, clocks, result. */
|
||||||
|
data class SpectatorSnapshot(
|
||||||
|
val gameId: String,
|
||||||
|
val white: SpectatorPlayer,
|
||||||
|
val black: SpectatorPlayer,
|
||||||
|
val movesUci: List<String>,
|
||||||
|
val initialSeconds: Int,
|
||||||
|
val incrementSeconds: Int,
|
||||||
|
val clock: SpectatorClock?,
|
||||||
|
val result: SpectatorResult? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class RejectReason(val wire: String) {
|
||||||
|
FULL("full"),
|
||||||
|
UPDATE_REQUIRED("update"),
|
||||||
|
NO_GAME("no_game"),
|
||||||
|
OTHER("other");
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromWire(value: String): RejectReason = entries.firstOrNull { it.wire == value } ?: OTHER
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class SpectatorMessage {
|
||||||
|
// Spectator to host.
|
||||||
|
data class Hello(val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION) : SpectatorMessage()
|
||||||
|
data object StatusQuery : SpectatorMessage()
|
||||||
|
data object Pong : SpectatorMessage()
|
||||||
|
data object Resync : SpectatorMessage()
|
||||||
|
data object Leave : SpectatorMessage()
|
||||||
|
|
||||||
|
// Host to spectator.
|
||||||
|
data class Welcome(val count: Int, val max: Int, val game: SpectatorSnapshot) : SpectatorMessage()
|
||||||
|
data class Status(val inGame: Boolean, val count: Int, val max: Int, val minVersion: Int) : SpectatorMessage()
|
||||||
|
data class Reject(val reason: RejectReason, val minVersion: Int) : SpectatorMessage()
|
||||||
|
data class MovePlayed(val gameId: String, val ply: Int, val uci: String, val clock: SpectatorClock?) : SpectatorMessage()
|
||||||
|
data class GameOver(val gameId: String, val result: SpectatorResult, val clock: SpectatorClock?) : SpectatorMessage()
|
||||||
|
data class NewGame(val game: SpectatorSnapshot) : SpectatorMessage()
|
||||||
|
data class Count(val count: Int, val max: Int) : SpectatorMessage()
|
||||||
|
data class Ping(val clock: SpectatorClock?) : SpectatorMessage()
|
||||||
|
data object Closing : SpectatorMessage()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One decoded line: the sender's protocol version and the message, or null for an unknown type. */
|
||||||
|
data class SpectatorEnvelope(val version: Int, val message: SpectatorMessage?)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wire format between a hosted game and its spectators: one JSON object per line, each carrying
|
||||||
|
* the sender's protocol version in "sv". Unknown types are skipped, never fatal.
|
||||||
|
*/
|
||||||
|
object SpectatorProtocol {
|
||||||
|
/**
|
||||||
|
* Bump on incompatible changes and raise [MIN_COMPATIBLE_VERSION] to the oldest version still
|
||||||
|
* understood. hello, status and reject keep their shape so any two versions can still tell
|
||||||
|
* each other that an update is required.
|
||||||
|
*/
|
||||||
|
const val VERSION = 1
|
||||||
|
const val MIN_COMPATIBLE_VERSION = 1
|
||||||
|
|
||||||
|
const val MAX_HOST_LINE_CHARS = 64_000
|
||||||
|
const val MAX_CLIENT_LINE_CHARS = 1_024
|
||||||
|
|
||||||
|
private const val MAX_NAME_CHARS = 40
|
||||||
|
private const val MAX_PLIES = 2_000
|
||||||
|
|
||||||
|
fun encode(message: SpectatorMessage, version: Int = VERSION): String {
|
||||||
|
val o = JSONObject()
|
||||||
|
o.put("sv", version)
|
||||||
|
when (message) {
|
||||||
|
is SpectatorMessage.Hello -> { o.put("type", "hello"); o.put("min", message.minVersion) }
|
||||||
|
SpectatorMessage.StatusQuery -> o.put("type", "query")
|
||||||
|
SpectatorMessage.Pong -> o.put("type", "pong")
|
||||||
|
SpectatorMessage.Resync -> o.put("type", "resync")
|
||||||
|
SpectatorMessage.Leave -> o.put("type", "leave")
|
||||||
|
is SpectatorMessage.Welcome -> {
|
||||||
|
o.put("type", "welcome"); o.put("n", message.count); o.put("max", message.max)
|
||||||
|
o.put("game", snapshotJson(message.game))
|
||||||
|
}
|
||||||
|
is SpectatorMessage.Status -> {
|
||||||
|
o.put("type", "status"); o.put("live", message.inGame)
|
||||||
|
o.put("n", message.count); o.put("max", message.max); o.put("min", message.minVersion)
|
||||||
|
}
|
||||||
|
is SpectatorMessage.Reject -> {
|
||||||
|
o.put("type", "reject"); o.put("reason", message.reason.wire); o.put("min", message.minVersion)
|
||||||
|
}
|
||||||
|
is SpectatorMessage.MovePlayed -> {
|
||||||
|
o.put("type", "move"); o.put("gid", message.gameId); o.put("ply", message.ply); o.put("uci", message.uci)
|
||||||
|
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||||
|
}
|
||||||
|
is SpectatorMessage.GameOver -> {
|
||||||
|
o.put("type", "end"); o.put("gid", message.gameId); o.put("result", resultJson(message.result))
|
||||||
|
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||||
|
}
|
||||||
|
is SpectatorMessage.NewGame -> { o.put("type", "game"); o.put("game", snapshotJson(message.game)) }
|
||||||
|
is SpectatorMessage.Count -> { o.put("type", "count"); o.put("n", message.count); o.put("max", message.max) }
|
||||||
|
is SpectatorMessage.Ping -> {
|
||||||
|
o.put("type", "ping")
|
||||||
|
message.clock?.let { o.put("clock", clockJson(it)) }
|
||||||
|
}
|
||||||
|
SpectatorMessage.Closing -> o.put("type", "closing")
|
||||||
|
}
|
||||||
|
return o.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Null when the line is not a protocol message at all. */
|
||||||
|
fun decode(line: String): SpectatorEnvelope? {
|
||||||
|
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
|
||||||
|
val type = o.optString("type", "")
|
||||||
|
if (type.isEmpty()) return null
|
||||||
|
val version = o.optInt("sv", 0)
|
||||||
|
val message = runCatching { decodeMessage(type, o) }.getOrNull()
|
||||||
|
return SpectatorEnvelope(version, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeMessage(type: String, o: JSONObject): SpectatorMessage? = when (type) {
|
||||||
|
"hello" -> SpectatorMessage.Hello(o.optInt("min", o.optInt("sv", 0)))
|
||||||
|
"query" -> SpectatorMessage.StatusQuery
|
||||||
|
"pong" -> SpectatorMessage.Pong
|
||||||
|
"resync" -> SpectatorMessage.Resync
|
||||||
|
"leave" -> SpectatorMessage.Leave
|
||||||
|
"welcome" -> SpectatorMessage.Welcome(o.getInt("n"), o.getInt("max"), parseSnapshot(o.getJSONObject("game")))
|
||||||
|
"status" -> SpectatorMessage.Status(o.getBoolean("live"), o.getInt("n"), o.getInt("max"), o.optInt("min", 0))
|
||||||
|
"reject" -> SpectatorMessage.Reject(RejectReason.fromWire(o.getString("reason")), o.optInt("min", 0))
|
||||||
|
"move" -> SpectatorMessage.MovePlayed(
|
||||||
|
o.getString("gid"), o.getInt("ply"), o.getString("uci"), o.optJSONObject("clock")?.let(::parseClock)
|
||||||
|
)
|
||||||
|
"end" -> SpectatorMessage.GameOver(
|
||||||
|
o.getString("gid"), parseResult(o.getJSONObject("result")), o.optJSONObject("clock")?.let(::parseClock)
|
||||||
|
)
|
||||||
|
"game" -> SpectatorMessage.NewGame(parseSnapshot(o.getJSONObject("game")))
|
||||||
|
"count" -> SpectatorMessage.Count(o.getInt("n"), o.getInt("max"))
|
||||||
|
"ping" -> SpectatorMessage.Ping(o.optJSONObject("clock")?.let(::parseClock))
|
||||||
|
"closing" -> SpectatorMessage.Closing
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sideWire(side: PieceColor?): String = when (side) {
|
||||||
|
PieceColor.WHITE -> "w"
|
||||||
|
PieceColor.BLACK -> "b"
|
||||||
|
null -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sideOf(wire: String): PieceColor? = when (wire) {
|
||||||
|
"w" -> PieceColor.WHITE
|
||||||
|
"b" -> PieceColor.BLACK
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clockJson(c: SpectatorClock) = JSONObject().apply {
|
||||||
|
put("w", c.whiteMs); put("b", c.blackMs)
|
||||||
|
if (c.running != null) put("r", sideWire(c.running))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseClock(o: JSONObject) = SpectatorClock(
|
||||||
|
whiteMs = o.getLong("w").coerceAtLeast(0),
|
||||||
|
blackMs = o.getLong("b").coerceAtLeast(0),
|
||||||
|
running = sideOf(o.optString("r", ""))
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun resultJson(r: SpectatorResult) = JSONObject().apply {
|
||||||
|
put("o", r.outcome.wire)
|
||||||
|
if (r.winner != null) put("w", sideWire(r.winner))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseResult(o: JSONObject) = SpectatorResult(
|
||||||
|
outcome = SpectatorOutcome.fromWire(o.getString("o")),
|
||||||
|
winner = sideOf(o.optString("w", ""))
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun playerJson(p: SpectatorPlayer) = JSONObject().apply {
|
||||||
|
put("id", p.id); put("name", p.name); put("elo", p.elo)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parsePlayer(o: JSONObject) = SpectatorPlayer(
|
||||||
|
id = o.optString("id", "").take(64),
|
||||||
|
name = o.optString("name", "").take(MAX_NAME_CHARS),
|
||||||
|
elo = o.optInt("elo", 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun snapshotJson(s: SpectatorSnapshot) = JSONObject().apply {
|
||||||
|
put("gid", s.gameId)
|
||||||
|
put("wp", playerJson(s.white))
|
||||||
|
put("bp", playerJson(s.black))
|
||||||
|
put("moves", JSONArray().also { array -> s.movesUci.forEach { array.put(it) } })
|
||||||
|
put("ti", s.initialSeconds)
|
||||||
|
put("tx", s.incrementSeconds)
|
||||||
|
s.clock?.let { put("clock", clockJson(it)) }
|
||||||
|
s.result?.let { put("result", resultJson(it)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseSnapshot(o: JSONObject): SpectatorSnapshot {
|
||||||
|
val array = o.getJSONArray("moves")
|
||||||
|
require(array.length() <= MAX_PLIES)
|
||||||
|
return SpectatorSnapshot(
|
||||||
|
gameId = o.getString("gid"),
|
||||||
|
white = parsePlayer(o.getJSONObject("wp")),
|
||||||
|
black = parsePlayer(o.getJSONObject("bp")),
|
||||||
|
movesUci = List(array.length()) { array.getString(it) },
|
||||||
|
initialSeconds = o.optInt("ti", 0),
|
||||||
|
incrementSeconds = o.optInt("tx", 0),
|
||||||
|
clock = o.optJSONObject("clock")?.let(::parseClock),
|
||||||
|
result = o.optJSONObject("result")?.let(::parseResult)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -78,14 +78,16 @@ fun ChessBoardView(
|
|||||||
interactionEnabled: Boolean = true,
|
interactionEnabled: Boolean = true,
|
||||||
/** A square briefly tinted to confirm or reject a move (puzzles). */
|
/** A square briefly tinted to confirm or reject a move (puzzles). */
|
||||||
flashSquare: Int? = null,
|
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 context = LocalContext.current
|
||||||
val appearance = remember { BoardAppearance(context) }
|
val appearance = remember { BoardAppearance(context) }
|
||||||
val theme = appearance.theme
|
val theme = appearance.theme
|
||||||
val showCoords = appearance.showCoordinates
|
val showCoords = appearance.showCoordinates
|
||||||
val imagePieces = appearance.useImagePieces
|
val imagePieces = appearance.useImagePieces
|
||||||
val showLastMove = appearance.showLastMove
|
val showLastMove = highlightLastMove ?: appearance.showLastMove
|
||||||
val showCheck = appearance.showCheckHighlight
|
val showCheck = appearance.showCheckHighlight
|
||||||
|
|
||||||
val pieceImages = if (imagePieces) remember(context) { PieceImages.get(context) } else null
|
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.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
|
||||||
|
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
|
@Composable
|
||||||
fun FriendsScreen(
|
fun FriendsScreen(
|
||||||
@@ -53,7 +62,8 @@ fun FriendsScreen(
|
|||||||
onHomeClick: () -> Unit,
|
onHomeClick: () -> Unit,
|
||||||
onSettingsClick: () -> Unit,
|
onSettingsClick: () -> Unit,
|
||||||
onAccountClick: () -> Unit,
|
onAccountClick: () -> Unit,
|
||||||
onPlay: () -> Unit = {}
|
onPlay: () -> Unit = {},
|
||||||
|
onWatch: (SpectateTarget) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
var onlineOnly by remember { mutableStateOf(false) }
|
var onlineOnly by remember { mutableStateOf(false) }
|
||||||
var version by remember { mutableStateOf(0) }
|
var version by remember { mutableStateOf(0) }
|
||||||
@@ -64,6 +74,28 @@ fun FriendsScreen(
|
|||||||
val peers by presence.peers.collectAsState()
|
val peers by presence.peers.collectAsState()
|
||||||
val friends = remember(peers, version) { FriendsStore.list() }
|
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.
|
// Fresh search on opening, then refresh "5 min ago" labels while the screen is visible.
|
||||||
androidx.compose.runtime.LaunchedEffect(Unit) {
|
androidx.compose.runtime.LaunchedEffect(Unit) {
|
||||||
presence.refresh()
|
presence.refresh()
|
||||||
@@ -115,18 +147,20 @@ fun FriendsScreen(
|
|||||||
FriendGroup(
|
FriendGroup(
|
||||||
title = stringResource(R.string.friends_group_favorites),
|
title = stringResource(R.string.friends_group_favorites),
|
||||||
list = favorites,
|
list = favorites,
|
||||||
isOnline = presence::isOnline,
|
statusOf = statusOf,
|
||||||
onOpen = { opened = it },
|
onOpen = { opened = it },
|
||||||
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
||||||
onPlay = onPlay
|
onPlay = onPlay,
|
||||||
|
onWatch = onWatch
|
||||||
)
|
)
|
||||||
FriendGroup(
|
FriendGroup(
|
||||||
title = if (favorites.isNotEmpty()) stringResource(R.string.friends_group_others) else null,
|
title = if (favorites.isNotEmpty()) stringResource(R.string.friends_group_others) else null,
|
||||||
list = others,
|
list = others,
|
||||||
isOnline = presence::isOnline,
|
statusOf = statusOf,
|
||||||
onOpen = { opened = it },
|
onOpen = { opened = it },
|
||||||
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
onToggleFavorite = { FriendsStore.toggleFavorite(it.userId); version++ },
|
||||||
onPlay = onPlay
|
onPlay = onPlay,
|
||||||
|
onWatch = onWatch
|
||||||
)
|
)
|
||||||
|
|
||||||
if (strangers.isNotEmpty()) {
|
if (strangers.isNotEmpty()) {
|
||||||
@@ -134,11 +168,13 @@ fun FriendsScreen(
|
|||||||
ListGroup {
|
ListGroup {
|
||||||
strangers.sortedBy { it.name }.forEachIndexed { index, peer ->
|
strangers.sortedBy { it.name }.forEachIndexed { index, peer ->
|
||||||
if (index > 0) ListDivider(inset = 68)
|
if (index > 0) ListDivider(inset = 68)
|
||||||
|
val status = statusOf(peer.playerId)
|
||||||
ListRow(
|
ListRow(
|
||||||
title = displayName(peer.name, peer.playerId),
|
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) },
|
leading = { AvatarCircle(base64 = null, size = 40.dp) },
|
||||||
trailing = { PlayChip(onPlay) }
|
trailing = { StatusAction(status, onPlay, onWatch) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,7 +185,7 @@ fun FriendsScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
opened?.let { friend ->
|
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(
|
private fun FriendGroup(
|
||||||
title: String?,
|
title: String?,
|
||||||
list: List<FriendEntry>,
|
list: List<FriendEntry>,
|
||||||
isOnline: (String) -> Boolean,
|
statusOf: (String) -> FriendGameStatus,
|
||||||
onOpen: (FriendEntry) -> Unit,
|
onOpen: (FriendEntry) -> Unit,
|
||||||
onToggleFavorite: (FriendEntry) -> Unit,
|
onToggleFavorite: (FriendEntry) -> Unit,
|
||||||
onPlay: () -> Unit
|
onPlay: () -> Unit,
|
||||||
|
onWatch: (SpectateTarget) -> Unit
|
||||||
) {
|
) {
|
||||||
if (list.isEmpty()) return
|
if (list.isEmpty()) return
|
||||||
if (title != null) SectionCaption(title)
|
if (title != null) SectionCaption(title)
|
||||||
@@ -170,10 +207,11 @@ private fun FriendGroup(
|
|||||||
if (index > 0) ListDivider(inset = 68)
|
if (index > 0) ListDivider(inset = 68)
|
||||||
FriendRow(
|
FriendRow(
|
||||||
friend = friend,
|
friend = friend,
|
||||||
online = isOnline(friend.userId),
|
status = statusOf(friend.userId),
|
||||||
onOpen = { onOpen(friend) },
|
onOpen = { onOpen(friend) },
|
||||||
onToggleFavorite = { onToggleFavorite(friend) },
|
onToggleFavorite = { onToggleFavorite(friend) },
|
||||||
onPlay = onPlay
|
onPlay = onPlay,
|
||||||
|
onWatch = onWatch
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,7 +243,7 @@ private fun PlayChip(onClick: () -> Unit) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Unit) {
|
private fun FriendCard(friend: FriendEntry, status: PresenceStatus, onDismiss: () -> Unit) {
|
||||||
Dialog(onDismissRequest = onDismiss) {
|
Dialog(onDismissRequest = onDismiss) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
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)) {
|
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
Text(
|
Text(
|
||||||
if (online) stringResource(R.string.friends_online)
|
statusText(status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||||
else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
color = when (status) {
|
||||||
color = if (online) Color(0xFF7BE495) else ink.copy(alpha = 0.6f),
|
PresenceStatus.ONLINE -> Color(0xFF7BE495)
|
||||||
|
PresenceStatus.IN_GAME -> InGameColor
|
||||||
|
PresenceStatus.OFFLINE -> ink.copy(alpha = 0.6f)
|
||||||
|
},
|
||||||
style = MaterialTheme.typography.bodyMedium
|
style = MaterialTheme.typography.bodyMedium
|
||||||
)
|
)
|
||||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||||
@@ -276,32 +317,33 @@ private fun FriendCard(friend: FriendEntry, online: Boolean, onDismiss: () -> Un
|
|||||||
@Composable
|
@Composable
|
||||||
private fun FriendRow(
|
private fun FriendRow(
|
||||||
friend: FriendEntry,
|
friend: FriendEntry,
|
||||||
online: Boolean,
|
status: FriendGameStatus,
|
||||||
onOpen: () -> Unit,
|
onOpen: () -> Unit,
|
||||||
onToggleFavorite: () -> Unit,
|
onToggleFavorite: () -> Unit,
|
||||||
onPlay: () -> Unit
|
onPlay: () -> Unit,
|
||||||
|
onWatch: (SpectateTarget) -> Unit
|
||||||
) {
|
) {
|
||||||
ListRow(
|
ListRow(
|
||||||
title = displayName(friend.name, friend.userId),
|
title = displayName(friend.name, friend.userId),
|
||||||
subtitle = stringResource(R.string.friends_rating, friend.elo) + " · " +
|
subtitle = stringResource(R.string.friends_rating, friend.elo) + " · " +
|
||||||
(if (online) stringResource(R.string.friends_online) else lastSeenText(maxOf(friend.lastPlayedMs, friend.lastSeenMs))),
|
statusText(status.status, maxOf(friend.lastPlayedMs, friend.lastSeenMs)),
|
||||||
subtitleColor = if (online) ChessGreen else ink.copy(alpha = 0.55f),
|
subtitleColor = statusColor(status.status),
|
||||||
leading = {
|
leading = {
|
||||||
Box {
|
Box {
|
||||||
AvatarCircle(base64 = friend.avatarBase64, size = 40.dp)
|
AvatarCircle(base64 = friend.avatarBase64, size = 40.dp)
|
||||||
if (online) {
|
if (status.status != PresenceStatus.OFFLINE) {
|
||||||
Box(
|
Box(
|
||||||
Modifier
|
Modifier
|
||||||
.align(Alignment.BottomEnd)
|
.align(Alignment.BottomEnd)
|
||||||
.size(11.dp)
|
.size(11.dp)
|
||||||
.clip(CircleShape)
|
.clip(CircleShape)
|
||||||
.background(ChessGreen)
|
.background(if (status.status == PresenceStatus.IN_GAME) InGameColor else ChessGreen)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
trailing = {
|
trailing = {
|
||||||
if (online) PlayChip(onPlay)
|
StatusAction(status, onPlay, onWatch)
|
||||||
AppIcon(
|
AppIcon(
|
||||||
R.drawable.ic_star,
|
R.drawable.ic_star,
|
||||||
size = 20.dp,
|
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
|
@Composable
|
||||||
private fun lastSeenText(lastSeenMs: Long): String {
|
private fun lastSeenText(lastSeenMs: Long): String {
|
||||||
if (lastSeenMs <= 0) return stringResource(R.string.friends_offline)
|
if (lastSeenMs <= 0) return stringResource(R.string.friends_offline)
|
||||||
|
|||||||
@@ -101,6 +101,11 @@ fun GameScreen(viewModel: GameViewModel, onExit: () -> Unit) {
|
|||||||
GlassScaffold(
|
GlassScaffold(
|
||||||
title = "",
|
title = "",
|
||||||
onBack = requestExit,
|
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) {
|
titleContent = if (showOpening && opening != null) {
|
||||||
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
|
{ OpeningTitle("${opening.eco} · ${opening.name}", bookStatus, inBook) }
|
||||||
} else null
|
} else null
|
||||||
@@ -490,7 +495,7 @@ private fun PlayerRow(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun BigClock(millis: Long, active: Boolean) {
|
internal fun BigClock(millis: Long, active: Boolean) {
|
||||||
val totalSeconds = millis / 1000
|
val totalSeconds = millis / 1000
|
||||||
val low = active && totalSeconds < 20
|
val low = active && totalSeconds < 20
|
||||||
val color = when {
|
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.SessionAuth
|
||||||
import cc.skysparkle.matewave.security.TrustResult
|
import cc.skysparkle.matewave.security.TrustResult
|
||||||
import cc.skysparkle.matewave.settings.Haptics
|
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 cc.skysparkle.matewave.stats.Stats
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
@@ -95,7 +104,10 @@ data class GameUiState(
|
|||||||
val opponentLeftMidGame: Boolean = false,
|
val opponentLeftMidGame: Boolean = false,
|
||||||
val rematchOfferFromOpponent: 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)
|
data class PendingPromotion(val from: Int, val to: Int)
|
||||||
@@ -172,6 +184,16 @@ class GameViewModel : ViewModel() {
|
|||||||
private var currentPly: Int = 0
|
private var currentPly: Int = 0
|
||||||
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
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 {
|
init {
|
||||||
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
GameSaveStore.load()?.let { saved -> restoreSaved(saved) }
|
||||||
}
|
}
|
||||||
@@ -689,6 +711,7 @@ class GameViewModel : ViewModel() {
|
|||||||
pendingLeave = null
|
pendingLeave = null
|
||||||
handshakeTimeoutJob?.cancel()
|
handshakeTimeoutJob?.cancel()
|
||||||
handshakeTimeoutJob = null
|
handshakeTimeoutJob = null
|
||||||
|
stopSpectating()
|
||||||
cancelAi()
|
cancelAi()
|
||||||
// A paused game against the AI stays saved and can be continued later.
|
// A paused game against the AI stays saved and can be continued later.
|
||||||
persistIfResumable()
|
persistIfResumable()
|
||||||
@@ -729,6 +752,8 @@ class GameViewModel : ViewModel() {
|
|||||||
heartbeat?.stop()
|
heartbeat?.stop()
|
||||||
heartbeat = cc.skysparkle.matewave.network.Heartbeat(viewModelScope, transport).also { it.start() }
|
heartbeat = cc.skysparkle.matewave.network.Heartbeat(viewModelScope, transport).also { it.start() }
|
||||||
|
|
||||||
|
spectatorWatcher = viewModelScope.launch { _uiState.collect { onStateForSpectators(it) } }
|
||||||
|
|
||||||
var profileSent = false
|
var profileSent = false
|
||||||
var connectedOnce = false
|
var connectedOnce = false
|
||||||
val connectStartedAt = System.currentTimeMillis()
|
val connectStartedAt = System.currentTimeMillis()
|
||||||
@@ -965,6 +990,10 @@ class GameViewModel : ViewModel() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
is GameMessage.PingMsg -> Unit
|
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 -> {
|
is GameMessage.TimeoutMsg -> {
|
||||||
if (!belongsToCurrentGame(msg.gameId)) return
|
if (!belongsToCurrentGame(msg.gameId)) return
|
||||||
val state = _uiState.value
|
val state = _uiState.value
|
||||||
@@ -1113,6 +1142,9 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun endNetworkSession() {
|
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?.cancel()
|
||||||
opponentFlagJob = null
|
opponentFlagJob = null
|
||||||
clock?.stop()
|
clock?.stop()
|
||||||
@@ -1137,7 +1169,9 @@ class GameViewModel : ViewModel() {
|
|||||||
return
|
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)
|
applyNetworkResultElo(0.0)
|
||||||
}
|
}
|
||||||
opponentFlagJob?.cancel()
|
opponentFlagJob?.cancel()
|
||||||
@@ -1218,7 +1252,8 @@ class GameViewModel : ViewModel() {
|
|||||||
handshake = state.handshake,
|
handshake = state.handshake,
|
||||||
activeTransport = state.activeTransport,
|
activeTransport = state.activeTransport,
|
||||||
opponentUnverified = state.opponentUnverified,
|
opponentUnverified = state.opponentUnverified,
|
||||||
chatMessages = state.chatMessages
|
chatMessages = state.chatMessages,
|
||||||
|
spectatorCount = state.spectatorCount
|
||||||
)
|
)
|
||||||
setupClock(timeControl)
|
setupClock(timeControl)
|
||||||
}
|
}
|
||||||
@@ -1333,6 +1368,119 @@ class GameViewModel : ViewModel() {
|
|||||||
|
|
||||||
// endregion
|
// 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
|
// region Clock
|
||||||
|
|
||||||
private fun disposeClock() {
|
private fun disposeClock() {
|
||||||
@@ -1418,6 +1566,7 @@ class GameViewModel : ViewModel() {
|
|||||||
pendingLeave?.first?.cancel()
|
pendingLeave?.first?.cancel()
|
||||||
pendingLeave?.second?.disconnect()
|
pendingLeave?.second?.disconnect()
|
||||||
pendingLeave = null
|
pendingLeave = null
|
||||||
|
stopSpectating()
|
||||||
persistIfResumable()
|
persistIfResumable()
|
||||||
clock?.stop()
|
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>
|
||||||
@@ -358,4 +358,26 @@
|
|||||||
<string name="piece_rook">Turm</string>
|
<string name="piece_rook">Turm</string>
|
||||||
<string name="piece_bishop">Läufer</string>
|
<string name="piece_bishop">Läufer</string>
|
||||||
<string name="piece_knight">Springer</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>
|
</resources>
|
||||||
|
|||||||
@@ -357,4 +357,26 @@
|
|||||||
<string name="piece_rook">ルーク</string>
|
<string name="piece_rook">ルーク</string>
|
||||||
<string name="piece_bishop">ビショップ</string>
|
<string name="piece_bishop">ビショップ</string>
|
||||||
<string name="piece_knight">ナイト</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>
|
</resources>
|
||||||
|
|||||||
@@ -360,4 +360,26 @@
|
|||||||
<string name="piece_rook">Bokštas</string>
|
<string name="piece_rook">Bokštas</string>
|
||||||
<string name="piece_bishop">Rikis</string>
|
<string name="piece_bishop">Rikis</string>
|
||||||
<string name="piece_knight">Žirgas</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>
|
</resources>
|
||||||
|
|||||||
@@ -366,4 +366,26 @@
|
|||||||
<string name="piece_rook">Ладья</string>
|
<string name="piece_rook">Ладья</string>
|
||||||
<string name="piece_bishop">Слон</string>
|
<string name="piece_bishop">Слон</string>
|
||||||
<string name="piece_knight">Конь</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>
|
</resources>
|
||||||
|
|||||||
@@ -357,4 +357,26 @@
|
|||||||
<string name="piece_rook">车</string>
|
<string name="piece_rook">车</string>
|
||||||
<string name="piece_bishop">象</string>
|
<string name="piece_bishop">象</string>
|
||||||
<string name="piece_knight">马</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>
|
</resources>
|
||||||
|
|||||||
@@ -358,4 +358,26 @@
|
|||||||
<string name="piece_rook">Rook</string>
|
<string name="piece_rook">Rook</string>
|
||||||
<string name="piece_bishop">Bishop</string>
|
<string name="piece_bishop">Bishop</string>
|
||||||
<string name="piece_knight">Knight</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>
|
</resources>
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.spectate.FriendStatusResolver
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.NearbyPlayerGame
|
||||||
|
import cc.skysparkle.matewave.spectate.PresenceStatus
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectateTarget
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorAdvert
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FriendStatusTest {
|
||||||
|
private val tag = SpectatorAdvert.tagOf("game-1")
|
||||||
|
private val host = NearbyPlayerGame("host", "192.168.1.10", tag, 40_123)
|
||||||
|
private val guest = NearbyPlayerGame("guest", "192.168.1.11", tag, 0)
|
||||||
|
private val idle = NearbyPlayerGame("idle", "192.168.1.12", "", 0)
|
||||||
|
private val nearby = listOf(host, guest, idle).associateBy { it.playerId }
|
||||||
|
private val target = SpectateTarget("192.168.1.10", 40_123, tag)
|
||||||
|
|
||||||
|
private fun status(count: Int, live: Boolean = true) = SpectatorMessage.Status(live, count, MAX_SPECTATORS, 1)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun notVisibleIsOffline() {
|
||||||
|
assertEquals(PresenceStatus.OFFLINE, FriendStatusResolver.resolve("nobody", nearby, emptyMap()).status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun visibleWithoutAGameIsOnline() {
|
||||||
|
val s = FriendStatusResolver.resolve("idle", nearby, emptyMap())
|
||||||
|
assertEquals(PresenceStatus.ONLINE, s.status)
|
||||||
|
assertNull(s.target)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostInGameCanBeWatchedWithTheLiveCount() {
|
||||||
|
val s = FriendStatusResolver.resolve("host", nearby, mapOf(target to status(7)))
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertEquals(target, s.target)
|
||||||
|
assertEquals(7, s.spectators)
|
||||||
|
assertFalse(s.full)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun guestIsWatchedThroughTheHost() {
|
||||||
|
val s = FriendStatusResolver.resolve("guest", nearby, mapOf(target to status(3)))
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertEquals(target, s.target)
|
||||||
|
assertEquals(3, s.spectators)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fullGameIsReportedAsFull() {
|
||||||
|
assertTrue(FriendStatusResolver.resolve("host", nearby, mapOf(target to status(MAX_SPECTATORS))).full)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun countIsUnknownUntilTheHostAnswers() {
|
||||||
|
val s = FriendStatusResolver.resolve("host", nearby, emptyMap())
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertNull(s.spectators)
|
||||||
|
assertFalse(s.full)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostSayingTheGameEndedWinsOverAStaleAnnouncement() {
|
||||||
|
val ended = mapOf(target to status(0, live = false))
|
||||||
|
assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("host", nearby, ended).status)
|
||||||
|
assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("guest", nearby, ended).status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun guestWhoseHostIsHiddenIsInGameWithoutWatch() {
|
||||||
|
val s = FriendStatusResolver.resolve("guest", mapOf("guest" to guest), emptyMap())
|
||||||
|
assertEquals(PresenceStatus.IN_GAME, s.status)
|
||||||
|
assertNull(s.target)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun onlyHostsAreProbed() {
|
||||||
|
assertEquals(setOf(target), FriendStatusResolver.targets(nearby.values))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun advertRoundTripsAndRejectsJunk() {
|
||||||
|
val state = SpectatorAdvert.State(tag, 40_123)
|
||||||
|
val attrs = SpectatorAdvert.attributes(state)
|
||||||
|
assertEquals(state, SpectatorAdvert.parse { attrs[it] ?: "" })
|
||||||
|
assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { "" })
|
||||||
|
assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { if (it == "g") "not-a-tag" else "1" })
|
||||||
|
assertEquals(SpectatorAdvert.State(tag, 0), SpectatorAdvert.parse { if (it == "g") tag else "99999" })
|
||||||
|
assertEquals(emptyMap<String, String>(), SpectatorAdvert.attributes(SpectatorAdvert.State()))
|
||||||
|
assertEquals(8, tag.length)
|
||||||
|
assertEquals("", SpectatorAdvert.tagOf(""))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ class GameMessageTest {
|
|||||||
@Test fun signed() = roundTrip(GameMessage.SignedMsg("abc", "tag", 7))
|
@Test fun signed() = roundTrip(GameMessage.SignedMsg("abc", "tag", 7))
|
||||||
@Test fun rematch() = roundTrip(GameMessage.RematchMsg("accept", "g1", "g2"))
|
@Test fun rematch() = roundTrip(GameMessage.RematchMsg("accept", "g1", "g2"))
|
||||||
@Test fun images() = roundTrip(GameMessage.ProfileImagesMsg("a", null, "g1"))
|
@Test fun images() = roundTrip(GameMessage.ProfileImagesMsg("a", null, "g1"))
|
||||||
|
@Test fun spectatorCount() = roundTrip(GameMessage.SpectatorCountMsg(7, "g1"))
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun profileCarriesGameIdAndVersion() {
|
fun profileCarriesGameIdAndVersion() {
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.GameStatus
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.engine.PieceType
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorDiff
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame.Applied
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
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 org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SpectatorGameTest {
|
||||||
|
private fun snapshot(moves: List<String>, gameId: String = "g1", result: SpectatorResult? = null) = SpectatorSnapshot(
|
||||||
|
gameId = gameId,
|
||||||
|
white = SpectatorPlayer("u1", "Alice", 1500),
|
||||||
|
black = SpectatorPlayer("u2", "Bob", 1400),
|
||||||
|
movesUci = moves,
|
||||||
|
initialSeconds = 180,
|
||||||
|
incrementSeconds = 2,
|
||||||
|
clock = SpectatorClock(170_000, 175_000, if (moves.size % 2 == 0) PieceColor.WHITE else PieceColor.BLACK),
|
||||||
|
result = result
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun move(ply: Int, uci: String, gameId: String = "g1") = SpectatorMessage.MovePlayed(gameId, ply, uci, null)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun loadReplaysTheMoveListWithTurnAndLastMove() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
assertTrue(game.load(snapshot(listOf("e2e4", "e7e5", "e1e2"))))
|
||||||
|
val view = game.view!!
|
||||||
|
assertEquals(listOf("e4", "e5", "Ke2"), view.moveSans)
|
||||||
|
assertEquals(PieceColor.BLACK, view.board.sideToMove)
|
||||||
|
assertEquals("e1e2", view.lastMove!!.toUci())
|
||||||
|
assertEquals(3, view.ply)
|
||||||
|
assertEquals(180, view.initialSeconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun illegalHistoryIsRefused() {
|
||||||
|
assertFalse(SpectatorGame().load(snapshot(listOf("e2e5"))))
|
||||||
|
assertFalse(SpectatorGame().load(snapshot(listOf("zz99"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun liveMovesFollowOnAndDuplicatesAreIgnored() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
game.load(snapshot(listOf("d2d4")))
|
||||||
|
assertEquals(Applied.APPLIED, game.onMove(move(2, "d7d5")))
|
||||||
|
assertEquals(Applied.IGNORED, game.onMove(move(2, "d7d5")))
|
||||||
|
assertEquals(Applied.IGNORED, game.onMove(move(1, "d2d4")))
|
||||||
|
assertEquals(listOf("d4", "d5"), game.view!!.moveSans)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun gapsIllegalMovesAndForeignGamesAskForResync() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
game.load(snapshot(listOf("d2d4")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(3, "c2c4")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d4d5")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d7d5", gameId = "other")))
|
||||||
|
assertEquals(Applied.NEEDS_RESYNC, SpectatorGame().onMove(move(1, "e2e4")))
|
||||||
|
assertEquals(1, game.view!!.ply)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun promotionIsKept() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
val moves = listOf("h2h4", "g7g5", "h4g5", "h7h6", "g5h6", "g8f6", "h6h7", "f6g8")
|
||||||
|
assertTrue(game.load(snapshot(moves)))
|
||||||
|
assertEquals(Applied.APPLIED, game.onMove(move(9, "h7g8n")))
|
||||||
|
assertEquals(PieceType.KNIGHT, game.view!!.lastMove!!.promotion)
|
||||||
|
assertEquals("hxg8=N", game.view!!.moveSans.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun gameOverStopsTheClockAndLaterMovesAreIgnored() {
|
||||||
|
val game = SpectatorGame()
|
||||||
|
game.load(snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4")))
|
||||||
|
val result = SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK)
|
||||||
|
assertEquals(Applied.APPLIED, game.onGameOver(SpectatorMessage.GameOver("g1", result, null)))
|
||||||
|
assertEquals(result, game.view!!.result)
|
||||||
|
assertNull(game.view!!.clock!!.running)
|
||||||
|
assertEquals(Applied.IGNORED, game.onMove(move(5, "a2a3")))
|
||||||
|
game.onClock(SpectatorClock(1, 1, PieceColor.WHITE))
|
||||||
|
assertNull(game.view!!.clock!!.running)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun diffTurnsNewMovesIntoLiveMessagesWithTheLatestClock() {
|
||||||
|
val before = snapshot(listOf("e2e4"))
|
||||||
|
val after = snapshot(listOf("e2e4", "e7e5", "g1f3"))
|
||||||
|
val events = SpectatorDiff.between(before, after)
|
||||||
|
assertEquals(2, events.size)
|
||||||
|
val first = events[0] as SpectatorMessage.MovePlayed
|
||||||
|
val second = events[1] as SpectatorMessage.MovePlayed
|
||||||
|
assertEquals(2 to "e7e5", first.ply to first.uci)
|
||||||
|
assertNull(first.clock)
|
||||||
|
assertEquals(3 to "g1f3", second.ply to second.uci)
|
||||||
|
assertEquals(after.clock, second.clock)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun diffReportsTheEndOnceAndRestartsOnANewGame() {
|
||||||
|
val playing = snapshot(listOf("e2e4"))
|
||||||
|
val over = playing.copy(result = SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.WHITE))
|
||||||
|
assertEquals(listOf(SpectatorMessage.GameOver("g1", over.result!!, over.clock)), SpectatorDiff.between(playing, over))
|
||||||
|
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(over, over))
|
||||||
|
val rematch = snapshot(emptyList(), gameId = "g2")
|
||||||
|
assertEquals(listOf(SpectatorMessage.NewGame(rematch)), SpectatorDiff.between(over, rematch))
|
||||||
|
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(null, rematch))
|
||||||
|
// Clock ticks alone are carried by pings, not extra messages.
|
||||||
|
assertEquals(emptyList<SpectatorMessage>(), SpectatorDiff.between(playing, playing.copy(clock = SpectatorClock(1, 2, null))))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun diffFallsBackToAFullSnapshotWhenHistoryChanges() {
|
||||||
|
val a = snapshot(listOf("e2e4", "e7e5"))
|
||||||
|
val b = snapshot(listOf("d2d4"))
|
||||||
|
assertEquals(listOf(SpectatorMessage.NewGame(b)), SpectatorDiff.between(a, b))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun resultsMapEveryWayAGameCanEnd() {
|
||||||
|
fun of(status: GameStatus, timedOut: PieceColor? = null, resigned: PieceColor? = null, left: Boolean = false) =
|
||||||
|
SpectatorResults.of(status, PieceColor.WHITE, timedOut, resigned, left)
|
||||||
|
assertNull(of(GameStatus.ONGOING))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK), of(GameStatus.CHECKMATE))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT, PieceColor.WHITE), of(GameStatus.TIMEOUT, timedOut = PieceColor.BLACK))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.BLACK), of(GameStatus.RESIGNATION, resigned = PieceColor.WHITE))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.WHITE), of(GameStatus.RESIGNATION, resigned = PieceColor.BLACK, left = true))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.STALEMATE, null), of(GameStatus.STALEMATE))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null), of(GameStatus.DRAW_50_MOVES))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.REPETITION, null), of(GameStatus.DRAW_REPETITION))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null), of(GameStatus.DRAW_MATERIAL))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null), of(GameStatus.TIMEOUT_DRAW))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.AGREEMENT, null), of(GameStatus.DRAW_AGREEMENT))
|
||||||
|
assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.BLACK), SpectatorResults.leftBy(PieceColor.WHITE))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,460 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.RejectReason
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorBroadcaster
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient.Event
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClient.Failure
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorGame
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorHub
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProbe
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProtocol
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResults
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Assert.fail
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.Closeable
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.ServerSocket
|
||||||
|
import java.net.Socket
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class SpectatorHubTest {
|
||||||
|
private val loopback: InetAddress = InetAddress.getLoopbackAddress()
|
||||||
|
private val hubTiming = SpectatorHub.Timing(helloTimeoutMs = 1_000, pingIntervalMs = 150, silenceTimeoutMs = 900)
|
||||||
|
private val clientTiming = SpectatorClient.Timing(connectTimeoutMs = 2_000, silenceTimeoutMs = 900)
|
||||||
|
|
||||||
|
private val hubs = CopyOnWriteArrayList<SpectatorHub>()
|
||||||
|
private val clients = CopyOnWriteArrayList<SpectatorClient>()
|
||||||
|
private val closeables = CopyOnWriteArrayList<Closeable>()
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
clients.forEach { it.stop() }
|
||||||
|
hubs.forEach { it.close() }
|
||||||
|
closeables.forEach { runCatching { it.close() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun snapshot(
|
||||||
|
moves: List<String> = emptyList(),
|
||||||
|
clock: SpectatorClock? = SpectatorClock(300_000, 300_000, PieceColor.WHITE),
|
||||||
|
gameId: String = "g1"
|
||||||
|
) = SpectatorSnapshot(
|
||||||
|
gameId = gameId,
|
||||||
|
white = SpectatorPlayer("u1", "Alice", 1500),
|
||||||
|
black = SpectatorPlayer("u2", "Bob", 1400),
|
||||||
|
movesUci = moves,
|
||||||
|
initialSeconds = 300,
|
||||||
|
incrementSeconds = 0,
|
||||||
|
clock = clock
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun hub(initial: SpectatorSnapshot? = snapshot()): SpectatorHub {
|
||||||
|
val hub = SpectatorHub(timing = hubTiming)
|
||||||
|
hubs += hub
|
||||||
|
hub.start(loopback)
|
||||||
|
if (initial != null) hub.publish(initial)
|
||||||
|
return hub
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Recorder {
|
||||||
|
val events = LinkedBlockingQueue<Event>()
|
||||||
|
|
||||||
|
fun next(timeoutMs: Long = 3_000): Event =
|
||||||
|
events.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: throw AssertionError("No event within $timeoutMs ms")
|
||||||
|
|
||||||
|
/** Skips pings and counts until an event matching [predicate]. */
|
||||||
|
fun awaitEvent(timeoutMs: Long = 3_000, predicate: (Event) -> Boolean): Event {
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
while (true) {
|
||||||
|
val left = deadline - System.currentTimeMillis()
|
||||||
|
if (left <= 0) throw AssertionError("Expected event did not arrive")
|
||||||
|
val event = events.poll(left, TimeUnit.MILLISECONDS) ?: continue
|
||||||
|
if (predicate(event)) return event
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun awaitMessage(timeoutMs: Long = 3_000, predicate: (SpectatorMessage) -> Boolean): SpectatorMessage =
|
||||||
|
(awaitEvent(timeoutMs) { it is Event.Received && predicate(it.message) } as Event.Received).message
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun watch(
|
||||||
|
port: Int,
|
||||||
|
recorder: Recorder = Recorder(),
|
||||||
|
version: Int = SpectatorProtocol.VERSION,
|
||||||
|
minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION
|
||||||
|
): Pair<SpectatorClient, Recorder> {
|
||||||
|
val client = SpectatorClient("127.0.0.1", port, { recorder.events.add(it) }, clientTiming, version, minVersion)
|
||||||
|
clients += client
|
||||||
|
client.start()
|
||||||
|
return client to recorder
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitCount(hub: SpectatorHub, expected: Int, timeoutMs: Long = 3_000) {
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
while (hub.count.value != expected) {
|
||||||
|
if (System.currentTimeMillis() > deadline) fail("Spectator count ${hub.count.value}, expected $expected")
|
||||||
|
Thread.sleep(10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun joined(recorder: Recorder): SpectatorMessage.Welcome {
|
||||||
|
val event = recorder.next()
|
||||||
|
assertTrue("Expected to join, got $event", event is Event.Joined)
|
||||||
|
return (event as Event.Joined).welcome
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun twentySpectatorsJoinAndTheTwentyFirstIsRefused() {
|
||||||
|
val hub = hub()
|
||||||
|
val watchers = List(MAX_SPECTATORS) { watch(hub.port).second }
|
||||||
|
watchers.forEach { joined(it) }
|
||||||
|
awaitCount(hub, MAX_SPECTATORS)
|
||||||
|
|
||||||
|
val (_, late) = watch(hub.port)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.FULL), late.next())
|
||||||
|
assertEquals(MAX_SPECTATORS, hub.count.value)
|
||||||
|
|
||||||
|
// Everyone already watching still gets the game.
|
||||||
|
hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null)))
|
||||||
|
watchers.forEach { recorder ->
|
||||||
|
val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed
|
||||||
|
assertEquals("e2e4", move.uci)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun simultaneousJoinsNeverExceedTheLimit() {
|
||||||
|
val hub = hub()
|
||||||
|
val start = CountDownLatch(1)
|
||||||
|
val recorders = List(MAX_SPECTATORS + 10) { Recorder() }
|
||||||
|
val threads = recorders.map { r -> Thread { start.await(); watch(hub.port, r) }.apply { start() } }
|
||||||
|
start.countDown()
|
||||||
|
threads.forEach { it.join() }
|
||||||
|
|
||||||
|
val outcomes = recorders.map { it.next(5_000) }
|
||||||
|
assertEquals(MAX_SPECTATORS, outcomes.count { it is Event.Joined })
|
||||||
|
assertEquals(10, outcomes.count { it == Event.JoinFailed(Failure.FULL) })
|
||||||
|
assertEquals(MAX_SPECTATORS, hub.count.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun joiningMidGameGetsFullStateThenFollowsLive() {
|
||||||
|
val hub = hub()
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
val opening = listOf("e2e4", "e7e5", "g1f3")
|
||||||
|
broadcaster.update(snapshot())
|
||||||
|
broadcaster.update(snapshot(opening, SpectatorClock(290_000, 295_000, PieceColor.BLACK)))
|
||||||
|
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
val welcome = joined(recorder)
|
||||||
|
assertEquals(1, welcome.count)
|
||||||
|
assertEquals(opening, welcome.game.movesUci)
|
||||||
|
assertEquals("Alice", welcome.game.white.name)
|
||||||
|
assertEquals(300, welcome.game.initialSeconds)
|
||||||
|
val clock = welcome.game.clock!!
|
||||||
|
assertEquals(PieceColor.BLACK, clock.running)
|
||||||
|
assertEquals(290_000, clock.whiteMs)
|
||||||
|
assertTrue(clock.blackMs in 290_000..295_000)
|
||||||
|
|
||||||
|
val game = SpectatorGame()
|
||||||
|
assertTrue(game.load(welcome.game))
|
||||||
|
assertEquals(PieceColor.BLACK, game.view!!.board.sideToMove)
|
||||||
|
assertEquals(listOf("e4", "e5", "Nf3"), game.view!!.moveSans)
|
||||||
|
|
||||||
|
broadcaster.update(snapshot(opening + "b8c6", SpectatorClock(290_000, 293_000, PieceColor.WHITE)))
|
||||||
|
val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed
|
||||||
|
assertEquals(4, move.ply)
|
||||||
|
assertEquals(SpectatorGame.Applied.APPLIED, game.onMove(move))
|
||||||
|
assertEquals(PieceColor.WHITE, game.view!!.board.sideToMove)
|
||||||
|
assertEquals("Nc6", game.view!!.moveSans.last())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostLeavingMidGameShowsTheResultThenSaysGoodbye() {
|
||||||
|
val hub = hub()
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
val playing = snapshot(listOf("e2e4"))
|
||||||
|
broadcaster.update(playing)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
joined(recorder)
|
||||||
|
|
||||||
|
broadcaster.close(playing.copy(result = SpectatorResults.leftBy(PieceColor.WHITE)))
|
||||||
|
val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver
|
||||||
|
assertEquals(SpectatorOutcome.LEFT, end.result.outcome)
|
||||||
|
assertEquals(PieceColor.BLACK, end.result.winner)
|
||||||
|
assertEquals(Event.Disconnected(hostClosed = true), recorder.awaitEvent { it is Event.Disconnected })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostDroppingOffIsSeenAsConnectionLost() {
|
||||||
|
val hub = hub()
|
||||||
|
val link = FlakyLink(hub.port)
|
||||||
|
val (_, recorder) = watch(link.port)
|
||||||
|
joined(recorder)
|
||||||
|
|
||||||
|
link.cut()
|
||||||
|
assertEquals(Event.Disconnected(hostClosed = false), recorder.awaitEvent { it is Event.Disconnected })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun wifiSwitchingOffIsDetectedOnBothSides() {
|
||||||
|
val hub = hub()
|
||||||
|
val link = FlakyLink(hub.port)
|
||||||
|
val (_, cutOff) = watch(link.port)
|
||||||
|
val (_, direct) = watch(hub.port)
|
||||||
|
joined(cutOff)
|
||||||
|
joined(direct)
|
||||||
|
awaitCount(hub, 2)
|
||||||
|
|
||||||
|
// No more packets either way, but no connection reset: what a dead Wi-Fi link looks like.
|
||||||
|
link.silent = true
|
||||||
|
|
||||||
|
assertEquals(Event.Disconnected(hostClosed = false), cutOff.awaitEvent { it is Event.Disconnected })
|
||||||
|
awaitCount(hub, 1)
|
||||||
|
// The remaining spectator's counter follows.
|
||||||
|
assertNotNull(direct.awaitMessage { it is SpectatorMessage.Count && it.count == 1 })
|
||||||
|
|
||||||
|
// The spectator who still has a connection keeps watching.
|
||||||
|
hub.publish(snapshot(listOf("d2d4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "d2d4", null)))
|
||||||
|
assertNotNull(direct.awaitMessage { it is SpectatorMessage.MovePlayed })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun spectatorsLeavingFreeTheirSlotsWhileOthersKeepWatching() {
|
||||||
|
val hub = hub()
|
||||||
|
val watchers = List(MAX_SPECTATORS) { watch(hub.port) }
|
||||||
|
watchers.forEach { joined(it.second) }
|
||||||
|
awaitCount(hub, MAX_SPECTATORS)
|
||||||
|
|
||||||
|
watchers.take(5).forEach { it.first.stop() }
|
||||||
|
awaitCount(hub, MAX_SPECTATORS - 5)
|
||||||
|
|
||||||
|
val (_, newcomer) = watch(hub.port)
|
||||||
|
assertEquals(MAX_SPECTATORS - 4, joined(newcomer).count)
|
||||||
|
|
||||||
|
hub.publish(snapshot(listOf("c2c4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "c2c4", null)))
|
||||||
|
(watchers.drop(5).map { it.second } + newcomer).forEach {
|
||||||
|
assertNotNull(it.awaitMessage { m -> m is SpectatorMessage.MovePlayed })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun stalledSpectatorsNeverSlowDownTheHost() {
|
||||||
|
val hub = hub()
|
||||||
|
val link = FlakyLink(hub.port)
|
||||||
|
repeat(5) { joined(watch(link.port).second) }
|
||||||
|
link.silent = true
|
||||||
|
|
||||||
|
val started = System.nanoTime()
|
||||||
|
repeat(2_000) { i ->
|
||||||
|
hub.publish(snapshot(), listOf(SpectatorMessage.Count(i, MAX_SPECTATORS)))
|
||||||
|
}
|
||||||
|
val elapsedMs = (System.nanoTime() - started) / 1_000_000
|
||||||
|
assertTrue("publish took $elapsedMs ms", elapsedMs < 1_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun outdatedSpectatorIsToldToUpdate() {
|
||||||
|
val hub = hub()
|
||||||
|
val (_, recorder) = watch(hub.port, version = 0, minVersion = 0)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.UPDATE_THIS_APP), recorder.next())
|
||||||
|
assertEquals(0, hub.count.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun outdatedHostIsReported() {
|
||||||
|
val hub = hub()
|
||||||
|
val newer = SpectatorProtocol.VERSION + 1
|
||||||
|
val (_, recorder) = watch(hub.port, version = newer, minVersion = newer)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.UPDATE_HOST_APP), recorder.next())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rawOldClientGetsAClearRejectInsteadOfACrash() {
|
||||||
|
val hub = hub()
|
||||||
|
Socket(loopback, hub.port).use { s ->
|
||||||
|
s.soTimeout = 2_000
|
||||||
|
s.getOutputStream().write("{\"type\":\"hello\",\"sv\":0}\n".toByteArray())
|
||||||
|
val reply = BufferedReader(InputStreamReader(s.getInputStream())).readLine()
|
||||||
|
val reject = SpectatorProtocol.decode(reply)!!.message as SpectatorMessage.Reject
|
||||||
|
assertEquals(RejectReason.UPDATE_REQUIRED, reject.reason)
|
||||||
|
assertEquals(SpectatorProtocol.MIN_COMPATIBLE_VERSION, reject.minVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun garbageAndOversizedInputCloseOnlyThatConnection() {
|
||||||
|
val hub = hub()
|
||||||
|
val (_, watcher) = watch(hub.port)
|
||||||
|
joined(watcher)
|
||||||
|
|
||||||
|
for (payload in listOf("hello?\n", "x".repeat(SpectatorProtocol.MAX_CLIENT_LINE_CHARS + 10) + "\n")) {
|
||||||
|
Socket(loopback, hub.port).use { s ->
|
||||||
|
s.soTimeout = 2_000
|
||||||
|
s.getOutputStream().write(payload.toByteArray())
|
||||||
|
// Closed with unread input the host may answer with a reset instead of a clean close.
|
||||||
|
val read = try { s.getInputStream().read() } catch (e: IOException) { -1 }
|
||||||
|
assertEquals(-1, read)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(1, hub.count.value)
|
||||||
|
hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null)))
|
||||||
|
assertNotNull(watcher.awaitMessage { it is SpectatorMessage.MovePlayed })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun silentConnectionThatNeverSaysHelloIsClosed() {
|
||||||
|
val hub = hub()
|
||||||
|
Socket(loopback, hub.port).use { s ->
|
||||||
|
s.soTimeout = 3_000
|
||||||
|
assertEquals(-1, s.getInputStream().read())
|
||||||
|
}
|
||||||
|
assertEquals(0, hub.count.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun noGameYetIsRefused() {
|
||||||
|
val hub = hub(initial = null)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.NO_GAME), recorder.next())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun statusProbeReportsLiveCountWithoutTakingASlot() {
|
||||||
|
val hub = hub()
|
||||||
|
repeat(3) { joined(watch(hub.port).second) }
|
||||||
|
awaitCount(hub, 3)
|
||||||
|
val status = SpectatorProbe.query("127.0.0.1", hub.port)!!
|
||||||
|
assertTrue(status.inGame)
|
||||||
|
assertEquals(3, status.count)
|
||||||
|
assertEquals(MAX_SPECTATORS, status.max)
|
||||||
|
assertEquals(3, hub.count.value)
|
||||||
|
|
||||||
|
hub.publish(snapshot().copy(result = SpectatorResults.interrupted))
|
||||||
|
assertFalse(SpectatorProbe.query("127.0.0.1", hub.port)!!.inGame)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun probeOfAClosedHostIsNull() {
|
||||||
|
val hub = hub()
|
||||||
|
val port = hub.port
|
||||||
|
hub.close()
|
||||||
|
assertEquals(null, SpectatorProbe.query("127.0.0.1", port, timeoutMs = 500))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun resyncSendsAFreshSnapshot() {
|
||||||
|
val hub = hub(snapshot(listOf("e2e4", "c7c5")))
|
||||||
|
val (client, recorder) = watch(hub.port)
|
||||||
|
joined(recorder)
|
||||||
|
client.requestResync()
|
||||||
|
val fresh = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame
|
||||||
|
assertEquals(listOf("e2e4", "c7c5"), fresh.game.movesUci)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rematchReachesSpectatorsAsANewGame() {
|
||||||
|
val hub = hub()
|
||||||
|
val broadcaster = SpectatorBroadcaster(hub)
|
||||||
|
val first = snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4"))
|
||||||
|
broadcaster.update(first)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
joined(recorder)
|
||||||
|
broadcaster.update(first.copy(result = SpectatorResults.of(
|
||||||
|
cc.skysparkle.matewave.engine.GameStatus.CHECKMATE, PieceColor.WHITE, null, null, false
|
||||||
|
)))
|
||||||
|
val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver
|
||||||
|
assertEquals(PieceColor.BLACK, end.result.winner)
|
||||||
|
|
||||||
|
broadcaster.update(snapshot(gameId = "g2"))
|
||||||
|
val next = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame
|
||||||
|
assertEquals("g2", next.game.gameId)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clocksKeepRunningBetweenHostUpdates() {
|
||||||
|
val hub = hub(snapshot(clock = SpectatorClock(60_000, 60_000, PieceColor.WHITE)))
|
||||||
|
Thread.sleep(400)
|
||||||
|
val (_, recorder) = watch(hub.port)
|
||||||
|
val clock = joined(recorder).game.clock!!
|
||||||
|
assertTrue("white ${clock.whiteMs}", clock.whiteMs in 50_000..59_700)
|
||||||
|
assertEquals(60_000, clock.blackMs)
|
||||||
|
val ping = recorder.awaitMessage { it is SpectatorMessage.Ping } as SpectatorMessage.Ping
|
||||||
|
assertTrue(ping.clock!!.whiteMs <= clock.whiteMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun closingTheHubEndsEveryoneAndRefusesNewcomers() {
|
||||||
|
val hub = hub()
|
||||||
|
val recorders = List(3) { watch(hub.port).second }
|
||||||
|
recorders.forEach { joined(it) }
|
||||||
|
val port = hub.port
|
||||||
|
hub.close()
|
||||||
|
recorders.forEach { assertEquals(Event.Disconnected(hostClosed = true), it.awaitEvent { e -> e is Event.Disconnected }) }
|
||||||
|
assertEquals(0, hub.count.value)
|
||||||
|
val (_, late) = watch(port)
|
||||||
|
assertEquals(Event.JoinFailed(Failure.UNREACHABLE), late.next())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A TCP relay that can go silent (dead Wi-Fi) or drop every connection (host gone). */
|
||||||
|
private inner class FlakyLink(target: Int) : Closeable {
|
||||||
|
private val server = ServerSocket(0, 50, loopback)
|
||||||
|
private val sockets = CopyOnWriteArrayList<Socket>()
|
||||||
|
@Volatile var silent = false
|
||||||
|
val port: Int get() = server.localPort
|
||||||
|
|
||||||
|
init {
|
||||||
|
closeables += this
|
||||||
|
Thread {
|
||||||
|
while (!server.isClosed) {
|
||||||
|
val inbound = try { server.accept() } catch (e: IOException) { break }
|
||||||
|
val outbound = Socket(loopback, target)
|
||||||
|
sockets += inbound
|
||||||
|
sockets += outbound
|
||||||
|
pump(inbound, outbound)
|
||||||
|
pump(outbound, inbound)
|
||||||
|
}
|
||||||
|
}.apply { isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pump(from: Socket, to: Socket) = Thread {
|
||||||
|
val buffer = ByteArray(8_192)
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
val n = from.getInputStream().read(buffer)
|
||||||
|
if (n < 0) break
|
||||||
|
if (!silent) to.getOutputStream().write(buffer, 0, n)
|
||||||
|
}
|
||||||
|
} catch (_: IOException) {
|
||||||
|
} finally {
|
||||||
|
runCatching { from.close() }
|
||||||
|
runCatching { to.close() }
|
||||||
|
}
|
||||||
|
}.apply { isDaemon = true }.start()
|
||||||
|
|
||||||
|
fun cut() = sockets.forEach { runCatching { it.close() } }
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
runCatching { server.close() }
|
||||||
|
cut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package cc.skysparkle.matewave
|
||||||
|
|
||||||
|
import cc.skysparkle.matewave.engine.PieceColor
|
||||||
|
import cc.skysparkle.matewave.spectate.MAX_SPECTATORS
|
||||||
|
import cc.skysparkle.matewave.spectate.RejectReason
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorClock
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorMessage
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorOutcome
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorPlayer
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorProtocol
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorResult
|
||||||
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SpectatorProtocolTest {
|
||||||
|
private val clock = SpectatorClock(295_000, 300_000, PieceColor.BLACK)
|
||||||
|
private val snapshot = SpectatorSnapshot(
|
||||||
|
gameId = "g1",
|
||||||
|
white = SpectatorPlayer("u1", "Владимир", 1350),
|
||||||
|
black = SpectatorPlayer("u2", "Bob", 1200),
|
||||||
|
movesUci = listOf("e2e4", "e7e5", "g1f3"),
|
||||||
|
initialSeconds = 300,
|
||||||
|
incrementSeconds = 2,
|
||||||
|
clock = clock
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun roundTrip(message: SpectatorMessage) {
|
||||||
|
val envelope = SpectatorProtocol.decode(SpectatorProtocol.encode(message))
|
||||||
|
assertNotNull(envelope)
|
||||||
|
assertEquals(SpectatorProtocol.VERSION, envelope!!.version)
|
||||||
|
assertEquals(message, envelope.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun hello() = roundTrip(SpectatorMessage.Hello(1))
|
||||||
|
@Test fun query() = roundTrip(SpectatorMessage.StatusQuery)
|
||||||
|
@Test fun pong() = roundTrip(SpectatorMessage.Pong)
|
||||||
|
@Test fun resync() = roundTrip(SpectatorMessage.Resync)
|
||||||
|
@Test fun leave() = roundTrip(SpectatorMessage.Leave)
|
||||||
|
@Test fun welcome() = roundTrip(SpectatorMessage.Welcome(7, MAX_SPECTATORS, snapshot))
|
||||||
|
@Test fun status() = roundTrip(SpectatorMessage.Status(true, 7, MAX_SPECTATORS, 1))
|
||||||
|
@Test fun reject() = roundTrip(SpectatorMessage.Reject(RejectReason.FULL, 1))
|
||||||
|
@Test fun move() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "b8c6", clock))
|
||||||
|
@Test fun moveWithoutClock() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "e7e8q", null))
|
||||||
|
@Test fun count() = roundTrip(SpectatorMessage.Count(3, MAX_SPECTATORS))
|
||||||
|
@Test fun ping() = roundTrip(SpectatorMessage.Ping(clock))
|
||||||
|
@Test fun closing() = roundTrip(SpectatorMessage.Closing)
|
||||||
|
@Test fun newGame() = roundTrip(SpectatorMessage.NewGame(snapshot.copy(movesUci = emptyList(), clock = null)))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun gameOverKeepsWinnerAndDraws() {
|
||||||
|
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.WHITE), clock.copy(running = null)))
|
||||||
|
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.AGREEMENT, null), null))
|
||||||
|
roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.INTERRUPTED, null), null))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun everyMessageCarriesTheSenderVersion() {
|
||||||
|
val line = SpectatorProtocol.encode(SpectatorMessage.Pong, version = 7)
|
||||||
|
assertEquals(7, SpectatorProtocol.decode(line)!!.version)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unknownTypeFromANewerVersionIsSkippedNotFatal() {
|
||||||
|
val envelope = SpectatorProtocol.decode("""{"type":"emote","sv":9,"what":"wave"}""")
|
||||||
|
assertNotNull(envelope)
|
||||||
|
assertEquals(9, envelope!!.version)
|
||||||
|
assertNull(envelope.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unknownOutcomeAndRejectReasonDegradeGracefully() {
|
||||||
|
val end = SpectatorProtocol.decode("""{"type":"end","sv":2,"gid":"g1","result":{"o":"abandoned"}}""")!!.message
|
||||||
|
assertEquals(SpectatorOutcome.UNKNOWN, (end as SpectatorMessage.GameOver).result.outcome)
|
||||||
|
val reject = SpectatorProtocol.decode("""{"type":"reject","sv":2,"reason":"banned","min":2}""")!!.message
|
||||||
|
assertEquals(RejectReason.OTHER, (reject as SpectatorMessage.Reject).reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun malformedInputNeverThrows() {
|
||||||
|
assertNull(SpectatorProtocol.decode("not json"))
|
||||||
|
assertNull(SpectatorProtocol.decode("{}"))
|
||||||
|
assertNull(SpectatorProtocol.decode(""))
|
||||||
|
// Known type with missing fields: skipped like an unknown one.
|
||||||
|
assertNull(SpectatorProtocol.decode("""{"type":"move","sv":1}""")!!.message)
|
||||||
|
assertNull(SpectatorProtocol.decode("""{"type":"welcome","sv":1,"n":1}""")!!.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun oldHelloWithoutMinimumStillParses() {
|
||||||
|
val hello = SpectatorProtocol.decode("""{"type":"hello","sv":1}""")!!.message
|
||||||
|
assertEquals(SpectatorMessage.Hello(1), hello)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clockAdvancesOnlyForTheRunningSide() {
|
||||||
|
val later = clock.advancedBy(1_500)
|
||||||
|
assertEquals(295_000, later.whiteMs)
|
||||||
|
assertEquals(298_500, later.blackMs)
|
||||||
|
assertEquals(0, SpectatorClock(1_000, 5_000, PieceColor.WHITE).advancedBy(9_000).whiteMs)
|
||||||
|
assertEquals(clock.copy(running = null), clock.copy(running = null).advancedBy(5_000))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hugeMoveListIsRejected() {
|
||||||
|
val moves = (1..2_001).joinToString(",") { "\"e2e4\"" }
|
||||||
|
val line = """{"type":"game","sv":1,"game":{"gid":"g","wp":{},"bp":{},"moves":[$moves]}}"""
|
||||||
|
assertNull(SpectatorProtocol.decode(line)!!.message)
|
||||||
|
assertTrue(SpectatorProtocol.MAX_CLIENT_LINE_CHARS < SpectatorProtocol.MAX_HOST_LINE_CHARS)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Partien von Freunden ansehen: bis zu 20 Zuschauer im selben WLAN können eine laufende LAN-Partie im Bereich „Freunde“ verfolgen
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Watch friends' games: up to 20 spectators on the same Wi-Fi can follow a live LAN game from the Friends section
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• 友達の対局を観戦:同じWi-Fiにいる最大20人が「フレンド」から進行中のLAN対局を見られます
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Draugų partijų stebėjimas: iki 20 žiūrovų tame pačiame Wi-Fi tinkle gali sekti vykstančią LAN partiją skiltyje „Draugai“
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• Просмотр партий друзей: до 20 зрителей в той же Wi-Fi сети могут следить за идущей LAN-партией в разделе «Друзья»
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
• 观看好友对局:同一 Wi-Fi 下最多 20 名观众可在“好友”中观看正在进行的局域网对局
|
||||||
Reference in New Issue
Block a user