Add Kaiser, Crazy 8s and Wizard

Three more card games, engine to screen.

Kaiser: 32-card prairie trick-taking with bidding, the five of hearts
worth five and the three of spades costing three. Bidding is capped at
ten because ten is all a hand can be worth, and a losing score gives the
game a floor — without one a table that keeps bidding and going down
never reaches a result.

Crazy 8s: eights are wild and name the suit in force, which is why the
table states that suit in words rather than leaving it to be read off
the pile. Blocked rounds are scored rather than hanging.

Wizard: the 60-card deck, one more card dealt each round until the pack
runs out, bid your tricks exactly. The shared card model gains WIZARD
and JESTER ranks, so every ordinary deck now builds from Rank.standard
rather than walking the whole enum.

Also fixes a lobby bug this would have hit: hosting seated the
catalogue minimum rather than the table the host had just set up, so a
six-handed game would have been rejected by its own rules engine.

164 engine tests pass locally.
This commit is contained in:
Claude
2026-08-06 10:21:23 +00:00
parent f5a2626196
commit fb70396d09
26 changed files with 4504 additions and 24 deletions
@@ -30,12 +30,18 @@ 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.crazyeights.CrazyEightsOptions
import org.prolibertate.games.game.euchre.EuchreOptions
import org.prolibertate.games.game.golf.GolfOptions
import org.prolibertate.games.game.kaiser.KaiserOptions
import org.prolibertate.games.game.president.PresidentOptions
import org.prolibertate.games.game.sequence.SequenceOptions
import org.prolibertate.games.game.wizard.WizardOptions
private val setupJson = Json { encodeDefaults = true }
private val setupJson = Json {
encodeDefaults = true
ignoreUnknownKeys = true
}
/**
* Choose who is playing and which house rules apply.
@@ -55,21 +61,21 @@ fun GameSetupScreen(
var sequence by remember { mutableStateOf(SequenceOptions()) }
var president by remember { mutableStateOf(PresidentOptions()) }
var golf by remember { mutableStateOf(GolfOptions()) }
var kaiser by remember { mutableStateOf(KaiserOptions()) }
var crazyEights by remember { mutableStateOf(CrazyEightsOptions()) }
var wizard by remember { mutableStateOf(WizardOptions()) }
val optionsJson = when (descriptor.id) {
GameCatalog.EUCHRE -> setupJson.encodeToString(euchre)
GameCatalog.SEQUENCE -> setupJson.encodeToString(sequence)
GameCatalog.PRESIDENT -> setupJson.encodeToString(president)
GameCatalog.GOLF -> setupJson.encodeToString(golf)
GameCatalog.KAISER -> setupJson.encodeToString(kaiser)
GameCatalog.CRAZY_EIGHTS -> setupJson.encodeToString(crazyEights)
GameCatalog.WIZARD -> setupJson.encodeToString(wizard)
else -> "{}"
}
val seatCount = when (descriptor.id) {
GameCatalog.EUCHRE -> 4
GameCatalog.SEQUENCE -> sequence.playerCount
GameCatalog.PRESIDENT -> president.playerCount
GameCatalog.GOLF -> golf.playerCount
else -> descriptor.minPlayers
}
val seatCount = seatCountFor(descriptor.id, optionsJson)
ScreenScaffold(title = descriptor.title, onBack = onBack) { modifier ->
Column(
@@ -86,6 +92,12 @@ fun GameSetupScreen(
GameCatalog.SEQUENCE -> SequenceOptionsEditor(sequence) { sequence = it }
GameCatalog.PRESIDENT -> PresidentOptionsEditor(president) { president = it }
GameCatalog.GOLF -> GolfOptionsEditor(golf) { golf = it }
GameCatalog.KAISER -> KaiserOptionsEditor(kaiser) { kaiser = it }
GameCatalog.CRAZY_EIGHTS -> CrazyEightsOptionsEditor(crazyEights) {
crazyEights = it
}
GameCatalog.WIZARD -> WizardOptionsEditor(wizard) { wizard = it }
else -> Text("No options yet for this game.")
}
@@ -131,9 +143,41 @@ private fun offlineConfig(
seed = System.currentTimeMillis(),
)
/**
* How many seats a table needs, read back out of the options the host chose.
*
* The lobby only carries the options as JSON, so this is the one place that
* knows a six-handed Wizard game needs six seats rather than the catalogue's
* minimum — seat the wrong number and the rules engine rejects the table.
*/
fun seatCountFor(gameId: String, optionsJson: String): Int {
val fallback = GameCatalog.byId(gameId)?.minPlayers ?: 2
return runCatching {
when (gameId) {
GameCatalog.EUCHRE, GameCatalog.KAISER -> 4
GameCatalog.SEQUENCE ->
setupJson.decodeFromString<SequenceOptions>(optionsJson).playerCount
GameCatalog.PRESIDENT ->
setupJson.decodeFromString<PresidentOptions>(optionsJson).playerCount
GameCatalog.GOLF ->
setupJson.decodeFromString<GolfOptions>(optionsJson).playerCount
GameCatalog.CRAZY_EIGHTS ->
setupJson.decodeFromString<CrazyEightsOptions>(optionsJson).playerCount
GameCatalog.WIZARD ->
setupJson.decodeFromString<WizardOptions>(optionsJson).playerCount
else -> fallback
}
}.getOrDefault(fallback)
}
fun teamForSeat(gameId: String, seat: Int): Int = when (gameId) {
// Partners sit opposite each other.
GameCatalog.EUCHRE, GameCatalog.SEQUENCE -> seat % 2
GameCatalog.EUCHRE, GameCatalog.KAISER, GameCatalog.SEQUENCE -> seat % 2
// Everyone else plays for themselves.
else -> seat
}
@@ -305,6 +349,113 @@ private fun GolfOptionsEditor(options: GolfOptions, onChange: (GolfOptions) -> U
}
}
@Composable
private fun KaiserOptionsEditor(options: KaiserOptions, onChange: (KaiserOptions) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
ChipRow(
label = "Lowest opening bid",
values = listOf(5, 6, 7, 8),
selected = options.minimumBid,
display = { "$it" },
onSelect = { onChange(options.copy(minimumBid = it)) },
)
ChipRow(
label = "Game to",
values = listOf(32, 52, 62),
selected = options.pointsToWin,
display = { "$it points" },
onSelect = { target ->
// The floor moves with the target: a long game needs a long
// rope before a team that keeps going down is written off.
onChange(options.copy(pointsToWin = target, losingScore = -target))
},
)
ToggleRow(
title = "No-trump bids",
subtitle = "Pays double, and costs double when it goes down",
checked = options.allowNoTrump,
onChange = { onChange(options.copy(allowNoTrump = it)) },
)
Text(
text = "Four players in two partnerships. The 5♥ is worth five and the 3♠ " +
"costs three, so a hand is worth ten points in all.",
style = MaterialTheme.typography.bodySmall,
)
}
}
@Composable
private fun CrazyEightsOptionsEditor(
options: CrazyEightsOptions,
onChange: (CrazyEightsOptions) -> Unit,
) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
ChipRow(
label = "Players",
values = listOf(2, 3, 4, 5, 6),
selected = options.playerCount,
display = { "$it" },
onSelect = { onChange(options.copy(playerCount = it)) },
)
ChipRow(
label = "Cards each",
values = listOf(0, 5, 7, 9),
selected = options.startingHand,
display = { if (it == 0) "standard" else "$it" },
onSelect = { onChange(options.copy(startingHand = it)) },
)
ChipRow(
label = "Rounds",
values = listOf(1, 3, 5),
selected = options.roundsToPlay,
display = { "$it" },
onSelect = { onChange(options.copy(roundsToPlay = it)) },
)
ToggleRow(
title = "Draw until you can play",
subtitle = "Otherwise you draw a single card and the turn passes on",
checked = options.drawUntilPlayable,
onChange = { onChange(options.copy(drawUntilPlayable = it)) },
)
Text(
text = "Standard is seven cards heads-up and five otherwise. Eights are wild " +
"and cost fifty if you are caught holding one.",
style = MaterialTheme.typography.bodySmall,
)
}
}
@Composable
private fun WizardOptionsEditor(options: WizardOptions, onChange: (WizardOptions) -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
ChipRow(
label = "Players",
values = listOf(3, 4, 5, 6),
selected = options.playerCount,
display = { "$it" },
onSelect = { onChange(options.copy(playerCount = it)) },
)
ChipRow(
label = "Rounds",
values = listOf(0, 5, 10),
selected = options.rounds,
display = { if (it == 0) "full game" else "$it" },
onSelect = { onChange(options.copy(rounds = it)) },
)
ToggleRow(
title = "Screw the dealer",
subtitle = "The dealer may not make the bids add up, so somebody always misses",
checked = options.screwTheDealer,
onChange = { onChange(options.copy(screwTheDealer = it)) },
)
Text(
text = "A full game deals the whole sixty-card pack out: " +
"${options.totalRounds()} rounds at this table.",
style = MaterialTheme.typography.bodySmall,
)
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun <T> ChipRow(
@@ -21,7 +21,6 @@ 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
@@ -46,10 +45,9 @@ fun LobbyScreen(
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
// Seat the table the host actually set up, not the catalogue
// minimum: the rules engine rejects a table of the wrong size.
val seatCount = seatCountFor(route.gameId, route.optionsJson)
env.lobby.startHosting(
gameId = route.gameId,
optionsJson = route.optionsJson,
@@ -7,6 +7,11 @@ 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.crazyeights.CrazyEightsAi
import org.prolibertate.games.game.crazyeights.CrazyEightsMove
import org.prolibertate.games.game.crazyeights.CrazyEightsPhase
import org.prolibertate.games.game.crazyeights.CrazyEightsRules
import org.prolibertate.games.game.crazyeights.CrazyEightsState
import org.prolibertate.games.game.euchre.EuchreAi
import org.prolibertate.games.game.euchre.EuchreMove
import org.prolibertate.games.game.euchre.EuchrePhase
@@ -17,6 +22,11 @@ import org.prolibertate.games.game.golf.GolfMove
import org.prolibertate.games.game.golf.GolfPhase
import org.prolibertate.games.game.golf.GolfRules
import org.prolibertate.games.game.golf.GolfState
import org.prolibertate.games.game.kaiser.KaiserAi
import org.prolibertate.games.game.kaiser.KaiserMove
import org.prolibertate.games.game.kaiser.KaiserPhase
import org.prolibertate.games.game.kaiser.KaiserRules
import org.prolibertate.games.game.kaiser.KaiserState
import org.prolibertate.games.game.president.PresidentAi
import org.prolibertate.games.game.president.PresidentMove
import org.prolibertate.games.game.president.PresidentPhase
@@ -26,13 +36,21 @@ 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.game.wizard.WizardAi
import org.prolibertate.games.game.wizard.WizardMove
import org.prolibertate.games.game.wizard.WizardPhase
import org.prolibertate.games.game.wizard.WizardRules
import org.prolibertate.games.game.wizard.WizardState
import org.prolibertate.games.net.MatchController
import org.prolibertate.games.settings.Settings
import org.prolibertate.games.ui.game.CrazyEightsScreen
import org.prolibertate.games.ui.game.EuchreScreen
import org.prolibertate.games.ui.game.GolfScreen
import org.prolibertate.games.ui.game.KaiserScreen
import org.prolibertate.games.ui.game.PresidentScreen
import org.prolibertate.games.ui.game.TRICK_HOLD_MILLIS
import org.prolibertate.games.ui.game.SequenceScreen
import org.prolibertate.games.ui.game.WizardScreen
/**
* Builds the match for the chosen game and hands it to that game's screen.
@@ -154,6 +172,107 @@ fun PlayScreen(
GolfScreen(controller = controller, localSeat = route.localSeat, onExit = onExit)
}
GameCatalog.KAISER -> {
val controller = remember(route) {
MatchController<KaiserState, KaiserMove>(
rules = KaiserRules,
ai = KaiserAi(),
config = route.config,
scope = scope,
role = role,
localSeats = setOf(route.localSeat),
primarySeat = route.localSeat,
advanceIdle = { state ->
if (state.phase == KaiserPhase.HAND_OVER) {
KaiserRules.nextHand(state)
} else {
null
}
},
aiThinkingMillis = { settings.scaled(700L) },
holdBeforeNextMove = { state ->
if (state.completedTrick.isNotEmpty()) {
settings.scaled(TRICK_HOLD_MILLIS)
} else {
0L
}
},
)
}
StartMatch(env, controller, route)
KaiserScreen(
controller = controller,
localSeat = route.localSeat,
trickHoldMillis = settings.scaled(TRICK_HOLD_MILLIS),
onExit = onExit,
)
}
GameCatalog.WIZARD -> {
val controller = remember(route) {
MatchController<WizardState, WizardMove>(
rules = WizardRules,
ai = WizardAi(),
config = route.config,
scope = scope,
role = role,
localSeats = setOf(route.localSeat),
primarySeat = route.localSeat,
advanceIdle = { state ->
if (state.phase == WizardPhase.ROUND_OVER) {
WizardRules.nextRound(state)
} else {
null
}
},
// Bids against tricks taken are read before the next deal.
awaitsConfirmation = { state -> state.phase == WizardPhase.ROUND_OVER },
aiThinkingMillis = { settings.scaled(700L) },
holdBeforeNextMove = { state ->
if (state.completedTrick.isNotEmpty()) {
settings.scaled(TRICK_HOLD_MILLIS)
} else {
0L
}
},
)
}
StartMatch(env, controller, route)
WizardScreen(
controller = controller,
localSeat = route.localSeat,
trickHoldMillis = settings.scaled(TRICK_HOLD_MILLIS),
onExit = onExit,
)
}
GameCatalog.CRAZY_EIGHTS -> {
val controller = remember(route) {
MatchController<CrazyEightsState, CrazyEightsMove>(
rules = CrazyEightsRules,
ai = CrazyEightsAi(),
config = route.config,
scope = scope,
role = role,
localSeats = setOf(route.localSeat),
primarySeat = route.localSeat,
advanceIdle = { state ->
if (state.phase == CrazyEightsPhase.ROUND_OVER) {
CrazyEightsRules.nextRound(state)
} else {
null
}
},
awaitsConfirmation = { state ->
state.phase == CrazyEightsPhase.ROUND_OVER
},
aiThinkingMillis = { settings.scaled(700L) },
)
}
StartMatch(env, controller, route)
CrazyEightsScreen(controller = controller, localSeat = route.localSeat, onExit = onExit)
}
else -> Text("That game isn't playable yet.")
}
}
@@ -0,0 +1,397 @@
package org.prolibertate.games.ui.game
import androidx.compose.foundation.background
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
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.rememberScrollState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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 androidx.compose.ui.unit.dp
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.crazyeights.CrazyEightsMove
import org.prolibertate.games.game.crazyeights.CrazyEightsPhase
import org.prolibertate.games.game.crazyeights.CrazyEightsState
import org.prolibertate.games.game.crazyeights.DrawCard
import org.prolibertate.games.game.crazyeights.PassTurn
import org.prolibertate.games.game.crazyeights.PlayCard
import org.prolibertate.games.game.crazyeights.crazyEightsPenalty
import org.prolibertate.games.game.crazyeights.isWild
import org.prolibertate.games.net.MatchController
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 Crazy 8s table.
*
* The one thing this screen has to get right is that the suit being followed is
* not always the suit on top of the pile — an eight changes it — so the suit in
* force is stated in words rather than left to be read off the card.
*/
@Composable
fun CrazyEightsScreen(
controller: MatchController<CrazyEightsState, CrazyEightsMove>,
localSeat: Int,
onExit: () -> Unit,
) {
val state by controller.state.collectAsState()
val legal by controller.legalMoves.collectAsState()
// Playing an eight is two decisions: the card, then the suit it turns the
// game to. The card is held here while the suit is chosen.
var pendingWild by remember { mutableStateOf<Card?>(null) }
val current = state
if (current == null) {
ScreenScaffold(title = "Crazy 8s", onBack = onExit) { modifier ->
Box(modifier, contentAlignment = Alignment.Center) { Text("Dealing…") }
}
return
}
ScreenScaffold(title = "Crazy 8s", onBack = onExit) { modifier ->
BoxWithConstraints(modifier = modifier) {
val cardWidth = (minOf(maxWidth, maxHeight) * 0.16f).coerceIn(44.dp, 92.dp)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ScoreLine(current, localSeat)
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.background(FeltGreenDark),
contentAlignment = Alignment.Center,
) {
PileArea(current, cardWidth)
}
OpponentCounts(current, localSeat)
if (current.phase == CrazyEightsPhase.PLAYING) {
TurnControls(
state = current,
localSeat = localSeat,
legal = legal,
pendingWild = pendingWild,
onCancelWild = { pendingWild = null },
onMove = { pendingWild = null; controller.submit(it) },
)
}
HandRow(
state = current,
localSeat = localSeat,
legal = legal,
cardWidth = cardWidth,
pendingWild = pendingWild,
onTap = { card ->
if (isWild(card)) {
pendingWild = if (pendingWild == card) null else card
} else {
pendingWild = null
controller.submit(PlayCard(card))
}
},
)
}
if (current.phase != CrazyEightsPhase.PLAYING) {
RoundScoreDialog(
state = current,
localSeat = localSeat,
onContinue = { controller.confirmAdvance() },
onExit = onExit,
)
}
}
}
}
@Composable
private fun ScoreLine(state: CrazyEightsState, localSeat: Int) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column {
Text(
text = "Round ${state.roundNumber + 1} of ${state.options.roundsToPlay}",
fontWeight = FontWeight.Bold,
)
Text(
text = "Your penalty so far: ${state.scores[localSeat]}",
style = MaterialTheme.typography.bodySmall,
)
}
Column(horizontalAlignment = Alignment.End) {
Text("Play ${state.suitInForce.symbol}", fontWeight = FontWeight.Bold)
Text(
text = "${state.stock.size} left in the stock",
style = MaterialTheme.typography.bodySmall,
)
}
}
}
@Composable
private fun PileArea(state: CrazyEightsState, cardWidth: Dp) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Stock",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
if (state.stock.isEmpty()) {
Text(
text = "empty",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
} else {
CardBackView(width = cardWidth)
}
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Pile",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
state.topCard?.let { PlayingCardView(card = it, width = cardWidth) }
}
}
// An eight on top says nothing about what may be played next, so the
// suit in force is spelled out under the pile.
Text(
text = "Following ${state.suitInForce.symbol} ${state.suitInForce.name.lowercase()}",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onPrimary,
)
}
}
@Composable
private fun OpponentCounts(state: CrazyEightsState, localSeat: Int) {
Row(
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
(0 until state.options.playerCount)
.filter { it != localSeat }
.forEach { seat ->
val count = state.handCounts.getOrElse(seat) { 0 }
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Seat $seat",
style = MaterialTheme.typography.labelSmall,
fontWeight = if (seat == state.turn) FontWeight.Bold else FontWeight.Normal,
)
Row(horizontalArrangement = Arrangement.spacedBy(1.dp)) {
repeat(count.coerceAtMost(8)) { CardBackView(width = 12.dp) }
}
Text("$count", style = MaterialTheme.typography.labelSmall)
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun TurnControls(
state: CrazyEightsState,
localSeat: Int,
legal: List<CrazyEightsMove>,
pendingWild: Card?,
onCancelWild: () -> Unit,
onMove: (CrazyEightsMove) -> Unit,
) {
if (legal.isEmpty()) {
Text("Seat ${state.turn} to play…", style = MaterialTheme.typography.bodySmall)
return
}
if (pendingWild != null) {
val suits = legal.filterIsInstance<PlayCard>()
.filter { it.card == pendingWild }
.mapNotNull { move -> move.nominatedSuit?.let { it to move } }
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("Playing ${pendingWild.label} — name the suit", fontWeight = FontWeight.Bold)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
suits.forEach { (suit, move) ->
Button(onClick = { onMove(move) }) {
Text("${suit.symbol} ${suit.name.lowercase()}")
}
}
}
OutlinedButton(onClick = onCancelWild, modifier = Modifier.fillMaxWidth()) {
Text("Pick a different card")
}
}
return
}
val canDraw = legal.contains(DrawCard)
val canPass = legal.contains(PassTurn)
val playable = legal.filterIsInstance<PlayCard>().isNotEmpty()
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = when {
playable -> "Your turn — tap a card"
canDraw -> "Nothing to play"
else -> "Nothing to play and nothing to draw"
},
fontWeight = FontWeight.Bold,
)
if (canDraw) {
Button(onClick = { onMove(DrawCard) }, modifier = Modifier.fillMaxWidth()) {
Text(
if (state.options.drawUntilPlayable) {
"Draw until something fits"
} else {
"Draw a card"
}
)
}
}
if (canPass) {
OutlinedButton(onClick = { onMove(PassTurn) }, modifier = Modifier.fillMaxWidth()) {
Text("Pass")
}
}
}
}
@Composable
private fun HandRow(
state: CrazyEightsState,
localSeat: Int,
legal: List<CrazyEightsMove>,
cardWidth: Dp,
pendingWild: Card?,
onTap: (Card) -> Unit,
) {
val hand = state.hands.getOrNull(localSeat).orEmpty()
val playable = legal.filterIsInstance<PlayCard>().map { it.card }.toSet()
Column {
Text(
text = "Your hand — ${hand.sumOf { crazyEightsPenalty(it) }} in penalties",
style = MaterialTheme.typography.labelLarge,
)
Row(
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
if (hand.isEmpty()) Text("—", style = MaterialTheme.typography.bodySmall)
hand.forEach { card ->
val canPlay = card in playable
PlayingCardView(
card = card,
width = cardWidth,
enabled = canPlay,
selected = card == pendingWild,
caption = if (isWild(card)) "WILD" else null,
onClick = { onTap(card) },
)
}
}
}
}
/** The card at the end of a round: what everyone was caught holding. */
@Composable
private fun RoundScoreDialog(
state: CrazyEightsState,
localSeat: Int,
onContinue: () -> Unit,
onExit: () -> Unit,
) {
var dismissed by remember(state.roundNumber, state.phase) { mutableStateOf(false) }
if (dismissed) return
val finalRound = state.phase == CrazyEightsPhase.GAME_OVER
val standings = (0 until state.options.playerCount).sortedBy { state.scores[it] }
AlertDialog(
onDismissRequest = { },
title = {
Text(
if (finalRound) {
"Final score"
} else {
"Round ${state.roundNumber + 1} of ${state.options.roundsToPlay}"
}
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
text = state.roundWinner?.let {
if (it == localSeat) "You went out." else "Seat $it went out."
} ?: "The round was blocked — nobody went out.",
style = MaterialTheme.typography.bodyMedium,
)
standings.forEach { seat ->
val you = seat == localSeat
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = if (you) "You" else "Seat $seat",
modifier = Modifier.weight(1f),
fontWeight = if (you) FontWeight.Bold else FontWeight.Normal,
)
Text("${state.scores[seat]}")
}
}
Text("Lowest penalty wins.", style = MaterialTheme.typography.bodySmall)
}
},
confirmButton = {
TextButton(onClick = {
dismissed = true
if (finalRound) onExit() else onContinue()
}) {
Text(if (finalRound) "Back to the menu" else "Deal the next round")
}
},
)
}
@@ -0,0 +1,414 @@
package org.prolibertate.games.ui.game
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
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.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import kotlinx.coroutines.delay
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.kaiser.FIVE_OF_HEARTS
import org.prolibertate.games.game.kaiser.KaiserMove
import org.prolibertate.games.game.kaiser.KaiserPhase
import org.prolibertate.games.game.kaiser.KaiserState
import org.prolibertate.games.game.kaiser.MakeBid
import org.prolibertate.games.game.kaiser.NameTrump
import org.prolibertate.games.game.kaiser.PassBid
import org.prolibertate.games.game.kaiser.PlayCard
import org.prolibertate.games.game.kaiser.THREE_OF_SPADES
import org.prolibertate.games.game.kaiser.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.PlayingCardView
import org.prolibertate.games.ui.theme.FeltGreenDark
/**
* The Kaiser table.
*
* Laid out like the Euchre table — partners opposite, each card on the side of
* whoever played it — with the two counters called out wherever they appear,
* since the whole hand is really played for those two cards.
*/
@Composable
fun KaiserScreen(
controller: MatchController<KaiserState, KaiserMove>,
localSeat: Int,
trickHoldMillis: Long,
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 = "Kaiser", onBack = onExit) { modifier ->
Box(modifier, contentAlignment = Alignment.Center) { Text("Dealing…") }
}
return
}
ScreenScaffold(title = "Kaiser", onBack = onExit) { modifier ->
BoxWithConstraints(modifier = modifier) {
val compact = maxWidth < 600.dp
val cardWidth = (minOf(maxWidth, maxHeight) * if (compact) 0.15f else 0.11f)
.coerceIn(44.dp, 96.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, localSeat, cardWidth, trickHoldMillis)
}
notice?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
when (current.phase) {
KaiserPhase.BIDDING ->
BiddingControls(current, localSeat, legal) { controller.submit(it) }
KaiserPhase.HAND_OVER -> Text(
text = current.log.lastOrNull().orEmpty(),
style = MaterialTheme.typography.titleSmall,
)
KaiserPhase.GAME_OVER -> {
Text("Game over.", fontWeight = FontWeight.Bold)
PrimaryAction(text = "Back to the menu") { onExit() }
}
else -> Unit
}
HandRow(current, localSeat, legal, cardWidth) { controller.submit(it) }
}
}
}
}
@Composable
private fun ScoreBar(state: KaiserState, localSeat: Int) {
val myTeam = teamOf(localSeat)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column {
Text(
text = "Us ${state.scores[myTeam]} — Them ${state.scores[1 - myTeam]}",
fontWeight = FontWeight.Bold,
)
Text(
text = "This hand: ${state.handPoints[myTeam]} to us, " +
"${state.handPoints[1 - myTeam]} to them",
style = MaterialTheme.typography.bodySmall,
)
}
Column(horizontalAlignment = Alignment.End) {
val bid = state.highBid
Text(
text = when {
bid == null -> "Bidding"
state.trump == null && state.phase != KaiserPhase.BIDDING -> "No trump"
state.trump != null -> "Trump ${state.trump!!.symbol}"
else -> "Bid ${bid.points}"
},
fontWeight = FontWeight.Bold,
)
if (bid != null) {
val bidder = state.highBidder
Text(
text = "Contract ${bid.points}${if (bid.noTrump) " no trump" else ""}" +
(bidder?.let { " by ${seatLabel(relativePosition(it, localSeat))}" } ?: ""),
style = MaterialTheme.typography.bodySmall,
)
}
}
}
}
/** Where a seat sits relative to you. Partners sit opposite, so 2 is yours. */
private fun relativePosition(seat: Int, localSeat: Int): Int = ((seat - localSeat) % 4 + 4) % 4
private fun seatLabel(relative: Int): String = when (relative) {
0 -> "You"
1 -> "Left"
2 -> "Partner"
else -> "Right"
}
/** Duration of the sweep towards the winner. */
private const val SWEEP_MILLIS = 450
@Composable
private fun TrickArea(
state: KaiserState,
localSeat: Int,
cardWidth: Dp,
trickHoldMillis: Long,
) {
val sweeping = state.trick.isEmpty() && state.completedTrick.isNotEmpty()
val cardsOnTable = if (sweeping) state.completedTrick else state.trick
var sweepStarted by remember(state.completedTrick) { mutableStateOf(false) }
LaunchedEffect(state.completedTrick) {
if (state.completedTrick.isNotEmpty()) {
delay(trickHoldMillis)
sweepStarted = true
}
}
val sweep by animateFloatAsState(
targetValue = if (sweeping && sweepStarted) 1f else 0f,
animationSpec = tween(durationMillis = SWEEP_MILLIS),
label = "kaiserSweep",
)
val winnerRelative = state.lastTrickWinner?.let { relativePosition(it, localSeat) } ?: 0
val (dirX, dirY) = when (winnerRelative) {
0 -> 0f to 1f
1 -> -1f to 0f
2 -> 0f to -1f
else -> 1f to 0f
}
val travelPx = with(LocalDensity.current) { (cardWidth * 2.5f).toPx() }
Box(modifier = Modifier.fillMaxSize().padding(4.dp)) {
if (cardsOnTable.isEmpty()) {
Text(
text = when {
state.phase == KaiserPhase.BIDDING -> "Bidding"
state.turn == localSeat -> "Lead a card"
else -> "Waiting…"
},
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.align(Alignment.Center),
)
}
cardsOnTable.forEach { played ->
val relative = relativePosition(played.seat, localSeat)
val alignment = when (relative) {
0 -> Alignment.BottomCenter
1 -> Alignment.CenterStart
2 -> Alignment.TopCenter
else -> Alignment.CenterEnd
}
val rotation = when (relative) {
1 -> 90f
2 -> 180f
3 -> -90f
else -> 0f
}
Column(
modifier = Modifier
.align(alignment)
.offset {
IntOffset(
x = (dirX * travelPx * sweep).roundToInt(),
y = (dirY * travelPx * sweep).roundToInt(),
)
}
.alpha(1f - sweep),
horizontalAlignment = Alignment.CenterHorizontally,
) {
PlayingCardView(
card = played.card,
width = cardWidth,
caption = counterCaption(played.card),
modifier = Modifier.rotate(rotation),
)
Text(
text = seatLabel(relative),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
}
}
if (sweeping && state.lastTrickWinner != null) {
Text(
text = "${seatLabel(winnerRelative)} takes it",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.align(Alignment.Center).alpha(1f - sweep),
)
}
if (state.phase == KaiserPhase.PLAYING && state.trick.size < 4) {
val waitingOn = relativePosition(state.turn, localSeat)
if (waitingOn != 0 && state.trick.none { it.seat == state.turn }) {
Text(
text = "${seatLabel(waitingOn)} to play",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.align(Alignment.BottomStart),
)
}
}
}
}
/** The two cards that decide the hand, named on their faces. */
private fun counterCaption(card: Card): String? = when (card) {
FIVE_OF_HEARTS -> "+5"
THREE_OF_SPADES -> "−3"
else -> null
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun BiddingControls(
state: KaiserState,
localSeat: Int,
legal: List<KaiserMove>,
onMove: (KaiserMove) -> Unit,
) {
if (legal.isEmpty()) {
val waitingOn = relativePosition(state.turn, localSeat)
Text("Waiting for ${seatLabel(waitingOn).lowercase()} to bid…")
return
}
val naming = legal.filterIsInstance<NameTrump>()
if (naming.isNotEmpty()) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("You won the bidding — name trump", fontWeight = FontWeight.Bold)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
naming.forEach { move ->
Button(onClick = { onMove(move) }) {
Text(move.suit?.let { "${it.symbol} ${it.name.lowercase()}" } ?: "No trump")
}
}
}
}
return
}
val bids = legal.filterIsInstance<MakeBid>()
val canPass = legal.contains(PassBid)
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = state.highBid?.let { high ->
"Bidding stands at ${high.points}${if (high.noTrump) " no trump" else ""}"
} ?: "Open the bidding",
fontWeight = FontWeight.Bold,
)
if (!canPass) {
Text(
text = "Everyone passed, so as dealer you have to take it.",
style = MaterialTheme.typography.bodySmall,
)
}
// Wraps rather than scrolls, so no bid can be pushed off the edge.
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
bids.forEach { move ->
Button(onClick = { onMove(move) }) {
Text("${move.bid.points}${if (move.bid.noTrump) " NT" else ""}")
}
}
}
Text(
text = "A no-trump contract pays double, and costs double if it goes down.",
style = MaterialTheme.typography.bodySmall,
)
if (canPass) {
OutlinedButton(onClick = { onMove(PassBid) }, modifier = Modifier.fillMaxWidth()) {
Text("Pass")
}
}
}
}
@Composable
private fun HandRow(
state: KaiserState,
seat: Int,
legal: List<KaiserMove>,
cardWidth: Dp,
onPlay: (KaiserMove) -> Unit,
) {
val hand = state.hands.getOrNull(seat).orEmpty()
val playable = legal.filterIsInstance<PlayCard>().map { it.card }.toSet()
Column {
Text(
text = if (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
PlayingCardView(
card = card,
width = cardWidth,
enabled = canPlay,
caption = counterCaption(card),
onClick = { if (canPlay) onPlay(PlayCard(card)) },
)
}
}
}
}
@@ -0,0 +1,473 @@
package org.prolibertate.games.ui.game
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
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.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.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
import kotlinx.coroutines.delay
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.wizard.ChooseTrump
import org.prolibertate.games.game.wizard.MakeBid
import org.prolibertate.games.game.wizard.PlayCard
import org.prolibertate.games.game.wizard.WizardMove
import org.prolibertate.games.game.wizard.WizardPhase
import org.prolibertate.games.game.wizard.WizardState
import org.prolibertate.games.game.wizard.isJester
import org.prolibertate.games.game.wizard.isWizardCard
import org.prolibertate.games.net.MatchController
import org.prolibertate.games.ui.ScreenScaffold
import org.prolibertate.games.ui.common.PlayingCardView
import org.prolibertate.games.ui.theme.FeltGreenDark
/**
* The Wizard table.
*
* Three to six can play, so seats are placed round a circle rather than at four
* fixed edges: you are always at the bottom and everyone else is spaced out from
* there, which keeps the same layout code working at every table size.
*/
@Composable
fun WizardScreen(
controller: MatchController<WizardState, WizardMove>,
localSeat: Int,
trickHoldMillis: Long,
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 = "Wizard", onBack = onExit) { modifier ->
Box(modifier, contentAlignment = Alignment.Center) { Text("Dealing…") }
}
return
}
ScreenScaffold(title = "Wizard", onBack = onExit) { modifier ->
BoxWithConstraints(modifier = modifier) {
val cardWidth = (minOf(maxWidth, maxHeight) * 0.14f).coerceIn(40.dp, 88.dp)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
RoundBar(current, localSeat)
BidTally(current, localSeat)
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.background(FeltGreenDark),
) {
TrickArea(current, localSeat, cardWidth, trickHoldMillis)
}
notice?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
if (current.phase == WizardPhase.BIDDING) {
BiddingControls(current, localSeat, legal) { controller.submit(it) }
}
HandRow(current, localSeat, legal, cardWidth) { controller.submit(it) }
}
if (current.phase == WizardPhase.ROUND_OVER || current.phase == WizardPhase.GAME_OVER) {
RoundScoreDialog(
state = current,
localSeat = localSeat,
onContinue = { controller.confirmAdvance() },
onExit = onExit,
)
}
}
}
}
@Composable
private fun RoundBar(state: WizardState, localSeat: Int) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column {
Text(
text = "Round ${state.round + 1} of ${state.options.totalRounds()}" +
" — ${state.cardsThisRound} card(s)",
fontWeight = FontWeight.Bold,
)
Text(
text = "Your score: ${state.scores[localSeat]}",
style = MaterialTheme.typography.bodySmall,
)
}
Column(horizontalAlignment = Alignment.End) {
Text(
text = state.trump?.let { "Trump ${it.symbol}" } ?: "No trump",
fontWeight = FontWeight.Bold,
)
state.trumpCard?.let {
Text("Turned ${it.label}", style = MaterialTheme.typography.bodySmall)
}
}
}
}
/** Everyone's bid against what they have actually taken — the whole game in a row. */
@Composable
private fun BidTally(state: WizardState, localSeat: Int) {
Row(
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
(0 until state.options.playerCount).forEach { seat ->
val bid = state.bids[seat]
val won = state.tricksWon[seat]
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = if (seat == localSeat) "You" else seatLabel(seat, localSeat),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (seat == state.turn) FontWeight.Bold else FontWeight.Normal,
)
Text(
text = bid?.let { "$won / $it" } ?: "—",
style = MaterialTheme.typography.labelLarge,
// Green while the bid is still on, red once it cannot be made.
color = when {
bid == null -> MaterialTheme.colorScheme.onSurface
won == bid -> MaterialTheme.colorScheme.primary
won > bid -> MaterialTheme.colorScheme.error
else -> MaterialTheme.colorScheme.onSurface
},
)
}
}
}
}
/** Seats are named by how far round the table they sit from you. */
private fun seatLabel(seat: Int, localSeat: Int): String =
if (seat == localSeat) "You" else "Seat $seat"
/** Duration of the sweep towards the winner. */
private const val SWEEP_MILLIS = 450
@Composable
private fun TrickArea(
state: WizardState,
localSeat: Int,
cardWidth: Dp,
trickHoldMillis: Long,
) {
val players = state.options.playerCount
val sweeping = state.trick.isEmpty() && state.completedTrick.isNotEmpty()
val cardsOnTable = if (sweeping) state.completedTrick else state.trick
var sweepStarted by remember(state.completedTrick) { mutableStateOf(false) }
LaunchedEffect(state.completedTrick) {
if (state.completedTrick.isNotEmpty()) {
delay(trickHoldMillis)
sweepStarted = true
}
}
val sweep by animateFloatAsState(
targetValue = if (sweeping && sweepStarted) 1f else 0f,
animationSpec = tween(durationMillis = SWEEP_MILLIS),
label = "wizardSweep",
)
val winnerRelative = state.lastTrickWinner
?.let { ((it - localSeat) % players + players) % players }
?: 0
val winnerAngle = 2.0 * PI * winnerRelative / players
BoxWithConstraints(modifier = Modifier.fillMaxSize().padding(4.dp)) {
// Cards sit on a circle that fits inside whatever space the table has.
val radius = (minOf(maxWidth, maxHeight) / 2 - cardWidth * 0.7f).coerceAtLeast(0.dp)
val radiusPx = with(LocalDensity.current) { radius.toPx() }
val travelPx = with(LocalDensity.current) { (cardWidth * 2f).toPx() }
if (cardsOnTable.isEmpty()) {
Text(
text = when {
state.phase == WizardPhase.BIDDING -> "Bidding"
state.turn == localSeat -> "Lead a card"
else -> "Waiting…"
},
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.align(Alignment.Center),
)
}
cardsOnTable.forEach { played ->
val relative = ((played.seat - localSeat) % players + players) % players
val angle = 2.0 * PI * relative / players
// Relative seat 0 is you, at the bottom; the rest run clockwise.
val x = -sin(angle) * radiusPx
val y = cos(angle) * radiusPx
// Turn each card to face whoever played it.
val rotation = (relative * 360f / players)
Column(
modifier = Modifier
.align(Alignment.Center)
.offset {
IntOffset(
x = (x + -sin(winnerAngle) * travelPx * sweep).roundToInt(),
y = (y + cos(winnerAngle) * travelPx * sweep).roundToInt(),
)
}
.alpha(1f - sweep),
horizontalAlignment = Alignment.CenterHorizontally,
) {
PlayingCardView(
card = played.card,
width = cardWidth,
caption = specialCaption(played.card),
modifier = Modifier.rotate(rotation),
)
Text(
text = seatLabel(played.seat, localSeat),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
)
}
}
if (sweeping && state.lastTrickWinner != null) {
Text(
text = "${seatLabel(state.lastTrickWinner!!, localSeat)} takes it",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.align(Alignment.Center).alpha(1f - sweep),
)
}
}
}
/**
* Wizards and jesters carry no rank or suit anyone can read off the face, so
* they say what they do instead.
*/
private fun specialCaption(card: Card): String? = when {
isWizardCard(card) -> "WIZARD"
isJester(card) -> "JESTER"
else -> null
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun BiddingControls(
state: WizardState,
localSeat: Int,
legal: List<WizardMove>,
onMove: (WizardMove) -> Unit,
) {
if (legal.isEmpty()) {
Text(
text = "Waiting for ${seatLabel(state.turn, localSeat).lowercase()} to bid…",
style = MaterialTheme.typography.bodySmall,
)
return
}
val trumpChoices = legal.filterIsInstance<ChooseTrump>()
if (trumpChoices.isNotEmpty()) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("A wizard was turned — you name trump", fontWeight = FontWeight.Bold)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
trumpChoices.forEach { move ->
Button(onClick = { onMove(move) }) {
Text("${move.suit.symbol} ${move.suit.name.lowercase()}")
}
}
}
}
return
}
val bids = legal.filterIsInstance<MakeBid>()
val bidSoFar = state.bids.filterNotNull().sum()
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "How many of the ${state.cardsThisRound} tricks will you take?",
fontWeight = FontWeight.Bold,
)
Text(
text = "Bid so far: $bidSoFar. Hit your bid exactly for 20 plus 10 a trick; " +
"miss it and it costs 10 for every trick either way.",
style = MaterialTheme.typography.bodySmall,
)
if (state.options.screwTheDealer && state.turn == state.dealer) {
Text(
text = "Screw the dealer: you may not make the bids add up.",
style = MaterialTheme.typography.bodySmall,
)
}
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
bids.forEach { move ->
Button(onClick = { onMove(move) }) { Text("${move.tricks}") }
}
}
}
}
@Composable
private fun HandRow(
state: WizardState,
seat: Int,
legal: List<WizardMove>,
cardWidth: Dp,
onPlay: (WizardMove) -> Unit,
) {
val hand = state.hands.getOrNull(seat).orEmpty()
val playable = legal.filterIsInstance<PlayCard>().map { it.card }.toSet()
Column {
Text(
text = if (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
PlayingCardView(
card = card,
width = cardWidth,
enabled = canPlay,
caption = specialCaption(card),
onClick = { if (canPlay) onPlay(PlayCard(card)) },
)
}
}
}
}
/** Bids against tricks taken, and what that was worth, before the next deal. */
@Composable
private fun RoundScoreDialog(
state: WizardState,
localSeat: Int,
onContinue: () -> Unit,
onExit: () -> Unit,
) {
var dismissed by remember(state.round, state.phase) { mutableStateOf(false) }
if (dismissed) return
val finalRound = state.phase == WizardPhase.GAME_OVER
val standings = (0 until state.options.playerCount).sortedByDescending { state.scores[it] }
AlertDialog(
onDismissRequest = { },
title = {
Text(
if (finalRound) {
"Final score"
} else {
"Round ${state.round + 1} of ${state.options.totalRounds()}"
}
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(modifier = Modifier.fillMaxWidth()) {
Text("Player", modifier = Modifier.weight(1f), fontWeight = FontWeight.Bold)
Text("Bid", fontWeight = FontWeight.Bold)
Text(" Took", fontWeight = FontWeight.Bold)
Text(" Round", fontWeight = FontWeight.Bold)
Text(" Total", fontWeight = FontWeight.Bold)
}
standings.forEach { seat ->
val you = seat == localSeat
val weight = if (you) FontWeight.Bold else FontWeight.Normal
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = if (you) "You" else "Seat $seat",
modifier = Modifier.weight(1f),
fontWeight = weight,
)
Text("${state.bids[seat] ?: 0}")
Text(" ${state.tricksWon[seat]}")
Text(" ${state.roundScores[seat]}")
Text(" ${state.scores[seat]}", fontWeight = weight)
}
}
Text(
text = if (finalRound) {
"Highest score wins — seat ${standings.first()} takes it."
} else {
"Highest score wins."
},
style = MaterialTheme.typography.bodySmall,
)
}
},
confirmButton = {
TextButton(onClick = {
dismissed = true
if (finalRound) onExit() else onContinue()
}) {
Text(if (finalRound) "Back to the menu" else "Deal the next round")
}
},
)
}