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:
Claude
2026-08-05 22:37:05 +00:00
parent 4312616efa
commit 487c68419e
54 changed files with 6487 additions and 0 deletions
@@ -0,0 +1,275 @@
package org.prolibertate.games.ui
import androidx.activity.compose.BackHandler
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.GameCategory
import org.prolibertate.games.game.GameDescriptor
import org.prolibertate.games.game.engine.TableConfig
import org.prolibertate.games.net.LobbyController
import org.prolibertate.games.settings.Settings
import org.prolibertate.games.settings.SettingsRepository
import org.prolibertate.games.update.Updater
/** Everything the screens need, assembled once by the activity. */
class AppEnv(
val settingsRepository: SettingsRepository,
val updater: Updater,
val lobby: LobbyController,
val peerId: String,
val requestBluetoothPermissions: () -> Unit,
)
/**
* Where the app currently is.
*
* A hand-rolled stack rather than the navigation library: there are six
* destinations, two of which carry a live [TableConfig], and a typed sealed
* class is both smaller and harder to get wrong than argument encoding.
*/
sealed interface Route {
data object Menu : Route
data object Settings : Route
data class Setup(val gameId: String) : Route
data class Lobby(val gameId: String, val optionsJson: String, val hosting: Boolean) : Route
data class Play(
val gameId: String,
val config: TableConfig,
val hosting: Boolean,
val localSeat: Int,
) : Route
}
@Composable
fun AppRoot(env: AppEnv) {
val settings by env.settingsRepository.settings.collectAsState(initial = Settings())
var stack by remember { mutableStateOf(listOf<Route>(Route.Menu)) }
fun push(route: Route) {
stack = stack + route
}
fun pop() {
if (stack.size > 1) {
// Leaving a lobby or a table tears the networking down with it.
when (stack.last()) {
is Route.Lobby, is Route.Play -> env.lobby.stop()
else -> Unit
}
stack = stack.dropLast(1)
}
}
BackHandler(enabled = stack.size > 1) { pop() }
when (val route = stack.last()) {
is Route.Menu -> MainMenuScreen(
onPickGame = { push(Route.Setup(it.id)) },
onJoinGame = { push(Route.Lobby(gameId = "", optionsJson = "{}", hosting = false)) },
onSettings = { push(Route.Settings) },
)
is Route.Settings -> SettingsScreen(
env = env,
settings = settings,
onBack = { pop() },
)
is Route.Setup -> GameSetupScreen(
descriptor = GameCatalog.byId(route.gameId)!!,
playerName = settings.playerName,
onBack = { pop() },
onPlayOffline = { config -> push(Route.Play(route.gameId, config, true, 0)) },
onHostOnline = { optionsJson ->
push(Route.Lobby(route.gameId, optionsJson, hosting = true))
},
)
is Route.Lobby -> LobbyScreen(
env = env,
route = route,
playerName = settings.playerName,
onBack = { pop() },
onStart = { config, hosting, seat ->
push(Route.Play(config.gameId, config, hosting, seat))
},
)
is Route.Play -> PlayScreen(
env = env,
route = route,
settings = settings,
onExit = { pop() },
)
}
}
// ---------------------------------------------------------------------------
// Main menu
// ---------------------------------------------------------------------------
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainMenuScreen(
onPickGame: (GameDescriptor) -> Unit,
onJoinGame: () -> Unit,
onSettings: () -> Unit,
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Pro Libertate Games") },
actions = { TextButton(onClick = onSettings) { Text("Settings") } },
)
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(horizontal = 12.dp),
) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedButton(onClick = onJoinGame) { Text("Join a game nearby") }
}
// The column count follows the available width, so a phone in
// portrait gets two and a tablet in landscape gets four or more.
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 172.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxSize(),
) {
GameCategory.entries.forEach { category ->
item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
Text(
text = category.label,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 12.dp, bottom = 4.dp),
)
}
items(GameCatalog.byCategory(category)) { game ->
GameTile(game = game, onClick = { onPickGame(game) })
}
}
}
}
}
}
@Composable
private fun GameTile(game: GameDescriptor, onClick: () -> Unit) {
Card(
onClick = onClick,
enabled = game.available,
colors = CardDefaults.cardColors(
containerColor = if (game.available) {
MaterialTheme.colorScheme.surfaceVariant
} else {
MaterialTheme.colorScheme.surface
}
),
modifier = Modifier.fillMaxWidth(),
) {
Column(modifier = Modifier.padding(12.dp)) {
Text(
text = game.title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
)
Text(
text = game.blurb,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 4.dp),
)
Text(
text = if (game.available) {
if (game.minPlayers == game.maxPlayers) {
"${game.minPlayers} players"
} else {
"${game.minPlayers}–${game.maxPlayers} players"
}
} else {
"Coming soon"
},
style = MaterialTheme.typography.labelSmall,
modifier = Modifier.padding(top = 8.dp),
)
}
}
}
// ---------------------------------------------------------------------------
// Shared chrome
// ---------------------------------------------------------------------------
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScreenScaffold(
title: String,
onBack: () -> Unit,
actions: @Composable () -> Unit = {},
content: @Composable (Modifier) -> Unit,
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(title) },
navigationIcon = { TextButton(onClick = onBack) { Text("Back") } },
actions = { actions() },
)
}
) { padding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.background(MaterialTheme.colorScheme.background),
contentAlignment = Alignment.TopStart,
) {
content(Modifier.fillMaxSize().padding(12.dp))
}
}
}
@Composable
fun PrimaryAction(text: String, enabled: Boolean = true, onClick: () -> Unit) {
Button(onClick = onClick, enabled = enabled, modifier = Modifier.fillMaxWidth()) {
Text(text)
}
}
@@ -0,0 +1,240 @@
package org.prolibertate.games.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.GameDescriptor
import org.prolibertate.games.game.engine.PlayerKind
import org.prolibertate.games.game.engine.PlayerSlot
import org.prolibertate.games.game.engine.TableConfig
import org.prolibertate.games.game.euchre.EuchreOptions
import org.prolibertate.games.game.sequence.SequenceOptions
private val setupJson = Json { encodeDefaults = true }
/**
* Choose who is playing and which house rules apply.
*
* Rule variations are per game and live here rather than in a global settings
* screen, because they change what the engine does rather than how it looks.
*/
@Composable
fun GameSetupScreen(
descriptor: GameDescriptor,
playerName: String,
onBack: () -> Unit,
onPlayOffline: (TableConfig) -> Unit,
onHostOnline: (String) -> Unit,
) {
var euchre by remember { mutableStateOf(EuchreOptions()) }
var sequence by remember { mutableStateOf(SequenceOptions()) }
val optionsJson = when (descriptor.id) {
GameCatalog.EUCHRE -> setupJson.encodeToString(euchre)
GameCatalog.SEQUENCE -> setupJson.encodeToString(sequence)
else -> "{}"
}
val seatCount = when (descriptor.id) {
GameCatalog.EUCHRE -> 4
GameCatalog.SEQUENCE -> sequence.playerCount
else -> descriptor.minPlayers
}
ScreenScaffold(title = descriptor.title, onBack = onBack) { modifier ->
Column(
modifier = modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(descriptor.blurb, style = MaterialTheme.typography.bodyMedium)
Divider()
Text("House rules", fontWeight = FontWeight.Bold)
when (descriptor.id) {
GameCatalog.EUCHRE -> EuchreOptionsEditor(euchre) { euchre = it }
GameCatalog.SEQUENCE -> SequenceOptionsEditor(sequence) { sequence = it }
else -> Text("No options yet for this game.")
}
Divider()
Text("Opponents", fontWeight = FontWeight.Bold)
Text(
text = "Play now and every other seat is taken by the computer. Host a game " +
"instead and people can claim those seats as they join — whatever is " +
"still empty when you start stays computer-controlled.",
style = MaterialTheme.typography.bodySmall,
)
PrimaryAction(text = "Play against the computer") {
onPlayOffline(
offlineConfig(descriptor.id, optionsJson, seatCount, playerName)
)
}
PrimaryAction(text = "Host a game for others to join") {
onHostOnline(optionsJson)
}
}
}
}
/** Seat 0 is the local player; the rest start as AI. */
private fun offlineConfig(
gameId: String,
optionsJson: String,
seatCount: Int,
playerName: String,
): TableConfig = TableConfig(
gameId = gameId,
seats = (0 until seatCount).map { seat ->
PlayerSlot(
seat = seat,
name = if (seat == 0) playerName else "Computer $seat",
kind = if (seat == 0) PlayerKind.HUMAN_LOCAL else PlayerKind.AI,
team = teamForSeat(gameId, seat),
)
},
optionsJson = optionsJson,
// Seeded from the clock so consecutive games are not identical.
seed = System.currentTimeMillis(),
)
fun teamForSeat(gameId: String, seat: Int): Int = when (gameId) {
// Partners sit opposite each other.
GameCatalog.EUCHRE -> seat % 2
else -> seat % 2
}
@Composable
private fun EuchreOptionsEditor(options: EuchreOptions, onChange: (EuchreOptions) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
ChipRow(
label = "Deck",
values = listOf(24, 32),
selected = options.deckSize,
display = { "$it cards" },
onSelect = { onChange(options.copy(deckSize = it)) },
)
ChipRow(
label = "Game to",
values = listOf(10, 11, 15),
selected = options.pointsToWin,
display = { "$it points" },
onSelect = { onChange(options.copy(pointsToWin = it)) },
)
ToggleRow(
title = "Stick the dealer",
subtitle = "If everyone passes twice, the dealer must name trump",
checked = options.stickTheDealer,
onChange = { onChange(options.copy(stickTheDealer = it)) },
)
ToggleRow(
title = "Allow going alone",
subtitle = "A maker may sit their partner out for a bigger score",
checked = options.allowGoingAlone,
onChange = { onChange(options.copy(allowGoingAlone = it)) },
)
}
}
@Composable
private fun SequenceOptionsEditor(options: SequenceOptions, onChange: (SequenceOptions) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
ChipRow(
label = "Teams",
values = listOf(2, 3),
selected = options.teamCount,
display = { "$it teams" },
onSelect = { teams ->
// Three teams race to a single sequence; two teams need two.
onChange(options.copy(teamCount = teams, sequencesToWin = if (teams == 3) 1 else 2))
},
)
ChipRow(
label = "Players per team",
values = listOf(1, 2, 3, 4),
selected = options.playersPerTeam,
display = { "$it" },
onSelect = { onChange(options.copy(playersPerTeam = it)) },
)
ChipRow(
label = "Sequences to win",
values = listOf(1, 2, 3),
selected = options.sequencesToWin,
display = { "$it" },
onSelect = { onChange(options.copy(sequencesToWin = it)) },
)
ToggleRow(
title = "Dead card exchange",
subtitle = "Swap a card whose squares are both already taken",
checked = options.deadCardExchange,
onChange = { onChange(options.copy(deadCardExchange = it)) },
)
Text(
text = "${options.playerCount} players in total.",
style = MaterialTheme.typography.bodySmall,
)
}
}
@Composable
private fun <T> ChipRow(
label: String,
values: List<T>,
selected: T,
display: (T) -> String,
onSelect: (T) -> Unit,
) {
Column {
Text(label, style = MaterialTheme.typography.labelLarge)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
values.forEach { value ->
FilterChip(
selected = value == selected,
onClick = { onSelect(value) },
label = { Text(display(value)) },
)
}
}
}
}
@Composable
private fun ToggleRow(
title: String,
subtitle: String,
checked: Boolean,
onChange: (Boolean) -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column(modifier = Modifier.weight(1f).padding(end = 8.dp)) {
Text(title)
Text(subtitle, style = MaterialTheme.typography.bodySmall)
}
Switch(checked = checked, onCheckedChange = onChange)
}
}
@@ -0,0 +1,187 @@
package org.prolibertate.games.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.engine.PlayerKind
import org.prolibertate.games.game.engine.TableConfig
import org.prolibertate.games.net.DiscoveredHost
import org.prolibertate.games.net.LobbyController
/**
* Hosting or joining a table.
*
* A host advertises on Wi-Fi and Bluetooth simultaneously, and the seat list
* does not care which one a given player arrived on.
*/
@Composable
fun LobbyScreen(
env: AppEnv,
route: Route.Lobby,
playerName: String,
onBack: () -> Unit,
onStart: (TableConfig, Boolean, Int) -> Unit,
) {
val state by env.lobby.state.collectAsState()
LaunchedEffect(route) {
env.requestBluetoothPermissions()
if (route.hosting) {
val descriptor = GameCatalog.byId(route.gameId)
val seatCount = descriptor?.let {
if (it.id == GameCatalog.EUCHRE) 4 else it.minPlayers
} ?: 4
env.lobby.startHosting(
gameId = route.gameId,
optionsJson = route.optionsJson,
hostName = playerName,
seatCount = seatCount,
teamOf = { seat -> teamForSeat(route.gameId, seat) },
)
} else {
env.lobby.startDiscovery()
}
}
// Both roles leave for the table the moment the host commits.
LaunchedEffect(state.started) {
val config = state.started ?: return@LaunchedEffect
val seat = if (route.hosting) {
0
} else {
config.seats.firstOrNull { it.peerId == env.peerId }?.seat
?: config.seats.firstOrNull { it.kind == PlayerKind.HUMAN_REMOTE }?.seat
?: 0
}
env.lobby.clearStarted()
onStart(config, route.hosting, seat)
}
val title = if (route.hosting) "Hosting" else "Join a game"
ScreenScaffold(title = title, onBack = onBack) { modifier ->
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(12.dp)) {
val available = env.lobby.availableTransports()
Text(
text = if (available.isEmpty()) {
"No Wi-Fi or Bluetooth available. Turn one on to play with others."
} else {
(if (route.hosting) "Visible over " else "Searching over ") +
available.joinToString(" and ") { it.kind.label } + "."
},
style = MaterialTheme.typography.bodySmall,
)
state.message?.let { Text(it, style = MaterialTheme.typography.bodyMedium) }
Divider()
if (route.hosting) {
HostingBody(env.lobby, state)
} else {
JoiningBody(env, state.discovered, playerName)
}
}
}
}
@Composable
private fun HostingBody(lobby: LobbyController, state: LobbyController.State) {
Text("Seats", fontWeight = FontWeight.Bold)
LazyColumn(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth(),
) {
items(state.seats) { slot ->
Card(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth().padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column {
Text("Seat ${slot.seat} — ${slot.name}")
Text(
text = when (slot.kind) {
PlayerKind.HUMAN_LOCAL -> "You"
PlayerKind.HUMAN_REMOTE -> "Joined"
PlayerKind.AI -> "Computer"
} + " · Team ${slot.team}",
style = MaterialTheme.typography.bodySmall,
)
}
if (slot.kind == PlayerKind.HUMAN_REMOTE) {
TextButton(onClick = {
lobby.setSeatKind(slot.seat, PlayerKind.AI, "Computer ${slot.seat}")
}) { Text("Drop") }
}
}
}
}
}
PrimaryAction(
text = "Start game",
enabled = state.seats.isNotEmpty(),
) {
lobby.startMatch(seed = System.currentTimeMillis())
}
Text(
text = "Any seat still showing Computer will be played by the AI.",
style = MaterialTheme.typography.bodySmall,
)
}
@Composable
private fun JoiningBody(
env: AppEnv,
discovered: List<DiscoveredHost>,
playerName: String,
) {
if (discovered.isEmpty()) {
Text("No games found yet. Make sure the host has started theirs.")
Text(
text = "Bluetooth only shows devices already paired in Android's " +
"Bluetooth settings.",
style = MaterialTheme.typography.bodySmall,
)
return
}
LazyColumn(verticalArrangement = Arrangement.spacedBy(6.dp)) {
items(discovered) { host ->
Card(
modifier = Modifier
.fillMaxWidth()
.clickable { env.lobby.join(host, playerName, env.peerId) }
) {
Column(modifier = Modifier.padding(12.dp)) {
Text(host.name, fontWeight = FontWeight.Bold)
Text(
text = "over ${host.kind.label}",
style = MaterialTheme.typography.bodySmall,
)
}
}
}
}
}
@@ -0,0 +1,104 @@
package org.prolibertate.games.ui
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.euchre.EuchreAi
import org.prolibertate.games.game.euchre.EuchreMove
import org.prolibertate.games.game.euchre.EuchrePhase
import org.prolibertate.games.game.euchre.EuchreRules
import org.prolibertate.games.game.euchre.EuchreState
import org.prolibertate.games.game.sequence.SequenceAi
import org.prolibertate.games.game.sequence.SequenceMove
import org.prolibertate.games.game.sequence.SequenceRules
import org.prolibertate.games.game.sequence.SequenceState
import org.prolibertate.games.net.MatchController
import org.prolibertate.games.settings.Settings
import org.prolibertate.games.ui.game.EuchreScreen
import org.prolibertate.games.ui.game.SequenceScreen
/**
* Builds the match for the chosen game and hands it to that game's screen.
*
* Offline play and hosting are the same thing here — an offline game is simply
* a host with no connections — so there is one path through this code whether
* or not anyone else is at the table.
*/
@Composable
fun PlayScreen(
env: AppEnv,
route: Route.Play,
settings: Settings,
onExit: () -> Unit,
) {
val scope = rememberCoroutineScope()
val role = if (route.hosting) MatchController.Role.HOST else MatchController.Role.CLIENT
when (route.gameId) {
GameCatalog.EUCHRE -> {
val controller = remember(route) {
MatchController<EuchreState, EuchreMove>(
rules = EuchreRules,
ai = EuchreAi(),
config = route.config,
scope = scope,
role = role,
localSeats = setOf(route.localSeat),
primarySeat = route.localSeat,
// A scored hand pauses on screen, then the next one is dealt.
advanceIdle = { state ->
if (state.phase == EuchrePhase.HAND_OVER) {
EuchreRules.nextHand(state)
} else {
null
}
},
aiThinkingMillis = { settings.scaled(700L) },
)
}
StartMatch(env, controller, route)
EuchreScreen(controller = controller, localSeat = route.localSeat, onExit = onExit)
}
GameCatalog.SEQUENCE -> {
val controller = remember(route) {
MatchController<SequenceState, SequenceMove>(
rules = SequenceRules,
ai = SequenceAi(),
config = route.config,
scope = scope,
role = role,
localSeats = setOf(route.localSeat),
primarySeat = route.localSeat,
aiThinkingMillis = { settings.scaled(700L) },
)
}
StartMatch(env, controller, route)
SequenceScreen(controller = controller, localSeat = route.localSeat, onExit = onExit)
}
else -> Text("That game isn't playable yet.")
}
}
@Composable
private fun <S : Any, M : Any> StartMatch(
env: AppEnv,
controller: MatchController<S, M>,
route: Route.Play,
) {
LaunchedEffect(controller) {
if (route.hosting) {
controller.startAsHost(env.lobby.hostConnections)
} else {
env.lobby.clientConnection?.let { controller.startAsClient(it) }
}
}
DisposableEffect(controller) {
onDispose { controller.close() }
}
}
@@ -0,0 +1,180 @@
package org.prolibertate.games.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import org.prolibertate.games.settings.Settings
import org.prolibertate.games.update.Updater
@Composable
fun SettingsScreen(
env: AppEnv,
settings: Settings,
onBack: () -> Unit,
) {
val scope = rememberCoroutineScope()
var name by remember(settings.playerName) { mutableStateOf(settings.playerName) }
var updateStatus by remember { mutableStateOf<String?>(null) }
var pendingRelease by remember { mutableStateOf<Updater.Release?>(null) }
ScreenScaffold(title = "Settings", onBack = onBack) { modifier ->
Column(
modifier = modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
SettingRow(
title = "Sound",
subtitle = "Card and chip effects",
) {
Switch(
checked = settings.soundEnabled,
onCheckedChange = { enabled ->
scope.launch { env.settingsRepository.setSoundEnabled(enabled) }
},
)
}
Divider()
Column {
Text("Animation speed", fontWeight = FontWeight.Bold)
Text(
text = "${"%.1f".format(settings.animationSpeed)}× — " +
"how quickly cards move and the computer takes its turn",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = settings.animationSpeed,
onValueChange = { speed ->
scope.launch { env.settingsRepository.setAnimationSpeed(speed) }
},
valueRange = Settings.MIN_SPEED..Settings.MAX_SPEED,
// Half-step increments across 0.5x-2.0x.
steps = 5,
)
}
Divider()
Column {
Text("Your name", fontWeight = FontWeight.Bold)
Text(
"Shown to other players in a lobby",
style = MaterialTheme.typography.bodySmall,
)
OutlinedTextField(
value = name,
onValueChange = { entered ->
name = entered
scope.launch { env.settingsRepository.setPlayerName(entered) }
},
singleLine = true,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
)
}
Divider()
Text("Updates", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium)
Text(
text = "Installed: v${env.updater.installedVersionName()}. Updates come from " +
"the latest release published on the project's main branch.",
style = MaterialTheme.typography.bodySmall,
)
SettingRow(
title = "Check on launch",
subtitle = "Look for a newer release when the app starts",
) {
Switch(
checked = settings.checkForUpdatesOnLaunch,
onCheckedChange = { enabled ->
scope.launch { env.settingsRepository.setCheckForUpdatesOnLaunch(enabled) }
},
)
}
PrimaryAction(text = "Check for updates now") {
scope.launch {
updateStatus = "Checking…"
when (val result = env.updater.check()) {
is Updater.Result.UpToDate -> {
updateStatus = "You're on the latest version."
pendingRelease = null
}
is Updater.Result.Available -> {
pendingRelease = result.release
updateStatus = "Version ${result.release.tag} is available."
}
is Updater.Result.Failed -> {
updateStatus = result.reason
pendingRelease = null
}
}
}
}
pendingRelease?.let { release ->
PrimaryAction(text = "Download and install ${release.tag}") {
scope.launch {
if (env.updater.needsInstallPermission()) {
updateStatus =
"Allow installs from this app, then tap install again."
env.updater.requestInstallPermission()
} else {
updateStatus = "Downloading…"
val error = env.updater.downloadAndInstall(release)
updateStatus = error ?: "Handing over to the installer…"
}
}
}
}
updateStatus?.let {
Text(it, style = MaterialTheme.typography.bodyMedium)
}
}
}
}
@Composable
private fun SettingRow(
title: String,
subtitle: String,
control: @Composable () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column(modifier = Modifier.weight(1f)) {
Text(title, fontWeight = FontWeight.Bold)
Text(subtitle, style = MaterialTheme.typography.bodySmall)
}
control()
}
}
@@ -0,0 +1,106 @@
package org.prolibertate.games.ui.common
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
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.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.ui.theme.CardBlack
import org.prolibertate.games.ui.theme.CardRed
/**
* A playing card.
*
* Sized by width with a fixed 5:7 aspect ratio so the same composable works
* from a phone in portrait up to a tablet in landscape — callers pass a width
* derived from the space they actually have rather than a hard-coded dp.
*/
@Composable
fun PlayingCardView(
card: Card,
modifier: Modifier = Modifier,
width: Dp = 64.dp,
selected: Boolean = false,
enabled: Boolean = true,
onClick: (() -> Unit)? = null,
) {
val ink = if (card.suit.isRed) CardRed else CardBlack
Box(
modifier = modifier
.width(width)
.aspectRatio(CARD_ASPECT)
.clip(RoundedCornerShape(width * 0.12f))
.background(Color.White)
.border(
width = if (selected) 3.dp else 1.dp,
color = if (selected) MaterialTheme.colorScheme.primary else Color(0x33000000),
shape = RoundedCornerShape(width * 0.12f),
)
.alpha(if (enabled) 1f else 0.45f)
.then(
if (onClick != null && enabled) Modifier.clickable { onClick() } else Modifier
),
contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = card.rank.short,
color = ink,
fontWeight = FontWeight.Bold,
fontSize = (width.value * 0.34f).sp,
)
Text(
text = card.suit.symbol,
color = ink,
fontSize = (width.value * 0.34f).sp,
)
}
}
}
/** The back of a card, for hands you are not allowed to see. */
@Composable
fun CardBackView(
modifier: Modifier = Modifier,
width: Dp = 64.dp,
) {
Box(
modifier = modifier
.width(width)
.aspectRatio(CARD_ASPECT)
.clip(RoundedCornerShape(width * 0.12f))
.background(MaterialTheme.colorScheme.primary)
.border(1.dp, Color(0x33000000), RoundedCornerShape(width * 0.12f)),
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(width * 0.12f)
.border(1.dp, Color(0x55FFFFFF), RoundedCornerShape(width * 0.06f)),
)
}
}
const val CARD_ASPECT = 5f / 7f
@@ -0,0 +1,282 @@
package org.prolibertate.games.ui.game
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.prolibertate.games.game.euchre.CallTrump
import org.prolibertate.games.game.euchre.Discard
import org.prolibertate.games.game.euchre.EuchreMove
import org.prolibertate.games.game.euchre.EuchrePhase
import org.prolibertate.games.game.euchre.EuchreState
import org.prolibertate.games.game.euchre.OrderUp
import org.prolibertate.games.game.euchre.Pass
import org.prolibertate.games.game.euchre.PlayCard
import org.prolibertate.games.game.euchre.teamOf
import org.prolibertate.games.net.MatchController
import org.prolibertate.games.ui.PrimaryAction
import org.prolibertate.games.ui.ScreenScaffold
import org.prolibertate.games.ui.common.CardBackView
import org.prolibertate.games.ui.common.PlayingCardView
import org.prolibertate.games.ui.theme.FeltGreenDark
/**
* The Euchre table.
*
* Layout is driven by the space available rather than by orientation checks:
* card width is a fraction of the narrower dimension, so the same code lays out
* sensibly on a phone held either way and on a tablet.
*/
@Composable
fun EuchreScreen(
controller: MatchController<EuchreState, EuchreMove>,
localSeat: Int,
onExit: () -> Unit,
) {
val state by controller.state.collectAsState()
val legal by controller.legalMoves.collectAsState()
val notice by controller.notice.collectAsState()
val current = state
if (current == null) {
ScreenScaffold(title = "Euchre", onBack = onExit) { modifier ->
Box(modifier, contentAlignment = Alignment.Center) { Text("Dealing…") }
}
return
}
ScreenScaffold(title = "Euchre", onBack = onExit) { modifier ->
BoxWithConstraints(modifier = modifier) {
val compact = maxWidth < 600.dp
val cardWidth = (minOf(maxWidth, maxHeight) * if (compact) 0.17f else 0.12f)
.coerceIn(48.dp, 104.dp)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ScoreBar(current, localSeat)
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.background(FeltGreenDark),
contentAlignment = Alignment.Center,
) {
TrickArea(current, cardWidth)
}
notice?.let {
Text(it, style = MaterialTheme.typography.bodySmall)
}
when (current.phase) {
EuchrePhase.BID_ROUND_1,
EuchrePhase.BID_ROUND_2,
-> BiddingControls(current, legal) { controller.submit(it) }
EuchrePhase.HAND_OVER -> Text(
text = current.log.lastOrNull().orEmpty(),
style = MaterialTheme.typography.titleSmall,
)
EuchrePhase.GAME_OVER -> {
Text("Game over.", fontWeight = FontWeight.Bold)
PrimaryAction(text = "Back to the menu") { onExit() }
}
else -> Unit
}
HandRow(
state = current,
seat = localSeat,
legal = legal,
cardWidth = cardWidth,
onPlay = { controller.submit(it) },
)
}
}
}
}
@Composable
private fun ScoreBar(state: EuchreState, localSeat: Int) {
val myTeam = teamOf(localSeat)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column {
Text("Us ${state.scores[myTeam]} — Them ${state.scores[1 - myTeam]}",
fontWeight = FontWeight.Bold)
val tricks = state.tricksWon.filterIndexed { seat, _ -> teamOf(seat) == myTeam }.sum()
Text("Tricks this hand: $tricks", style = MaterialTheme.typography.bodySmall)
}
Column(horizontalAlignment = Alignment.End) {
Text(
text = state.trump?.let { "Trump ${it.symbol}" } ?: "Bidding",
fontWeight = FontWeight.Bold,
)
state.aloneSeat?.let {
Text("Seat $it is alone", style = MaterialTheme.typography.bodySmall)
}
}
}
}
@Composable
private fun TrickArea(state: EuchreState, cardWidth: androidx.compose.ui.unit.Dp) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
state.upCard?.let { up ->
Text("Turned up", color = MaterialTheme.colorScheme.onPrimary)
PlayingCardView(card = up, width = cardWidth)
}
if (state.trick.isNotEmpty()) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
state.trick.forEach { played ->
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Seat ${played.seat}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
PlayingCardView(card = played.card, width = cardWidth)
}
}
}
} else if (state.upCard == null && state.phase == EuchrePhase.PLAYING) {
Text("Lead a card", color = MaterialTheme.colorScheme.onPrimary)
}
// Opponents' hands are only ever card counts on this device.
Row(
modifier = Modifier.padding(top = 12.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
state.handCounts.forEachIndexed { seat, count ->
if (seat != state.turn) return@forEachIndexed
repeat(count.coerceAtMost(5)) {
CardBackView(width = cardWidth * 0.4f)
}
}
}
}
}
@Composable
private fun BiddingControls(
state: EuchreState,
legal: List<EuchreMove>,
onMove: (EuchreMove) -> Unit,
) {
if (legal.isEmpty()) {
Text("Waiting for seat ${state.turn}…")
return
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = if (state.phase == EuchrePhase.BID_ROUND_1) {
"Order up ${state.upCard?.label.orEmpty()}?"
} else {
"Name a suit"
},
fontWeight = FontWeight.Bold,
)
Row(
modifier = Modifier.horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
legal.forEach { move ->
val label = when (move) {
is Pass -> "Pass"
is OrderUp -> if (move.alone) "Order up alone" else "Order up"
is CallTrump -> {
(if (move.alone) "Alone " else "") + move.suit.symbol
}
is Discard -> "Discard ${move.card.label}"
is PlayCard -> move.card.label
}
if (move is Pass) {
OutlinedButton(onClick = { onMove(move) }) { Text(label) }
} else {
Button(onClick = { onMove(move) }) { Text(label) }
}
}
}
}
}
@Composable
private fun HandRow(
state: EuchreState,
seat: Int,
legal: List<EuchreMove>,
cardWidth: androidx.compose.ui.unit.Dp,
onPlay: (EuchreMove) -> Unit,
) {
val hand = state.hands.getOrNull(seat).orEmpty()
val playable = legal.filterIsInstance<PlayCard>().map { it.card }.toSet()
val discardable = legal.filterIsInstance<Discard>().map { it.card }.toSet()
Column {
Text(
text = when {
discardable.isNotEmpty() -> "Discard a card"
playable.isNotEmpty() -> "Your turn"
else -> "Your hand"
},
style = MaterialTheme.typography.labelLarge,
)
Row(
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
if (hand.isEmpty()) {
Box(modifier = Modifier.size(cardWidth)) {
Text("—", style = MaterialTheme.typography.bodySmall)
}
}
hand.forEach { card ->
val canPlay = card in playable
val canDiscard = card in discardable
PlayingCardView(
card = card,
width = cardWidth,
enabled = canPlay || canDiscard,
onClick = {
when {
canDiscard -> onPlay(Discard(card))
canPlay -> onPlay(PlayCard(card))
}
},
)
}
}
}
}
@@ -0,0 +1,296 @@
package org.prolibertate.games.ui.game
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.sequence.BOARD_SIZE
import org.prolibertate.games.game.sequence.ExchangeDeadCard
import org.prolibertate.games.game.sequence.NO_TEAM
import org.prolibertate.games.game.sequence.PlaceChip
import org.prolibertate.games.game.sequence.RemoveChip
import org.prolibertate.games.game.sequence.SequenceBoard
import org.prolibertate.games.game.sequence.SequenceMove
import org.prolibertate.games.game.sequence.SequenceState
import org.prolibertate.games.net.MatchController
import org.prolibertate.games.ui.PrimaryAction
import org.prolibertate.games.ui.ScreenScaffold
import org.prolibertate.games.ui.theme.FeltGreenDark
import org.prolibertate.games.ui.theme.TeamColours
/**
* The Sequence board.
*
* The board is always square and always fits: its side is the smaller of the
* available width and the height left over after the hand, so rotating the
* device rescales rather than clipping.
*/
@Composable
fun SequenceScreen(
controller: MatchController<SequenceState, SequenceMove>,
localSeat: Int,
onExit: () -> Unit,
) {
val state by controller.state.collectAsState()
val legal by controller.legalMoves.collectAsState()
var selected by remember { mutableStateOf<Card?>(null) }
val current = state
if (current == null) {
ScreenScaffold(title = "Sequence", onBack = onExit) { modifier ->
Box(modifier, contentAlignment = Alignment.Center) { Text("Dealing…") }
}
return
}
// Squares the selected card could legally claim or clear.
val placements = legal.filterIsInstance<PlaceChip>().filter { it.card == selected }
val removals = legal.filterIsInstance<RemoveChip>().filter { it.card == selected }
val highlighted = (placements.map { it.cell } + removals.map { it.cell }).toSet()
ScreenScaffold(title = "Sequence", onBack = onExit) { modifier ->
BoxWithConstraints(modifier = modifier) {
val wide = maxWidth > maxHeight
val boardSide = if (wide) {
minOf(maxWidth * 0.62f, maxHeight)
} else {
minOf(maxWidth, maxHeight * 0.68f)
}
val cell = boardSide / BOARD_SIZE
val board: @Composable () -> Unit = {
BoardGrid(
state = current,
cellSize = cell,
highlighted = highlighted,
onCellTap = { index ->
val placement = placements.firstOrNull { it.cell == index }
val removal = removals.firstOrNull { it.cell == index }
when {
placement != null -> {
controller.submit(placement)
selected = null
}
removal != null -> {
controller.submit(removal)
selected = null
}
}
},
)
}
val side: @Composable () -> Unit = {
Column(
modifier = Modifier.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
StatusPanel(current, localSeat)
HandStrip(
state = current,
seat = localSeat,
legal = legal,
selected = selected,
cardWidth = (cell * 1.4f).coerceIn(40.dp, 84.dp),
onSelect = { card -> selected = if (selected == card) null else card },
onExchange = { controller.submit(it); selected = null },
)
if (controller.finished.collectAsState().value) {
PrimaryAction("Back to the menu") { onExit() }
}
}
}
if (wide) {
Row(modifier = Modifier.fillMaxSize()) {
board()
Box(modifier = Modifier.weight(1f)) { side() }
}
} else {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
board()
side()
}
}
}
}
}
@Composable
private fun BoardGrid(
state: SequenceState,
cellSize: Dp,
highlighted: Set<Int>,
onCellTap: (Int) -> Unit,
) {
Column(modifier = Modifier.background(FeltGreenDark)) {
for (row in 0 until BOARD_SIZE) {
Row {
for (col in 0 until BOARD_SIZE) {
val index = SequenceBoard.cellAt(row, col)
BoardCell(
card = SequenceBoard.cells[index],
team = state.chips[index],
locked = state.locked[index],
highlighted = index in highlighted,
size = cellSize,
onClick = { onCellTap(index) },
)
}
}
}
}
}
@Composable
private fun BoardCell(
card: Card?,
team: Int,
locked: Boolean,
highlighted: Boolean,
size: Dp,
onClick: () -> Unit,
) {
Box(
modifier = Modifier
.size(size)
.padding(0.5.dp)
.clip(RoundedCornerShape(size * 0.12f))
.background(if (card == null) MaterialTheme.colorScheme.primary else Color.White)
.border(
width = if (highlighted) 2.dp else 0.5.dp,
color = if (highlighted) MaterialTheme.colorScheme.tertiary else Color(0x33000000),
shape = RoundedCornerShape(size * 0.12f),
)
.clickable { onClick() },
contentAlignment = Alignment.Center,
) {
if (card == null) {
// A free corner, wild for every team.
Text("★", fontSize = (size.value * 0.45f).sp, color = Color.White)
} else {
Text(
text = card.label,
fontSize = (size.value * 0.26f).sp,
color = if (card.suit.isRed) Color(0xFFB3261E) else Color.Black,
)
}
if (team != NO_TEAM) {
Box(
modifier = Modifier
.size(size * 0.62f)
.clip(CircleShape)
.background(TeamColours.getOrElse(team) { Color.Gray })
.border(
width = if (locked) 2.dp else 0.dp,
color = if (locked) Color.White else Color.Transparent,
shape = CircleShape,
)
)
}
}
}
@Composable
private fun StatusPanel(state: SequenceState, localSeat: Int) {
val myTeam = state.teamOf(localSeat)
Column {
Text("You are team $myTeam", fontWeight = FontWeight.Bold)
state.sequencesByTeam.forEachIndexed { team, count ->
Text(
text = "Team $team: $count / ${state.options.sequencesToWin} sequences",
style = MaterialTheme.typography.bodySmall,
color = TeamColours.getOrElse(team) { Color.Gray },
)
}
state.winner?.let {
Text("Team $it wins!", fontWeight = FontWeight.Bold)
} ?: Text(
text = if (state.turn == localSeat) "Your turn" else "Seat ${state.turn} is playing…",
style = MaterialTheme.typography.bodyMedium,
)
}
}
@Composable
private fun HandStrip(
state: SequenceState,
seat: Int,
legal: List<SequenceMove>,
selected: Card?,
cardWidth: Dp,
onSelect: (Card) -> Unit,
onExchange: (ExchangeDeadCard) -> Unit,
) {
val hand = state.hands.getOrNull(seat).orEmpty()
val playable = legal.mapNotNull {
when (it) {
is PlaceChip -> it.card
is RemoveChip -> it.card
is ExchangeDeadCard -> it.card
}
}.toSet()
val exchanges = legal.filterIsInstance<ExchangeDeadCard>().associateBy { it.card }
Column {
Text("Your hand", style = MaterialTheme.typography.labelLarge)
Row(
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
hand.forEach { card ->
org.prolibertate.games.ui.common.PlayingCardView(
card = card,
width = cardWidth,
selected = card == selected,
enabled = card in playable,
onClick = {
val dead = exchanges[card]
if (dead != null) onExchange(dead) else onSelect(card)
},
)
}
}
selected?.let {
Text(
text = "Tap a highlighted square to play ${it.label}.",
style = MaterialTheme.typography.bodySmall,
)
}
}
}
@@ -0,0 +1,50 @@
package org.prolibertate.games.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
/** Card-table green, which the board and table surfaces are drawn on. */
val FeltGreen = Color(0xFF1B5E20)
val FeltGreenDark = Color(0xFF0B3D12)
val Parchment = Color(0xFFF4EFE4)
val CardRed = Color(0xFFB3261E)
val CardBlack = Color(0xFF1C1B1F)
val TeamColours: List<Color> = listOf(
Color(0xFF1565C0), // blue
Color(0xFFC62828), // red
Color(0xFF2E7D32), // green, only used with three teams
)
private val DarkColours = darkColorScheme(
primary = Color(0xFF7BC67E),
onPrimary = Color(0xFF00390A),
secondary = Color(0xFFB9CCB4),
background = Color(0xFF10140F),
surface = Color(0xFF1A1F18),
surfaceVariant = Color(0xFF2A2F27),
)
private val LightColours = lightColorScheme(
primary = FeltGreen,
onPrimary = Color.White,
secondary = Color(0xFF52634F),
background = Parchment,
surface = Color(0xFFFBF8F1),
surfaceVariant = Color(0xFFE0E4D8),
)
@Composable
fun ProLibertateTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit,
) {
MaterialTheme(
colorScheme = if (darkTheme) DarkColours else LightColours,
content = content,
)
}