Add app shell with Euchre and Sequence, LAN/Bluetooth play
First vertical slice: the whole shell plus two games playable end to end, so every layer is exercised before the other nine games are built on it. Games - Euchre: bowers, ordering up, dealer discard, going alone, stick the dealer, and full scoring. Rule variants (deck size, points to win, stick the dealer, going alone) are toggles in game setup. - Sequence: two-eyed and one-eyed jacks, free corners, locked sequences, the shared-chip limit, and dead-card exchange. Teams, players per team and the sequence target are toggles. - The board layout in SequenceBoard is generated, not the commercial board — it holds every structural property the rules need, but does not match a physical board. Documented in docs/RULES-sequence.md. Multiplayer - One transport abstraction over newline-delimited JSON, implemented twice: LAN via NSD discovery and TCP, Bluetooth via Classic RFCOMM. A lobby advertises on both at once, so a table can mix them. - Host-authoritative: clients send move intents, the host re-validates every one against the rules, and each client receives a state redacted for its own seat so hidden information never crosses the wire. - Seats start as AI and are handed to people as they join, which is what makes any mix of humans and AI work without a separate code path. Shell - Main menu lists all eleven games; the nine without engines are marked coming soon and are driven entirely by GameCatalog. - Settings: sound, animation speed (one multiplier drives card movement and AI thinking time), and OTA updates from the latest GitHub release. - Layouts measure available space rather than assuming an orientation. The game package is free of Android types, so the rules engines and AI run under plain JUnit; 43 tests cover ranking, following suit, scoring, sequence detection, redaction, wire round-trips and full random and AI playthroughs. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015qjfMiPUDshdKEUa6vxqzN
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
package org.prolibertate.games.net
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.BluetoothAdapter
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.BluetoothServerSocket
|
||||
import android.bluetooth.BluetoothSocket
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Bluetooth play over Classic RFCOMM.
|
||||
*
|
||||
* RFCOMM rather than BLE: this is a sustained, ordered, two-way stream of small
|
||||
* messages, which is exactly what a serial profile is for. BLE would mean
|
||||
* chunking everything into 20-byte GATT writes for no benefit.
|
||||
*
|
||||
* Discovery is limited to *paired* devices. Pair the two devices once in
|
||||
* Android's Bluetooth settings and they will see each other here; scanning for
|
||||
* unpaired devices needs a foreground scan plus location permission on older
|
||||
* releases and is not worth the friction for a game lobby.
|
||||
*/
|
||||
class BluetoothTransport(private val context: Context) : Transport {
|
||||
|
||||
override val kind: TransportKind = TransportKind.BLUETOOTH
|
||||
|
||||
private val serviceUuid: UUID = UUID.fromString(RFCOMM_UUID)
|
||||
|
||||
private val adapter: BluetoothAdapter?
|
||||
get() = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
|
||||
|
||||
private var serverSocket: BluetoothServerSocket? = null
|
||||
|
||||
override fun isAvailable(): Boolean = adapter?.isEnabled == true && hasConnectPermission()
|
||||
|
||||
/**
|
||||
* Android 12 replaced the blanket BLUETOOTH permission with BLUETOOTH_CONNECT.
|
||||
* Below 31 the manifest permission is granted at install time.
|
||||
*/
|
||||
fun hasConnectPermission(): Boolean =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
android.Manifest.permission.BLUETOOTH_CONNECT,
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
true
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Hosting
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
override fun host(displayName: String, scope: CoroutineScope): Flow<Connection> = callbackFlow {
|
||||
val bluetooth = adapter
|
||||
if (bluetooth == null || !hasConnectPermission()) {
|
||||
close()
|
||||
return@callbackFlow
|
||||
}
|
||||
|
||||
val server = runCatching {
|
||||
bluetooth.listenUsingRfcommWithServiceRecord(SERVICE_NAME, serviceUuid)
|
||||
}.getOrNull()
|
||||
if (server == null) {
|
||||
close()
|
||||
return@callbackFlow
|
||||
}
|
||||
serverSocket = server
|
||||
|
||||
val acceptJob = scope.launch(Dispatchers.IO) {
|
||||
while (isActive) {
|
||||
val socket: BluetoothSocket = runCatching { server.accept() }.getOrNull() ?: break
|
||||
val connection = StreamConnection(
|
||||
peerId = runCatching { socket.remoteDevice?.address }.getOrNull() ?: "bt",
|
||||
kind = TransportKind.BLUETOOTH,
|
||||
input = socket.inputStream,
|
||||
output = socket.outputStream,
|
||||
scope = scope,
|
||||
onClosed = { runCatching { socket.close() } },
|
||||
)
|
||||
trySend(connection)
|
||||
}
|
||||
}
|
||||
|
||||
awaitClose {
|
||||
acceptJob.cancel()
|
||||
runCatching { server.close() }
|
||||
serverSocket = null
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Discovery
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Paired devices are re-published on a slow poll: there is no callback for
|
||||
* "a device became reachable", and a host that is not listening simply
|
||||
* refuses the connection when joined.
|
||||
*/
|
||||
@SuppressLint("MissingPermission")
|
||||
override fun discover(scope: CoroutineScope): Flow<List<DiscoveredHost>> = callbackFlow {
|
||||
if (!hasConnectPermission()) {
|
||||
trySend(emptyList())
|
||||
close()
|
||||
return@callbackFlow
|
||||
}
|
||||
|
||||
val pollJob = scope.launch {
|
||||
while (isActive) {
|
||||
val bonded = runCatching { adapter?.bondedDevices.orEmpty() }.getOrDefault(emptySet())
|
||||
trySend(
|
||||
bonded.map { device ->
|
||||
DiscoveredHost(
|
||||
id = "bt:${device.address}",
|
||||
name = runCatching { device.name }.getOrNull() ?: device.address,
|
||||
kind = TransportKind.BLUETOOTH,
|
||||
address = device.address,
|
||||
)
|
||||
}
|
||||
)
|
||||
delay(POLL_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
awaitClose { pollJob.cancel() }
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Joining
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
override suspend fun join(host: DiscoveredHost, scope: CoroutineScope): Connection =
|
||||
withContext(Dispatchers.IO) {
|
||||
val bluetooth = requireNotNull(adapter) { "No Bluetooth adapter" }
|
||||
require(hasConnectPermission()) { "Bluetooth permission not granted" }
|
||||
|
||||
val device = bluetooth.getRemoteDevice(host.address)
|
||||
// Discovery is expensive and slows down a connect attempt sharply.
|
||||
runCatching { bluetooth.cancelDiscovery() }
|
||||
|
||||
val socket = device.createRfcommSocketToServiceRecord(serviceUuid)
|
||||
socket.connect()
|
||||
StreamConnection(
|
||||
peerId = host.id,
|
||||
kind = TransportKind.BLUETOOTH,
|
||||
input = socket.inputStream,
|
||||
output = socket.outputStream,
|
||||
scope = scope,
|
||||
onClosed = { runCatching { socket.close() } },
|
||||
)
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
runCatching { serverSocket?.close() }
|
||||
serverSocket = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val POLL_INTERVAL_MS = 4_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package org.prolibertate.games.net
|
||||
|
||||
import android.content.Context
|
||||
import android.net.nsd.NsdManager
|
||||
import android.net.nsd.NsdServiceInfo
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.util.Collections
|
||||
|
||||
/**
|
||||
* LAN play: mDNS service discovery to find the host, then a plain TCP socket
|
||||
* per client.
|
||||
*
|
||||
* NSD is used rather than a UDP broadcast ping because it works across the
|
||||
* Wi-Fi isolation settings most home routers ship with, and because Android
|
||||
* gives us the resolver for free.
|
||||
*/
|
||||
class LanTransport(private val context: Context) : Transport {
|
||||
|
||||
override val kind: TransportKind = TransportKind.LAN
|
||||
|
||||
private val nsdManager: NsdManager
|
||||
get() = context.getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
|
||||
private var serverSocket: ServerSocket? = null
|
||||
private var registrationListener: NsdManager.RegistrationListener? = null
|
||||
private var discoveryListener: NsdManager.DiscoveryListener? = null
|
||||
|
||||
override fun isAvailable(): Boolean = true
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Hosting
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
override fun host(displayName: String, scope: CoroutineScope): Flow<Connection> = callbackFlow {
|
||||
// Port 0 lets the OS pick a free port, which is then advertised.
|
||||
val server = ServerSocket(0)
|
||||
serverSocket = server
|
||||
|
||||
val serviceInfo = NsdServiceInfo().apply {
|
||||
serviceName = "$SERVICE_NAME @ $displayName"
|
||||
serviceType = SERVICE_TYPE
|
||||
port = server.localPort
|
||||
}
|
||||
val listener = object : NsdManager.RegistrationListener {
|
||||
override fun onServiceRegistered(info: NsdServiceInfo) = Unit
|
||||
override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) = Unit
|
||||
override fun onServiceUnregistered(info: NsdServiceInfo) = Unit
|
||||
override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) = Unit
|
||||
}
|
||||
registrationListener = listener
|
||||
runCatching {
|
||||
nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||
}
|
||||
|
||||
val acceptJob = scope.launch(Dispatchers.IO) {
|
||||
while (isActive && !server.isClosed) {
|
||||
val socket = runCatching { server.accept() }.getOrNull() ?: break
|
||||
socket.tcpNoDelay = true
|
||||
val connection = StreamConnection(
|
||||
peerId = socket.inetAddress?.hostAddress ?: "unknown",
|
||||
kind = TransportKind.LAN,
|
||||
input = socket.getInputStream(),
|
||||
output = socket.getOutputStream(),
|
||||
scope = scope,
|
||||
onClosed = { runCatching { socket.close() } },
|
||||
)
|
||||
trySend(connection)
|
||||
}
|
||||
}
|
||||
|
||||
awaitClose {
|
||||
acceptJob.cancel()
|
||||
stopAdvertising()
|
||||
runCatching { server.close() }
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Discovery
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
override fun discover(scope: CoroutineScope): Flow<List<DiscoveredHost>> = callbackFlow {
|
||||
val found = Collections.synchronizedMap(linkedMapOf<String, DiscoveredHost>())
|
||||
|
||||
fun publish() {
|
||||
trySend(synchronized(found) { found.values.toList() })
|
||||
}
|
||||
|
||||
// Resolutions are queued one at a time: NsdManager rejects concurrent
|
||||
// resolve calls with FAILURE_ALREADY_ACTIVE on many devices.
|
||||
val pending = ArrayDeque<NsdServiceInfo>()
|
||||
var resolving = false
|
||||
|
||||
fun resolveNext() {
|
||||
if (resolving) return
|
||||
val next = synchronized(pending) { pending.removeFirstOrNull() } ?: return
|
||||
resolving = true
|
||||
val resolveListener = object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {
|
||||
resolving = false
|
||||
resolveNext()
|
||||
}
|
||||
|
||||
override fun onServiceResolved(info: NsdServiceInfo) {
|
||||
val address = info.host?.hostAddress
|
||||
if (address != null) {
|
||||
val host = DiscoveredHost(
|
||||
id = "lan:$address:${info.port}",
|
||||
name = info.serviceName.substringAfter("@ ").trim()
|
||||
.ifBlank { info.serviceName },
|
||||
kind = TransportKind.LAN,
|
||||
address = address,
|
||||
port = info.port,
|
||||
)
|
||||
synchronized(found) { found[host.id] = host }
|
||||
publish()
|
||||
}
|
||||
resolving = false
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
runCatching { nsdManager.resolveService(next, resolveListener) }
|
||||
.onFailure {
|
||||
resolving = false
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
|
||||
val listener = object : NsdManager.DiscoveryListener {
|
||||
override fun onDiscoveryStarted(serviceType: String) = Unit
|
||||
|
||||
override fun onServiceFound(info: NsdServiceInfo) {
|
||||
if (info.serviceType?.contains("plgames") != true) return
|
||||
synchronized(pending) { pending.addLast(info) }
|
||||
resolveNext()
|
||||
}
|
||||
|
||||
override fun onServiceLost(info: NsdServiceInfo) {
|
||||
synchronized(found) {
|
||||
val key = found.entries.firstOrNull { it.value.name == info.serviceName }?.key
|
||||
if (key != null) found.remove(key)
|
||||
}
|
||||
publish()
|
||||
}
|
||||
|
||||
override fun onDiscoveryStopped(serviceType: String) = Unit
|
||||
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
|
||||
close()
|
||||
}
|
||||
|
||||
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
|
||||
}
|
||||
discoveryListener = listener
|
||||
|
||||
publish()
|
||||
runCatching {
|
||||
nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||
}.onFailure { close() }
|
||||
|
||||
awaitClose { stopDiscovery() }
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Joining
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
override suspend fun join(host: DiscoveredHost, scope: CoroutineScope): Connection =
|
||||
withContext(Dispatchers.IO) {
|
||||
val socket = Socket()
|
||||
socket.connect(InetSocketAddress(host.address, host.port), CONNECT_TIMEOUT_MS)
|
||||
socket.tcpNoDelay = true
|
||||
StreamConnection(
|
||||
peerId = host.id,
|
||||
kind = TransportKind.LAN,
|
||||
input = socket.getInputStream(),
|
||||
output = socket.getOutputStream(),
|
||||
scope = scope,
|
||||
onClosed = { runCatching { socket.close() } },
|
||||
)
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private fun stopAdvertising() {
|
||||
registrationListener?.let { runCatching { nsdManager.unregisterService(it) } }
|
||||
registrationListener = null
|
||||
}
|
||||
|
||||
private fun stopDiscovery() {
|
||||
discoveryListener?.let { runCatching { nsdManager.stopServiceDiscovery(it) } }
|
||||
discoveryListener = null
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
stopAdvertising()
|
||||
stopDiscovery()
|
||||
runCatching { serverSocket?.close() }
|
||||
serverSocket = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val CONNECT_TIMEOUT_MS = 8_000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package org.prolibertate.games.net
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import org.prolibertate.games.game.engine.PlayerKind
|
||||
import org.prolibertate.games.game.engine.PlayerSlot
|
||||
import org.prolibertate.games.game.engine.TableConfig
|
||||
|
||||
/**
|
||||
* The pre-game lobby.
|
||||
*
|
||||
* The host advertises on every available transport at once, so a table can mix
|
||||
* players arriving over Wi-Fi with players arriving over Bluetooth — from the
|
||||
* seat list's point of view a peer is a peer. Seats start filled with AI and
|
||||
* are handed over to people as they join, which is what makes "AI, humans, or
|
||||
* any combination" fall out for free: whatever is still AI when the host
|
||||
* starts, stays AI.
|
||||
*/
|
||||
class LobbyController(
|
||||
context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
) {
|
||||
|
||||
data class State(
|
||||
val hosting: Boolean = false,
|
||||
val joining: Boolean = false,
|
||||
val connected: Boolean = false,
|
||||
val gameId: String? = null,
|
||||
val optionsJson: String = "{}",
|
||||
val hostName: String = "",
|
||||
val seats: List<PlayerSlot> = emptyList(),
|
||||
val discovered: List<DiscoveredHost> = emptyList(),
|
||||
val message: String? = null,
|
||||
val started: TableConfig? = null,
|
||||
)
|
||||
|
||||
private val lan = LanTransport(context)
|
||||
private val bluetooth = BluetoothTransport(context)
|
||||
|
||||
val transports: List<Transport> = listOf(lan, bluetooth)
|
||||
|
||||
private val _state = MutableStateFlow(State())
|
||||
val state: StateFlow<State> = _state.asStateFlow()
|
||||
|
||||
/** Peer id -> live connection, for every seated remote player. */
|
||||
private val connections = linkedMapOf<String, Connection>()
|
||||
private var clientLink: Connection? = null
|
||||
private val jobs = mutableListOf<Job>()
|
||||
|
||||
val hostConnections: List<Connection> get() = connections.values.toList()
|
||||
val clientConnection: Connection? get() = clientLink
|
||||
|
||||
fun availableTransports(): List<Transport> = transports.filter { it.isAvailable() }
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Hosting
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
fun startHosting(
|
||||
gameId: String,
|
||||
optionsJson: String,
|
||||
hostName: String,
|
||||
seatCount: Int,
|
||||
teamOf: (Int) -> Int,
|
||||
) {
|
||||
stop()
|
||||
val seats = (0 until seatCount).map { seat ->
|
||||
PlayerSlot(
|
||||
seat = seat,
|
||||
name = if (seat == 0) hostName else "Computer $seat",
|
||||
kind = if (seat == 0) PlayerKind.HUMAN_LOCAL else PlayerKind.AI,
|
||||
team = teamOf(seat),
|
||||
)
|
||||
}
|
||||
_state.value = State(
|
||||
hosting = true,
|
||||
gameId = gameId,
|
||||
optionsJson = optionsJson,
|
||||
hostName = hostName,
|
||||
seats = seats,
|
||||
message = "Waiting for players…",
|
||||
)
|
||||
|
||||
for (transport in availableTransports()) {
|
||||
jobs += scope.launch {
|
||||
transport.host(hostName, scope).collect { connection ->
|
||||
onClientConnected(connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onClientConnected(connection: Connection) {
|
||||
jobs += scope.launch {
|
||||
connection.incoming.collect { message ->
|
||||
if (message !is Hello) return@collect
|
||||
if (message.protocol != PROTOCOL_VERSION) {
|
||||
connection.send(
|
||||
Welcome(
|
||||
hostName = _state.value.hostName,
|
||||
gameId = _state.value.gameId.orEmpty(),
|
||||
accepted = false,
|
||||
reason = "Different app version — update both devices.",
|
||||
)
|
||||
)
|
||||
connection.close()
|
||||
return@collect
|
||||
}
|
||||
seatPlayer(connection, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Gives an arriving player the first seat still held by the computer. */
|
||||
private suspend fun seatPlayer(connection: Connection, hello: Hello) {
|
||||
val current = _state.value
|
||||
val seats = current.seats.toMutableList()
|
||||
val index = seats.indexOfFirst { it.kind == PlayerKind.AI }
|
||||
if (index < 0) {
|
||||
connection.send(
|
||||
Welcome(current.hostName, current.gameId.orEmpty(), accepted = false, reason = "The table is full.")
|
||||
)
|
||||
connection.close()
|
||||
return
|
||||
}
|
||||
|
||||
seats[index] = seats[index].copy(
|
||||
name = hello.displayName,
|
||||
kind = PlayerKind.HUMAN_REMOTE,
|
||||
peerId = connection.peerId,
|
||||
)
|
||||
connections[connection.peerId] = connection
|
||||
_state.value = current.copy(
|
||||
seats = seats,
|
||||
message = "${hello.displayName} joined over ${connection.kind.label}.",
|
||||
)
|
||||
|
||||
connection.send(Welcome(current.hostName, current.gameId.orEmpty(), accepted = true))
|
||||
broadcastLobby()
|
||||
}
|
||||
|
||||
private suspend fun broadcastLobby() {
|
||||
val current = _state.value
|
||||
val update = LobbyUpdate(
|
||||
gameId = current.gameId.orEmpty(),
|
||||
seats = current.seats,
|
||||
optionsJson = current.optionsJson,
|
||||
hostName = current.hostName,
|
||||
)
|
||||
connections.values.forEach { it.send(update) }
|
||||
}
|
||||
|
||||
/** Host: lock the table in and tell everyone to build the same match. */
|
||||
fun startMatch(seed: Long): TableConfig {
|
||||
val current = _state.value
|
||||
val config = TableConfig(
|
||||
gameId = current.gameId.orEmpty(),
|
||||
seats = current.seats,
|
||||
optionsJson = current.optionsJson,
|
||||
seed = seed,
|
||||
)
|
||||
scope.launch { connections.values.forEach { it.send(StartGame(config)) } }
|
||||
_state.value = current.copy(started = config)
|
||||
return config
|
||||
}
|
||||
|
||||
/** Replaces a seat's occupant — used by the host to swap a person for AI. */
|
||||
fun setSeatKind(seat: Int, kind: PlayerKind, name: String? = null) {
|
||||
val current = _state.value
|
||||
val seats = current.seats.toMutableList()
|
||||
if (seat !in seats.indices) return
|
||||
seats[seat] = seats[seat].copy(
|
||||
kind = kind,
|
||||
name = name ?: seats[seat].name,
|
||||
peerId = if (kind == PlayerKind.AI) null else seats[seat].peerId,
|
||||
)
|
||||
_state.value = current.copy(seats = seats)
|
||||
scope.launch { broadcastLobby() }
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Joining
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
fun startDiscovery() {
|
||||
stop()
|
||||
_state.value = State(joining = true, message = "Looking for games…")
|
||||
for (transport in availableTransports()) {
|
||||
jobs += scope.launch {
|
||||
transport.discover(scope).collect { hosts ->
|
||||
val others = _state.value.discovered.filter { it.kind != transport.kind }
|
||||
_state.value = _state.value.copy(discovered = others + hosts)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun join(host: DiscoveredHost, displayName: String, peerId: String) {
|
||||
jobs += scope.launch {
|
||||
_state.value = _state.value.copy(message = "Connecting to ${host.name}…")
|
||||
val transport = transports.firstOrNull { it.kind == host.kind } ?: return@launch
|
||||
val connection = runCatching { transport.join(host, scope) }.getOrElse { error ->
|
||||
_state.value = _state.value.copy(message = "Couldn't connect: ${error.message}")
|
||||
return@launch
|
||||
}
|
||||
clientLink = connection
|
||||
|
||||
launch {
|
||||
connection.incoming.collect { message ->
|
||||
when (message) {
|
||||
is Welcome -> _state.value = if (message.accepted) {
|
||||
_state.value.copy(
|
||||
connected = true,
|
||||
gameId = message.gameId,
|
||||
hostName = message.hostName,
|
||||
message = "Joined ${message.hostName}. Waiting for the host to start…",
|
||||
)
|
||||
} else {
|
||||
_state.value.copy(message = message.reason ?: "The host declined.")
|
||||
}
|
||||
|
||||
is LobbyUpdate -> _state.value = _state.value.copy(
|
||||
seats = message.seats,
|
||||
gameId = message.gameId,
|
||||
optionsJson = message.optionsJson,
|
||||
hostName = message.hostName,
|
||||
)
|
||||
|
||||
is StartGame -> _state.value = _state.value.copy(started = message.config)
|
||||
|
||||
is Bye -> _state.value =
|
||||
_state.value.copy(connected = false, message = "The host left.")
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
connection.send(Hello(peerId = peerId, displayName = displayName))
|
||||
}
|
||||
}
|
||||
|
||||
fun clearStarted() {
|
||||
_state.value = _state.value.copy(started = null)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
jobs.forEach { it.cancel() }
|
||||
jobs.clear()
|
||||
connections.values.forEach { runCatching { it.close() } }
|
||||
connections.clear()
|
||||
runCatching { clientLink?.close() }
|
||||
clientLink = null
|
||||
transports.forEach { runCatching { it.stop() } }
|
||||
_state.value = State()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package org.prolibertate.games.net
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import org.prolibertate.games.game.engine.GameAi
|
||||
import org.prolibertate.games.game.engine.GameRules
|
||||
import org.prolibertate.games.game.engine.PlayerKind
|
||||
import org.prolibertate.games.game.engine.TableConfig
|
||||
|
||||
/**
|
||||
* Drives one match, in either of two roles.
|
||||
*
|
||||
* As HOST it owns the authoritative state: it validates every move (local, AI
|
||||
* or remote), advances the game, and pushes each participant a view redacted
|
||||
* for their seat. As CLIENT it holds only what the host has sent and turns
|
||||
* local input into [MoveIntent]s.
|
||||
*
|
||||
* A purely offline game against AI is just a host with no connections, so
|
||||
* there is only one code path to get right.
|
||||
*/
|
||||
class MatchController<S : Any, M : Any>(
|
||||
private val rules: GameRules<S, M>,
|
||||
private val ai: GameAi<S, M>,
|
||||
private val config: TableConfig,
|
||||
private val scope: CoroutineScope,
|
||||
val role: Role,
|
||||
/** Seats played by a person on this device. */
|
||||
private val localSeats: Set<Int>,
|
||||
/** The local player's primary seat, used to pick the view to render. */
|
||||
val primarySeat: Int,
|
||||
/**
|
||||
* Advances a state that nobody is waiting on — Euchre's gap between a
|
||||
* scored hand and the next deal. Returning null means the game is over.
|
||||
*/
|
||||
private val advanceIdle: (S) -> S? = { null },
|
||||
/** Scaled by the animation-speed setting so the table paces itself. */
|
||||
private val aiThinkingMillis: () -> Long = { 700L },
|
||||
) {
|
||||
|
||||
enum class Role { HOST, CLIENT }
|
||||
|
||||
private val _state = MutableStateFlow<S?>(null)
|
||||
|
||||
/** What the local player should see: redacted on the host, as-sent on a client. */
|
||||
val state: StateFlow<S?> = _state.asStateFlow()
|
||||
|
||||
private val _legalMoves = MutableStateFlow<List<M>>(emptyList())
|
||||
val legalMoves: StateFlow<List<M>> = _legalMoves.asStateFlow()
|
||||
|
||||
private val _finished = MutableStateFlow(false)
|
||||
val finished: StateFlow<Boolean> = _finished.asStateFlow()
|
||||
|
||||
private val _notice = MutableStateFlow<String?>(null)
|
||||
val notice: StateFlow<String?> = _notice.asStateFlow()
|
||||
|
||||
/** Host only: the true state. Clients never see this. */
|
||||
private var authoritative: S? = null
|
||||
private val lock = Mutex()
|
||||
private var sequence = 0
|
||||
|
||||
private val peers = mutableMapOf<String, Connection>()
|
||||
private var hostLink: Connection? = null
|
||||
|
||||
private val seatKinds: Map<Int, PlayerKind> =
|
||||
config.seats.associate { it.seat to it.kind }
|
||||
private val seatPeers: Map<Int, String?> =
|
||||
config.seats.associate { it.seat to it.peerId }
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Start-up
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/** Host: begin the match and start pushing state to [clients]. */
|
||||
fun startAsHost(clients: List<Connection>) {
|
||||
check(role == Role.HOST) { "Not hosting" }
|
||||
clients.forEach { connection ->
|
||||
peers[connection.peerId] = connection
|
||||
scope.launch {
|
||||
connection.incoming.collect { message -> onHostMessage(connection, message) }
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
lock.withLock {
|
||||
authoritative = rules.initialState(config)
|
||||
publish()
|
||||
}
|
||||
driveIdleSeats()
|
||||
}
|
||||
}
|
||||
|
||||
/** Client: render whatever arrives from [link]. */
|
||||
fun startAsClient(link: Connection) {
|
||||
check(role == Role.CLIENT) { "Not a client" }
|
||||
hostLink = link
|
||||
scope.launch {
|
||||
link.incoming.collect { message ->
|
||||
when (message) {
|
||||
is StateSync -> {
|
||||
_state.value = rules.decodeState(message.stateJson)
|
||||
_legalMoves.value = message.legalMoves.map { rules.decodeMove(it) }
|
||||
_finished.value = _state.value?.let { rules.isFinished(it) } ?: false
|
||||
}
|
||||
|
||||
is Rejected -> _notice.value = message.reason
|
||||
is Bye -> _notice.value = "The host left the game."
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Input
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/** Called by the UI when the local player commits to a move. */
|
||||
fun submit(move: M) {
|
||||
scope.launch {
|
||||
when (role) {
|
||||
Role.HOST -> applyIfLegal(primarySeatOnClock(), move)
|
||||
Role.CLIENT -> hostLink?.send(MoveIntent(rules.encodeMove(move)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun primarySeatOnClock(): Int {
|
||||
val current = authoritative?.let { rules.currentSeat(it) }
|
||||
// With several local seats (pass-and-play or AI fill), the seat on the
|
||||
// clock is the one submitting, provided it is actually ours.
|
||||
return if (current != null && current in localSeats) current else primarySeat
|
||||
}
|
||||
|
||||
private suspend fun onHostMessage(connection: Connection, message: NetMessage) {
|
||||
if (message !is MoveIntent) return
|
||||
val seat = seatPeers.entries.firstOrNull { it.value == connection.peerId }?.key
|
||||
if (seat == null) {
|
||||
connection.send(Rejected("You are not seated at this table."))
|
||||
return
|
||||
}
|
||||
val move = runCatching { rules.decodeMove(message.moveJson) }.getOrNull()
|
||||
if (move == null) {
|
||||
connection.send(Rejected("Unreadable move."))
|
||||
return
|
||||
}
|
||||
applyIfLegal(seat, move)
|
||||
}
|
||||
|
||||
/**
|
||||
* The single choke point where a move becomes real. Everything — local
|
||||
* taps, AI picks and anything arriving over the wire — lands here and is
|
||||
* re-checked against the rules.
|
||||
*/
|
||||
private suspend fun applyIfLegal(seat: Int, move: M) {
|
||||
lock.withLock {
|
||||
val current = authoritative ?: return
|
||||
if (rules.currentSeat(current) != seat) {
|
||||
seatPeers[seat]?.let { peers[it]?.send(Rejected("It is not your turn.")) }
|
||||
return
|
||||
}
|
||||
if (move !in rules.legalMoves(current, seat)) {
|
||||
seatPeers[seat]?.let { peers[it]?.send(Rejected("That move is not legal.")) }
|
||||
return
|
||||
}
|
||||
authoritative = rules.applyMove(current, seat, move)
|
||||
publish()
|
||||
}
|
||||
driveIdleSeats()
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Host loop
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Plays out every seat the humans are not responsible for, then advances
|
||||
* through any state nobody is waiting on, until a person is on the clock.
|
||||
*/
|
||||
private suspend fun driveIdleSeats() {
|
||||
while (true) {
|
||||
val current = lock.withLock { authoritative } ?: return
|
||||
if (rules.isFinished(current)) {
|
||||
_finished.value = true
|
||||
return
|
||||
}
|
||||
|
||||
val seat = rules.currentSeat(current)
|
||||
if (seat == null) {
|
||||
// Nobody on the clock: a hand has been scored, or the game ended.
|
||||
delay(aiThinkingMillis() * 2)
|
||||
val advanced = advanceIdle(current)
|
||||
if (advanced == null) {
|
||||
_finished.value = true
|
||||
return
|
||||
}
|
||||
lock.withLock {
|
||||
authoritative = advanced
|
||||
publish()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (seatKinds[seat] != PlayerKind.AI) return // a person's turn
|
||||
|
||||
delay(aiThinkingMillis())
|
||||
val chosen = lock.withLock {
|
||||
val live = authoritative ?: return
|
||||
if (rules.currentSeat(live) != seat) return@withLock null
|
||||
val legal = rules.legalMoves(live, seat)
|
||||
if (legal.isEmpty()) return@withLock null
|
||||
val move = ai.chooseMove(live, seat, legal)
|
||||
authoritative = rules.applyMove(live, seat, move)
|
||||
publish()
|
||||
move
|
||||
}
|
||||
if (chosen == null) return
|
||||
}
|
||||
}
|
||||
|
||||
/** Pushes the local view and every remote seat's view. Call under [lock]. */
|
||||
private suspend fun publish() {
|
||||
val current = authoritative ?: return
|
||||
sequence++
|
||||
|
||||
_state.value = rules.viewFor(current, primarySeat)
|
||||
_legalMoves.value = if (rules.currentSeat(current) in localSeats) {
|
||||
rules.legalMoves(current, rules.currentSeat(current)!!)
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
_finished.value = rules.isFinished(current)
|
||||
|
||||
for (slot in config.seats) {
|
||||
val peerId = slot.peerId ?: continue
|
||||
val connection = peers[peerId] ?: continue
|
||||
val seatView = rules.viewFor(current, slot.seat)
|
||||
val moves = if (rules.currentSeat(current) == slot.seat) {
|
||||
rules.legalMoves(current, slot.seat).map { rules.encodeMove(it) }
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
connection.send(
|
||||
StateSync(
|
||||
seq = sequence,
|
||||
yourSeat = slot.seat,
|
||||
stateJson = rules.encodeState(seatView),
|
||||
legalMoves = moves,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
peers.values.forEach { runCatching { it.close() } }
|
||||
peers.clear()
|
||||
runCatching { hostLink?.close() }
|
||||
hostLink = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package org.prolibertate.games.net
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.prolibertate.games.game.engine.PlayerSlot
|
||||
import org.prolibertate.games.game.engine.TableConfig
|
||||
|
||||
/**
|
||||
* The wire protocol, shared by the LAN and Bluetooth transports.
|
||||
*
|
||||
* The host is authoritative: clients send [MoveIntent] and render whatever
|
||||
* [StateSync] tells them. Nothing is trusted from a client beyond "I would like
|
||||
* to make this move", which the host re-validates against the rules before it
|
||||
* takes effect. Each client is sent a state redacted for its own seat, so an
|
||||
* opponent's hand is never transmitted in the first place.
|
||||
*/
|
||||
const val PROTOCOL_VERSION = 1
|
||||
|
||||
/** Service type advertised over mDNS, and the RFCOMM service name. */
|
||||
const val SERVICE_TYPE = "_plgames._tcp"
|
||||
const val SERVICE_NAME = "ProLibertateGames"
|
||||
|
||||
/** Fixed RFCOMM UUID. Both ends must agree; this is ours. */
|
||||
const val RFCOMM_UUID = "8f1d5a20-3a4e-4b26-9d31-6c0d2f7a91b4"
|
||||
|
||||
val protocolJson: Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
classDiscriminator = "t"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
sealed interface NetMessage
|
||||
|
||||
/** First message a joining client sends. */
|
||||
@Serializable
|
||||
@SerialName("hello")
|
||||
data class Hello(
|
||||
val peerId: String,
|
||||
val displayName: String,
|
||||
val protocol: Int = PROTOCOL_VERSION,
|
||||
) : NetMessage
|
||||
|
||||
/** Host's reply, or a refusal if the lobby is full or the versions differ. */
|
||||
@Serializable
|
||||
@SerialName("welcome")
|
||||
data class Welcome(
|
||||
val hostName: String,
|
||||
val gameId: String,
|
||||
val accepted: Boolean,
|
||||
val reason: String? = null,
|
||||
) : NetMessage
|
||||
|
||||
/** Broadcast whenever the seat list or options change. */
|
||||
@Serializable
|
||||
@SerialName("lobby")
|
||||
data class LobbyUpdate(
|
||||
val gameId: String,
|
||||
val seats: List<PlayerSlot>,
|
||||
val optionsJson: String,
|
||||
val hostName: String,
|
||||
) : NetMessage
|
||||
|
||||
/** Host starts the match; everyone builds the same initial state from this. */
|
||||
@Serializable
|
||||
@SerialName("start")
|
||||
data class StartGame(val config: TableConfig) : NetMessage
|
||||
|
||||
/** A client's redacted view of the authoritative state. */
|
||||
@Serializable
|
||||
@SerialName("state")
|
||||
data class StateSync(
|
||||
val seq: Int,
|
||||
val yourSeat: Int,
|
||||
val stateJson: String,
|
||||
/** Encoded moves this seat may currently make. Empty when it is not its turn. */
|
||||
val legalMoves: List<String>,
|
||||
) : NetMessage
|
||||
|
||||
/** A client asking to play a move. The host validates it. */
|
||||
@Serializable
|
||||
@SerialName("intent")
|
||||
data class MoveIntent(val moveJson: String) : NetMessage
|
||||
|
||||
@Serializable
|
||||
@SerialName("rejected")
|
||||
data class Rejected(val reason: String) : NetMessage
|
||||
|
||||
@Serializable
|
||||
@SerialName("bye")
|
||||
data object Bye : NetMessage
|
||||
@@ -0,0 +1,137 @@
|
||||
package org.prolibertate.games.net
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.BufferedWriter
|
||||
import java.io.Closeable
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
enum class TransportKind(val label: String) {
|
||||
LAN("Wi-Fi"),
|
||||
BLUETOOTH("Bluetooth"),
|
||||
}
|
||||
|
||||
/**
|
||||
* A host someone could join, found by one of the transports. [address] is
|
||||
* transport-specific: an IP for LAN, a MAC for Bluetooth.
|
||||
*/
|
||||
data class DiscoveredHost(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val kind: TransportKind,
|
||||
val address: String,
|
||||
val port: Int = 0,
|
||||
)
|
||||
|
||||
/**
|
||||
* One peer-to-peer link carrying [NetMessage]s.
|
||||
*
|
||||
* Both transports end up with a plain pair of streams, so the framing and
|
||||
* serialisation live here once rather than twice.
|
||||
*/
|
||||
interface Connection : Closeable {
|
||||
val peerId: String
|
||||
val kind: TransportKind
|
||||
val incoming: SharedFlow<NetMessage>
|
||||
suspend fun send(message: NetMessage)
|
||||
val isOpen: Boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Newline-delimited JSON over a stream pair.
|
||||
*
|
||||
* Line framing keeps this debuggable — you can watch a session with netcat —
|
||||
* and JSON payloads never contain a raw newline, so the framing is safe.
|
||||
*/
|
||||
class StreamConnection(
|
||||
override val peerId: String,
|
||||
override val kind: TransportKind,
|
||||
private val input: InputStream,
|
||||
private val output: OutputStream,
|
||||
private val scope: CoroutineScope,
|
||||
private val onClosed: (StreamConnection) -> Unit = {},
|
||||
) : Connection {
|
||||
|
||||
private val reader: BufferedReader = input.bufferedReader()
|
||||
private val writer: BufferedWriter = output.bufferedWriter()
|
||||
private val closed = AtomicBoolean(false)
|
||||
|
||||
private val _incoming = MutableSharedFlow<NetMessage>(replay = 0, extraBufferCapacity = 64)
|
||||
override val incoming: SharedFlow<NetMessage> = _incoming
|
||||
|
||||
override val isOpen: Boolean get() = !closed.get()
|
||||
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
while (isActive && !closed.get()) {
|
||||
val line = reader.readLine() ?: break
|
||||
if (line.isBlank()) continue
|
||||
val message = runCatching {
|
||||
protocolJson.decodeFromString<NetMessage>(line)
|
||||
}.getOrNull() ?: continue // ignore anything we can't parse
|
||||
_incoming.emit(message)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// A dropped link is normal: someone walked out of range or
|
||||
// closed the app. Fall through to close().
|
||||
} finally {
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun send(message: NetMessage) {
|
||||
if (closed.get()) return
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
writer.write(protocolJson.encodeToString<NetMessage>(message))
|
||||
writer.newLine()
|
||||
writer.flush()
|
||||
} catch (_: Exception) {
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (!closed.compareAndSet(false, true)) return
|
||||
runCatching { reader.close() }
|
||||
runCatching { writer.close() }
|
||||
runCatching { input.close() }
|
||||
runCatching { output.close() }
|
||||
onClosed(this)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Discovery and connection setup. Everything after the handshake is the same
|
||||
* for both transports, which is what lets a lobby accept players over Wi-Fi and
|
||||
* Bluetooth at the same time.
|
||||
*/
|
||||
interface Transport {
|
||||
|
||||
val kind: TransportKind
|
||||
|
||||
/** Whether the radio exists and is usable right now. */
|
||||
fun isAvailable(): Boolean
|
||||
|
||||
/** Starts advertising and emits each client that connects. */
|
||||
fun host(displayName: String, scope: CoroutineScope): Flow<Connection>
|
||||
|
||||
/** Emits the current list of visible hosts as it changes. */
|
||||
fun discover(scope: CoroutineScope): Flow<List<DiscoveredHost>>
|
||||
|
||||
suspend fun join(host: DiscoveredHost, scope: CoroutineScope): Connection
|
||||
|
||||
fun stop()
|
||||
}
|
||||
Reference in New Issue
Block a user