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,159 @@
package org.prolibertate.games.game
/**
* The catalogue the main menu is built from.
*
* Every game the app intends to ship appears here, whether or not its rules
* engine exists yet. [GameDescriptor.available] is what the menu keys off to
* decide between "play" and "coming soon", so adding a game is a matter of
* flipping that flag once its engine and screen land.
*/
enum class GameCategory(val label: String) {
CARD("Playing Card Games"),
BOARD("Board Games"),
}
data class GameDescriptor(
val id: String,
val title: String,
val category: GameCategory,
val minPlayers: Int,
val maxPlayers: Int,
/** True when players are grouped into partnerships rather than playing solo. */
val teamBased: Boolean,
val blurb: String,
val available: Boolean,
)
object GameCatalog {
const val EUCHRE = "euchre"
const val KAISER = "kaiser"
const val PRESIDENT = "president"
const val GOLF = "golf"
const val WIZARD = "wizard"
const val CRAZY_EIGHTS = "crazy8s"
const val SEQUENCE = "sequence"
const val MASTERMIND = "mastermind"
const val BACKGAMMON = "backgammon"
const val CHESS = "chess"
const val CHECKERS = "checkers"
val all: List<GameDescriptor> = listOf(
GameDescriptor(
id = EUCHRE,
title = "Euchre",
category = GameCategory.CARD,
minPlayers = 4,
maxPlayers = 4,
teamBased = true,
blurb = "Four players, two partnerships, 24-card deck. Bowers are trump.",
available = true,
),
GameDescriptor(
id = KAISER,
title = "Kaiser",
category = GameCategory.CARD,
minPlayers = 4,
maxPlayers = 4,
teamBased = true,
blurb = "Prairie trick-taking with bidding. The 5 of hearts and 3 of spades decide it.",
available = false,
),
GameDescriptor(
id = PRESIDENT,
title = "President",
category = GameCategory.CARD,
minPlayers = 3,
maxPlayers = 7,
teamBased = false,
blurb = "Shed your hand first and rule the table. Last one out serves the drinks.",
available = false,
),
GameDescriptor(
id = GOLF,
title = "Golf",
category = GameCategory.CARD,
minPlayers = 2,
maxPlayers = 6,
teamBased = false,
blurb = "Lowest score wins over nine holes. Match pairs to cancel them out.",
available = false,
),
GameDescriptor(
id = WIZARD,
title = "Wizard",
category = GameCategory.CARD,
minPlayers = 3,
maxPlayers = 6,
teamBased = false,
blurb = "Bid your tricks exactly. Wizards always win, jesters always lose.",
available = false,
),
GameDescriptor(
id = CRAZY_EIGHTS,
title = "Crazy 8s",
category = GameCategory.CARD,
minPlayers = 2,
maxPlayers = 6,
teamBased = false,
blurb = "Match rank or suit, and eights change everything.",
available = false,
),
GameDescriptor(
id = SEQUENCE,
title = "Sequence",
category = GameCategory.BOARD,
minPlayers = 2,
maxPlayers = 12,
teamBased = true,
blurb = "Play a card, claim its square, and build five in a row.",
available = true,
),
GameDescriptor(
id = MASTERMIND,
title = "Mastermind",
category = GameCategory.BOARD,
minPlayers = 2,
maxPlayers = 2,
teamBased = false,
blurb = "Break the hidden code from black and white peg clues.",
available = false,
),
GameDescriptor(
id = BACKGAMMON,
title = "Backgammon",
category = GameCategory.BOARD,
minPlayers = 2,
maxPlayers = 2,
teamBased = false,
blurb = "Race your checkers home, and hit your opponent on the way.",
available = false,
),
GameDescriptor(
id = CHESS,
title = "Chess",
category = GameCategory.BOARD,
minPlayers = 2,
maxPlayers = 2,
teamBased = false,
blurb = "The old game. Full legal moves, castling, en passant, promotion.",
available = false,
),
GameDescriptor(
id = CHECKERS,
title = "Checkers",
category = GameCategory.BOARD,
minPlayers = 2,
maxPlayers = 2,
teamBased = false,
blurb = "Forced captures, kings, and the long diagonal.",
available = false,
),
)
fun byId(id: String): GameDescriptor? = all.firstOrNull { it.id == id }
fun byCategory(category: GameCategory): List<GameDescriptor> =
all.filter { it.category == category }
}
@@ -0,0 +1,97 @@
package org.prolibertate.games.game.cards
import kotlinx.serialization.Serializable
import kotlin.random.Random
@Serializable
enum class Suit(val symbol: String, val isRed: Boolean) {
CLUBS("♣", false),
DIAMONDS("♦", true),
HEARTS("♥", true),
SPADES("♠", false);
/** Euchre's left bower lives in the suit of the same colour. */
fun sameColour(): Suit = when (this) {
CLUBS -> SPADES
SPADES -> CLUBS
DIAMONDS -> HEARTS
HEARTS -> DIAMONDS
}
}
@Serializable
enum class Rank(val short: String, val order: Int) {
TWO("2", 2),
THREE("3", 3),
FOUR("4", 4),
FIVE("5", 5),
SIX("6", 6),
SEVEN("7", 7),
EIGHT("8", 8),
NINE("9", 9),
TEN("10", 10),
JACK("J", 11),
QUEEN("Q", 12),
KING("K", 13),
ACE("A", 14),
}
@Serializable
data class Card(val rank: Rank, val suit: Suit) {
/** Compact form used in logs and in the Sequence board layout table. */
val code: String get() = "${rank.short}${suit.name.first()}"
val label: String get() = "${rank.short}${suit.symbol}"
override fun toString(): String = label
companion object {
/** Parses the [code] form, e.g. "10H", "AS", "9D". */
fun parse(code: String): Card {
val suitChar = code.last()
val rankPart = code.dropLast(1)
val suit = Suit.entries.first { it.name.first() == suitChar }
val rank = Rank.entries.first { it.short == rankPart }
return Card(rank, suit)
}
}
}
object Decks {
/** Standard 52-card deck. */
fun standard52(): List<Card> =
Suit.entries.flatMap { suit -> Rank.entries.map { rank -> Card(rank, suit) } }
/**
* Euchre decks. 24 cards (9 through ace) is the common game; 32 cards
* (7 through ace) is a widespread variant that lengthens the hand.
*/
fun euchre(size: Int): List<Card> {
val lowest = when (size) {
24 -> Rank.NINE
32 -> Rank.SEVEN
else -> throw IllegalArgumentException("Unsupported Euchre deck size: $size")
}
return Suit.entries.flatMap { suit ->
Rank.entries.filter { it.order >= lowest.order }.map { rank -> Card(rank, suit) }
}
}
/** Two full decks shuffled together, as Sequence uses. */
fun double52(): List<Card> = standard52() + standard52()
}
/**
* Deterministic shuffle. Every shuffle in the app runs through a seeded
* [Random] so a networked hand can be reproduced from its seed and so tests
* are repeatable — the host generates the seed and ships it with the state.
*/
fun <T> List<T>.shuffledWith(random: Random): List<T> = toMutableList().apply {
for (i in indices.reversed()) {
val j = random.nextInt(i + 1)
val tmp = this[i]
this[i] = this[j]
this[j] = tmp
}
}
@@ -0,0 +1,87 @@
package org.prolibertate.games.game.engine
import kotlinx.serialization.Serializable
@Serializable
enum class PlayerKind {
/** A person on this device. */
HUMAN_LOCAL,
/** A person on another device, reached over LAN or Bluetooth. */
HUMAN_REMOTE,
/** Driven by the host's AI. */
AI,
}
@Serializable
data class PlayerSlot(
val seat: Int,
val name: String,
val kind: PlayerKind,
/** Partnership index. Solo games put every seat on its own team. */
val team: Int,
/** Identifies the remote device for [PlayerKind.HUMAN_REMOTE] seats. */
val peerId: String? = null,
)
@Serializable
data class TableConfig(
val gameId: String,
val seats: List<PlayerSlot>,
/** Game-specific options, serialised by the owning rules implementation. */
val optionsJson: String,
/** Shared shuffle seed so a hand is reproducible from its state. */
val seed: Long,
)
/**
* A game's rules, expressed as a pure state machine.
*
* Implementations must be free of Android dependencies and free of side
* effects: [applyMove] returns a new state rather than mutating. That is what
* lets the same code drive the local AI, the host's authoritative copy, and
* the unit tests.
*/
interface GameRules<S : Any, M : Any> {
val gameId: String
fun initialState(config: TableConfig): S
/** The seat expected to move, or null when nobody is on the clock. */
fun currentSeat(state: S): Int?
fun legalMoves(state: S, seat: Int): List<M>
/**
* Applies [move] on behalf of [seat].
*
* @throws IllegalArgumentException if the move is not currently legal —
* the host validates every intent that arrives over the network this way.
*/
fun applyMove(state: S, seat: Int, move: M): S
fun isFinished(state: S): Boolean
fun summary(state: S): String
/**
* Strips information [seat] is not entitled to see.
*
* The host holds the true state and sends each client only its own view,
* so an opponent's hand never crosses the wire in the first place. Any
* hidden-information game must implement this meaningfully.
*/
fun viewFor(state: S, seat: Int): S
fun encodeState(state: S): String
fun decodeState(json: String): S
fun encodeMove(move: M): String
fun decodeMove(json: String): M
}
/** Chooses moves for unoccupied seats. Always runs on the host. */
interface GameAi<S : Any, M : Any> {
fun chooseMove(state: S, seat: Int, legal: List<M>): M
}
@@ -0,0 +1,175 @@
package org.prolibertate.games.game.euchre
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.cards.Rank
import org.prolibertate.games.game.cards.Suit
import org.prolibertate.games.game.engine.GameAi
/**
* A heuristic Euchre opponent.
*
* It does not look at anybody else's cards and it does not search — it counts
* trump, respects its partner, and plays the cheapest card that does the job.
* That is enough to be a reasonable table opponent without pretending to be a
* solver.
*/
class EuchreAi(private val difficulty: Difficulty = Difficulty.NORMAL) :
GameAi<EuchreState, EuchreMove> {
enum class Difficulty(val bidThreshold: Int, val aloneThreshold: Int) {
/** Bids loosely and plays straightforwardly. */
EASY(bidThreshold = 7, aloneThreshold = 26),
NORMAL(bidThreshold = 9, aloneThreshold = 24),
/** Bids tighter and is harder to sneak a trick past. */
CAUTIOUS(bidThreshold = 11, aloneThreshold = 22),
}
override fun chooseMove(state: EuchreState, seat: Int, legal: List<EuchreMove>): EuchreMove {
require(legal.isNotEmpty()) { "No legal move for seat $seat" }
return when (state.phase) {
EuchrePhase.BID_ROUND_1 -> chooseBidRound1(state, seat, legal)
EuchrePhase.BID_ROUND_2 -> chooseBidRound2(state, seat, legal)
EuchrePhase.DEALER_DISCARD -> chooseDiscard(state, legal)
EuchrePhase.PLAYING -> choosePlay(state, seat, legal)
else -> legal.first()
}
}
// -----------------------------------------------------------------------
// Bidding
// -----------------------------------------------------------------------
/**
* Rates a hand for a candidate trump suit. Bowers and trump length carry
* the hand; off-suit aces are worth a trick more often than not.
*/
private fun handValue(hand: List<Card>, trump: Suit): Int {
var value = 0
for (card in hand) {
value += when {
isRightBower(card, trump) -> 9
isLeftBower(card, trump) -> 7
isTrumpCard(card, trump) -> 3 + (card.rank.order - Rank.NINE.order) / 2
card.rank == Rank.ACE -> 3
card.rank == Rank.KING -> 1
else -> 0
}
}
// A void in a side suit means an early chance to trump in.
val sideSuits = Suit.entries.filter { it != trump }
value += sideSuits.count { suit -> hand.none { effectiveSuit(it, trump) == suit } } * 2
return value
}
private fun chooseBidRound1(
state: EuchreState,
seat: Int,
legal: List<EuchreMove>,
): EuchreMove {
val upCard = state.upCard ?: return Pass
val trump = upCard.suit
var hand = state.hands[seat]
// If our partner is the dealer they gain the turn card, and if we are
// the dealer we gain it ourselves — both make the hand stronger than it
// looks. Ordering up into an opponent dealer instead hands them a card.
if (seat == state.dealer) hand = hand + upCard
var value = handValue(hand, trump)
if (partnerOf(seat) == state.dealer) value += 2
if (seat != state.dealer && partnerOf(seat) != state.dealer) value -= 2
val alone = OrderUp(alone = true)
if (value >= difficulty.aloneThreshold && legal.contains(alone)) return alone
val order = OrderUp(alone = false)
if (value >= difficulty.bidThreshold && legal.contains(order)) return order
return if (legal.contains(Pass)) Pass else legal.first()
}
private fun chooseBidRound2(
state: EuchreState,
seat: Int,
legal: List<EuchreMove>,
): EuchreMove {
val hand = state.hands[seat]
val callable = legal.filterIsInstance<CallTrump>()
if (callable.isEmpty()) return legal.first()
val best = callable
.filter { !it.alone }
.maxByOrNull { handValue(hand, it.suit) }
?: callable.first()
val bestValue = handValue(hand, best.suit)
val alone = callable.firstOrNull { it.alone && it.suit == best.suit }
if (alone != null && bestValue >= difficulty.aloneThreshold) return alone
if (bestValue >= difficulty.bidThreshold) return best
// Stuck as dealer with a bad hand: name the least-bad suit anyway.
return if (legal.contains(Pass)) Pass else best
}
private fun chooseDiscard(state: EuchreState, legal: List<EuchreMove>): EuchreMove {
val trump = requireNotNull(state.trump)
val discards = legal.filterIsInstance<Discard>()
// Prefer to void a side suit entirely; otherwise throw the lowest card.
val hand = state.hands[state.dealer]
val suitCounts = hand.groupingBy { effectiveSuit(it, trump) }.eachCount()
return discards.minByOrNull { discard ->
val card = discard.card
val suit = effectiveSuit(card, trump)
val trumpPenalty = if (suit == trump) 1000 else 0
val singletonBonus = if (suitCounts[suit] == 1 && card.rank != Rank.ACE) -20 else 0
trumpPenalty + singletonBonus + card.rank.order
} ?: discards.first()
}
// -----------------------------------------------------------------------
// Card play
// -----------------------------------------------------------------------
private fun choosePlay(
state: EuchreState,
seat: Int,
legal: List<EuchreMove>,
): EuchreMove {
val trump = requireNotNull(state.trump)
val cards = legal.filterIsInstance<PlayCard>().map { it.card }
if (cards.size == 1) return PlayCard(cards.first())
if (state.trick.isEmpty()) return PlayCard(chooseLead(cards, trump))
val ledSuit = effectiveSuit(state.trick.first().card, trump)
val bestSoFar = state.trick.maxBy { trickStrength(it.card, trump, ledSuit) }
val partnerWinning = partnerOf(bestSoFar.seat) == seat
val lastToPlay = state.trick.size == state.activeSeatCount - 1
// Partner already has it and we are last: never waste a good card.
if (partnerWinning && lastToPlay) return PlayCard(lowest(cards, trump, ledSuit))
val bestStrength = trickStrength(bestSoFar.card, trump, ledSuit)
val winners = cards.filter { trickStrength(it, trump, ledSuit) > bestStrength }
return when {
// Take it as cheaply as we can.
winners.isNotEmpty() && (!partnerWinning || !lastToPlay) ->
PlayCard(winners.minBy { trickStrength(it, trump, ledSuit) })
else -> PlayCard(lowest(cards, trump, ledSuit))
}
}
private fun chooseLead(cards: List<Card>, trump: Suit): Card {
// Right bower up front pulls trump and protects the left.
cards.firstOrNull { isRightBower(it, trump) }?.let { return it }
// Off-suit aces are most likely to survive early.
cards.filter { !isTrumpCard(it, trump) && it.rank == Rank.ACE }
.maxByOrNull { it.rank.order }
?.let { return it }
val offSuit = cards.filter { !isTrumpCard(it, trump) }
if (offSuit.isNotEmpty()) return offSuit.maxBy { it.rank.order }
return cards.maxBy { trumpStrength(it, trump) }
}
private fun lowest(cards: List<Card>, trump: Suit, ledSuit: Suit): Card =
cards.minBy { trickStrength(it, trump, ledSuit).takeIf { s -> s > 0 } ?: it.rank.order }
}
@@ -0,0 +1,154 @@
package org.prolibertate.games.game.euchre
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.cards.Rank
import org.prolibertate.games.game.cards.Suit
/**
* Rule toggles. Euchre is played differently in almost every kitchen, so the
* variations that actually change play are surfaced in the game setup screen
* rather than baked in. Defaults are the common North American game.
*/
@Serializable
data class EuchreOptions(
/** 24 cards (9–A) is standard; 32 (7–A) is a widespread longer variant. */
val deckSize: Int = 24,
/** Dealer must name trump rather than pass the hand out. Also called screw the dealer. */
val stickTheDealer: Boolean = true,
/** Allow a maker to play the hand without their partner for a bigger score. */
val allowGoingAlone: Boolean = true,
/** First team to this many points wins. 10 is standard; 11 and 15 are common. */
val pointsToWin: Int = 10,
) {
init {
require(deckSize == 24 || deckSize == 32) { "Euchre deck must be 24 or 32 cards" }
require(pointsToWin > 0) { "pointsToWin must be positive" }
}
}
@Serializable
enum class EuchrePhase {
/** Players may order up the turned card, in turn, starting left of the dealer. */
BID_ROUND_1,
/** The turn card is down; players may name any other suit. */
BID_ROUND_2,
/** The dealer has picked up the turn card and must discard one. */
DEALER_DISCARD,
PLAYING,
/** Five tricks played and scored; waiting to deal the next hand. */
HAND_OVER,
GAME_OVER,
}
@Serializable
data class PlayedCard(val seat: Int, val card: Card)
@Serializable
data class EuchreState(
val options: EuchreOptions,
val seed: Long,
val handNumber: Int,
val dealer: Int,
val phase: EuchrePhase,
/** Per-seat hands. Redacted to empty for seats other than the viewer. */
val hands: List<List<Card>>,
/** Card counts survive redaction so the table can still be drawn. */
val handCounts: List<Int>,
val upCard: Card?,
/** The turned-down card in round two; its suit may not be named. */
val turnedDown: Card?,
val trump: Suit?,
val maker: Int?,
val aloneSeat: Int?,
val turn: Int,
val passes: Int,
val trick: List<PlayedCard>,
val leader: Int,
val tricksWon: List<Int>,
/** Two entries: team 0 is seats 0 and 2, team 1 is seats 1 and 3. */
val scores: List<Int>,
val lastTrickWinner: Int?,
val log: List<String>,
) {
val sittingOut: Int? get() = aloneSeat?.let { partnerOf(it) }
fun isActive(seat: Int): Boolean = seat != sittingOut
val activeSeatCount: Int get() = if (aloneSeat != null) 3 else 4
}
@Serializable
sealed interface EuchreMove
@Serializable
@SerialName("pass")
data object Pass : EuchreMove
@Serializable
@SerialName("order_up")
data class OrderUp(val alone: Boolean) : EuchreMove
@Serializable
@SerialName("call_trump")
data class CallTrump(val suit: Suit, val alone: Boolean) : EuchreMove
@Serializable
@SerialName("discard")
data class Discard(val card: Card) : EuchreMove
@Serializable
@SerialName("play")
data class PlayCard(val card: Card) : EuchreMove
// ---------------------------------------------------------------------------
// Seating and card ranking
// ---------------------------------------------------------------------------
fun partnerOf(seat: Int): Int = (seat + 2) % 4
fun teamOf(seat: Int): Int = seat % 2
/** The jack of trump: the highest card in the game. */
fun isRightBower(card: Card, trump: Suit): Boolean =
card.rank == Rank.JACK && card.suit == trump
/**
* The jack of the same colour as trump. It counts as a trump card and outranks
* every trump except the right bower — the rule that catches every new player.
*/
fun isLeftBower(card: Card, trump: Suit): Boolean =
card.rank == Rank.JACK && card.suit == trump.sameColour()
/** The suit a card counts as, which is trump for the left bower. */
fun effectiveSuit(card: Card, trump: Suit?): Suit =
if (trump != null && isLeftBower(card, trump)) trump else card.suit
fun isTrumpCard(card: Card, trump: Suit?): Boolean =
trump != null && effectiveSuit(card, trump) == trump
/**
* Ranks a card within a trick. Higher wins. Cards that neither follow the led
* suit nor trump score zero and can never take the trick.
*/
fun trickStrength(card: Card, trump: Suit, ledSuit: Suit): Int = when {
isRightBower(card, trump) -> 1000
isLeftBower(card, trump) -> 900
isTrumpCard(card, trump) -> 800 + card.rank.order
effectiveSuit(card, trump) == ledSuit -> 100 + card.rank.order
else -> 0
}
/** Ranks a card in isolation, for AI hand evaluation. */
fun trumpStrength(card: Card, trump: Suit): Int = when {
isRightBower(card, trump) -> 1000
isLeftBower(card, trump) -> 900
isTrumpCard(card, trump) -> 800 + card.rank.order
else -> card.rank.order
}
@@ -0,0 +1,377 @@
package org.prolibertate.games.game.euchre
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.cards.Decks
import org.prolibertate.games.game.cards.Suit
import org.prolibertate.games.game.cards.shuffledWith
import org.prolibertate.games.game.engine.GameRules
import org.prolibertate.games.game.engine.TableConfig
import kotlin.random.Random
/**
* Euchre as a pure state machine. See RULES-euchre.md for the ruleset and the
* variants exposed through [EuchreOptions].
*/
object EuchreRules : GameRules<EuchreState, EuchreMove> {
override val gameId: String = GameCatalog.EUCHRE
private const val CARDS_PER_HAND = 5
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}
// -----------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------
override fun initialState(config: TableConfig): EuchreState {
require(config.seats.size == 4) { "Euchre is a four-handed game" }
val options = json.decodeFromString<EuchreOptions>(config.optionsJson)
return deal(
options = options,
seed = config.seed,
handNumber = 0,
dealer = 0,
scores = listOf(0, 0),
log = listOf("Hand 1 — dealer is seat 0."),
)
}
/** Deals a fresh hand and opens the first round of bidding. */
private fun deal(
options: EuchreOptions,
seed: Long,
handNumber: Int,
dealer: Int,
scores: List<Int>,
log: List<String>,
): EuchreState {
// Derived per hand so a given (seed, handNumber) always reproduces the
// same deal — handy for tests and for replaying a networked game.
val random = Random(seed + handNumber * 7919L)
val deck = Decks.euchre(options.deckSize).shuffledWith(random)
val hands = (0 until 4).map { seat ->
deck.subList(seat * CARDS_PER_HAND, (seat + 1) * CARDS_PER_HAND).toList()
}
val upCard = deck[4 * CARDS_PER_HAND]
return EuchreState(
options = options,
seed = seed,
handNumber = handNumber,
dealer = dealer,
phase = EuchrePhase.BID_ROUND_1,
hands = hands,
handCounts = hands.map { it.size },
upCard = upCard,
turnedDown = null,
trump = null,
maker = null,
aloneSeat = null,
turn = (dealer + 1) % 4,
passes = 0,
trick = emptyList(),
leader = (dealer + 1) % 4,
tricksWon = listOf(0, 0, 0, 0),
scores = scores,
lastTrickWinner = null,
log = log,
)
}
/**
* Advances from [EuchrePhase.HAND_OVER] into the next deal. Driven by the
* session controller once the finished hand has been on screen long enough
* to read, rather than by a player move.
*/
fun nextHand(state: EuchreState): EuchreState {
check(state.phase == EuchrePhase.HAND_OVER) { "Hand is not over" }
val dealer = (state.dealer + 1) % 4
return deal(
options = state.options,
seed = state.seed,
handNumber = state.handNumber + 1,
dealer = dealer,
scores = state.scores,
log = state.log + "Hand ${state.handNumber + 2} — dealer is seat $dealer.",
)
}
// -----------------------------------------------------------------------
// Turn order
// -----------------------------------------------------------------------
private fun nextActive(state: EuchreState, from: Int): Int {
var seat = (from + 1) % 4
while (seat == state.sittingOut) seat = (seat + 1) % 4
return seat
}
override fun currentSeat(state: EuchreState): Int? = when (state.phase) {
EuchrePhase.BID_ROUND_1,
EuchrePhase.BID_ROUND_2,
EuchrePhase.DEALER_DISCARD,
EuchrePhase.PLAYING,
-> state.turn
EuchrePhase.HAND_OVER, EuchrePhase.GAME_OVER -> null
}
// -----------------------------------------------------------------------
// Legal moves
// -----------------------------------------------------------------------
override fun legalMoves(state: EuchreState, seat: Int): List<EuchreMove> {
if (currentSeat(state) != seat) return emptyList()
return when (state.phase) {
EuchrePhase.BID_ROUND_1 -> buildList {
add(OrderUp(alone = false))
if (state.options.allowGoingAlone) add(OrderUp(alone = true))
add(Pass)
}
EuchrePhase.BID_ROUND_2 -> buildList {
val barred = state.turnedDown?.suit
for (suit in Suit.entries) {
if (suit == barred) continue
add(CallTrump(suit, alone = false))
if (state.options.allowGoingAlone) add(CallTrump(suit, alone = true))
}
// Stick the dealer: with three passes already in, the dealer has
// to name something rather than throw the hand in.
val dealerIsStuck =
state.options.stickTheDealer && seat == state.dealer && state.passes == 3
if (!dealerIsStuck) add(Pass)
}
EuchrePhase.DEALER_DISCARD -> state.hands[state.dealer].map { Discard(it) }
EuchrePhase.PLAYING -> playableCards(state, seat).map { PlayCard(it) }
EuchrePhase.HAND_OVER, EuchrePhase.GAME_OVER -> emptyList()
}
}
/** Follow the led suit if you can; otherwise anything goes. */
fun playableCards(state: EuchreState, seat: Int): List<Card> {
val hand = state.hands[seat]
val led = state.trick.firstOrNull() ?: return hand
val ledSuit = effectiveSuit(led.card, state.trump)
val following = hand.filter { effectiveSuit(it, state.trump) == ledSuit }
return following.ifEmpty { hand }
}
// -----------------------------------------------------------------------
// Move application
// -----------------------------------------------------------------------
override fun applyMove(state: EuchreState, seat: Int, move: EuchreMove): EuchreState {
require(currentSeat(state) == seat) { "Not seat $seat's turn" }
require(move in legalMoves(state, seat)) { "Illegal move $move for seat $seat" }
return when (move) {
is Pass -> applyPass(state, seat)
is OrderUp -> applyOrderUp(state, seat, move.alone)
is CallTrump -> applyCallTrump(state, seat, move.suit, move.alone)
is Discard -> applyDiscard(state, move.card)
is PlayCard -> applyPlay(state, seat, move.card)
}.normalised()
}
private fun EuchreState.normalised(): EuchreState = copy(handCounts = hands.map { it.size })
private fun applyPass(state: EuchreState, seat: Int): EuchreState {
val passes = state.passes + 1
val log = state.log + "Seat $seat passes."
return when (state.phase) {
EuchrePhase.BID_ROUND_1 -> if (passes >= 4) {
state.copy(
phase = EuchrePhase.BID_ROUND_2,
turnedDown = state.upCard,
upCard = null,
turn = (state.dealer + 1) % 4,
passes = 0,
log = log + "${state.upCard?.label} turned down.",
)
} else {
state.copy(turn = (seat + 1) % 4, passes = passes, log = log)
}
EuchrePhase.BID_ROUND_2 -> if (passes >= 4) {
// Nobody wanted it and the dealer wasn't stuck: throw the hand in.
deal(
options = state.options,
seed = state.seed,
handNumber = state.handNumber + 1,
dealer = (state.dealer + 1) % 4,
scores = state.scores,
log = log + "Hand thrown in; redealing.",
)
} else {
state.copy(turn = (seat + 1) % 4, passes = passes, log = log)
}
else -> error("Pass is not legal in ${state.phase}")
}
}
private fun applyOrderUp(state: EuchreState, seat: Int, alone: Boolean): EuchreState {
val upCard = requireNotNull(state.upCard) { "No turn card to order up" }
// The dealer takes the turn card into hand and will discard one back.
val hands = state.hands.toMutableList()
hands[state.dealer] = hands[state.dealer] + upCard
return state.copy(
phase = EuchrePhase.DEALER_DISCARD,
hands = hands,
trump = upCard.suit,
maker = seat,
aloneSeat = if (alone) seat else null,
upCard = null,
turn = state.dealer,
log = state.log + buildString {
append("Seat $seat orders up ${upCard.suit.symbol}")
if (alone) append(" and goes alone")
append(".")
},
)
}
private fun applyCallTrump(
state: EuchreState,
seat: Int,
suit: Suit,
alone: Boolean,
): EuchreState {
val withTrump = state.copy(
trump = suit,
maker = seat,
aloneSeat = if (alone) seat else null,
log = state.log + buildString {
append("Seat $seat names ${suit.symbol}")
if (alone) append(" and goes alone")
append(".")
},
)
return beginPlay(withTrump)
}
private fun applyDiscard(state: EuchreState, card: Card): EuchreState {
val hands = state.hands.toMutableList()
hands[state.dealer] = hands[state.dealer] - card
return beginPlay(state.copy(hands = hands, log = state.log + "Dealer discards."))
}
/** Trump is settled: clear any lone hand's partner and lead to the first trick. */
private fun beginPlay(state: EuchreState): EuchreState {
val sittingOut = state.sittingOut
val hands = state.hands.toMutableList()
if (sittingOut != null) hands[sittingOut] = emptyList()
val leader = nextActive(state, state.dealer)
return state.copy(
phase = EuchrePhase.PLAYING,
hands = hands,
leader = leader,
turn = leader,
trick = emptyList(),
passes = 0,
)
}
private fun applyPlay(state: EuchreState, seat: Int, card: Card): EuchreState {
val hands = state.hands.toMutableList()
hands[seat] = hands[seat] - card
val trick = state.trick + PlayedCard(seat, card)
val played = state.copy(hands = hands, trick = trick)
if (trick.size < state.activeSeatCount) {
return played.copy(turn = nextActive(state, seat))
}
// Trick complete: resolve it.
val trump = requireNotNull(state.trump)
val ledSuit = effectiveSuit(trick.first().card, trump)
val winner = trick.maxBy { trickStrength(it.card, trump, ledSuit) }.seat
val tricksWon = state.tricksWon.toMutableList()
tricksWon[winner] = tricksWon[winner] + 1
val afterTrick = played.copy(
trick = emptyList(),
tricksWon = tricksWon,
leader = winner,
turn = winner,
lastTrickWinner = winner,
log = state.log + "Seat $winner takes the trick.",
)
val handFinished = afterTrick.hands.all { it.isEmpty() }
return if (handFinished) scoreHand(afterTrick) else afterTrick
}
// -----------------------------------------------------------------------
// Scoring
// -----------------------------------------------------------------------
private fun scoreHand(state: EuchreState): EuchreState {
val maker = requireNotNull(state.maker)
val makerTeam = teamOf(maker)
val makerTricks = state.tricksWon.filterIndexed { seat, _ -> teamOf(seat) == makerTeam }.sum()
val scores = state.scores.toMutableList()
val note: String
if (makerTricks >= 3) {
val points = when {
makerTricks == 5 && state.aloneSeat != null -> 4
makerTricks == 5 -> 2
else -> 1
}
scores[makerTeam] = scores[makerTeam] + points
note = "Team $makerTeam took $makerTricks tricks for $points point(s)."
} else {
// Euchred: the defenders score two regardless of how it fell apart.
val defenders = 1 - makerTeam
scores[defenders] = scores[defenders] + 2
note = "Team $makerTeam is euchred — team $defenders scores 2."
}
val winner = scores.indexOfFirst { it >= state.options.pointsToWin }
return state.copy(
phase = if (winner >= 0) EuchrePhase.GAME_OVER else EuchrePhase.HAND_OVER,
scores = scores,
log = state.log + note + if (winner >= 0) listOf("Team $winner wins.") else emptyList(),
)
}
override fun isFinished(state: EuchreState): Boolean = state.phase == EuchrePhase.GAME_OVER
override fun summary(state: EuchreState): String = when (state.phase) {
EuchrePhase.GAME_OVER -> {
val winner = state.scores.indexOfFirst { it >= state.options.pointsToWin }
"Team $winner wins ${state.scores[0]}–${state.scores[1]}"
}
else -> "We ${state.scores[0]} — They ${state.scores[1]}"
}
// -----------------------------------------------------------------------
// Redaction and wire format
// -----------------------------------------------------------------------
override fun viewFor(state: EuchreState, seat: Int): EuchreState = state.copy(
hands = state.hands.mapIndexed { index, hand -> if (index == seat) hand else emptyList() },
handCounts = state.handCounts,
)
override fun encodeState(state: EuchreState): String = json.encodeToString(state)
override fun decodeState(json: String): EuchreState =
this.json.decodeFromString(json)
override fun encodeMove(move: EuchreMove): String = json.encodeToString(move)
override fun decodeMove(json: String): EuchreMove =
this.json.decodeFromString(json)
}
@@ -0,0 +1,122 @@
package org.prolibertate.games.game.sequence
import org.prolibertate.games.game.engine.GameAi
/**
* A heuristic Sequence opponent.
*
* It scores every legal placement by how much it advances one of its own runs
* and how badly it spoils an opponent's, holds its jacks back until they are
* worth spending, and never looks at anyone's hand.
*/
class SequenceAi(private val difficulty: Difficulty = Difficulty.NORMAL) :
GameAi<SequenceState, SequenceMove> {
enum class Difficulty(val blockWeight: Int, val jackPatience: Int) {
/** Builds its own runs and mostly ignores yours. */
EASY(blockWeight = 1, jackPatience = 0),
NORMAL(blockWeight = 3, jackPatience = 3),
/** Blocks aggressively and saves jacks for real threats. */
CAUTIOUS(blockWeight = 5, jackPatience = 4),
}
override fun chooseMove(
state: SequenceState,
seat: Int,
legal: List<SequenceMove>,
): SequenceMove {
require(legal.isNotEmpty()) { "No legal move for seat $seat" }
val team = state.teamOf(seat)
// Clearing a dead card is free value when nothing better is on offer.
val exchange = legal.filterIsInstance<ExchangeDeadCard>().firstOrNull()
if (exchange != null && legal.none { it is PlaceChip }) return exchange
val best = legal
.filterIsInstance<PlaceChip>()
.maxByOrNull { scorePlacement(state, it, team) }
val removal = legal
.filterIsInstance<RemoveChip>()
.maxByOrNull { threatAt(state, it.cell, state.chips[it.cell]) }
// Spend a one-eyed jack only on a genuinely dangerous chip.
if (removal != null) {
val threat = threatAt(state, removal.cell, state.chips[removal.cell])
if (threat >= difficulty.jackPatience) return removal
}
return best ?: removal ?: exchange ?: legal.first()
}
/**
* Rates placing a chip: how long a run it joins for us, plus how much of an
* opponent's run it interrupts. Wild jacks are discounted so they are not
* burned on an ordinary square.
*/
private fun scorePlacement(state: SequenceState, move: PlaceChip, team: Int): Int {
val ours = runPotential(state, move.cell, team)
val theirs = (0 until state.options.teamCount)
.filter { it != team }
.maxOfOrNull { runPotential(state, move.cell, it) }
?: 0
var score = ours * 4 + theirs * difficulty.blockWeight
// Central squares sit on more possible lines than edge squares.
val row = SequenceBoard.rowOf(move.cell)
val col = SequenceBoard.colOf(move.cell)
score += 4 - (kotlin.math.abs(row - 4) + kotlin.math.abs(col - 4)) / 2
if (isTwoEyedJack(move.card)) score -= 12
return score
}
/**
* The best run this team could still build through [cell]: the highest
* count of friendly-or-free squares in any five-window containing it, once
* windows blocked by an opponent are discarded.
*/
private fun runPotential(state: SequenceState, cell: Int, team: Int): Int {
val row = SequenceBoard.rowOf(cell)
val col = SequenceBoard.colOf(cell)
var best = 0
for ((dr, dc) in DIRECTIONS) {
for (offset in -(RUN_LENGTH - 1)..0) {
var count = 0
var blocked = false
for (step in 0 until RUN_LENGTH) {
val r = row + (offset + step) * dr
val c = col + (offset + step) * dc
if (r !in 0 until BOARD_SIZE || c !in 0 until BOARD_SIZE) {
blocked = true
break
}
val target = SequenceBoard.cellAt(r, c)
val occupant = state.chips[target]
when {
SequenceBoard.isCorner(target) -> count++
target == cell -> count++
occupant == team -> count++
occupant == NO_TEAM -> Unit
else -> {
blocked = true
}
}
if (blocked) break
}
if (!blocked && count > best) best = count
}
}
return best
}
/** How close [team] is to completing a run through [cell]. */
private fun threatAt(state: SequenceState, cell: Int, team: Int): Int =
if (team == NO_TEAM) 0 else runPotential(state, cell, team)
private companion object {
val DIRECTIONS = listOf(1 to 0, 0 to 1, 1 to 1, 1 to -1)
}
}
@@ -0,0 +1,144 @@
package org.prolibertate.games.game.sequence
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.cards.Rank
import org.prolibertate.games.game.cards.Suit
const val BOARD_SIZE = 10
const val BOARD_CELLS = BOARD_SIZE * BOARD_SIZE
const val RUN_LENGTH = 5
/** Sentinel stored in [SequenceState.chips] for an unoccupied square. */
const val NO_TEAM = -1
/**
* The printed board.
*
* IMPORTANT: this is a generated layout, not a reproduction of the commercial
* Sequence board. It satisfies every structural property the rules depend on —
* each of the 48 non-jack cards appears exactly twice, the four corners are
* free squares, and no card sits next to its own twin — so play is correct, but
* square-for-square it will not match a physical board. Replace [LAYOUT] with
* the real arrangement to match one; nothing else needs to change.
*/
object SequenceBoard {
private val LAYOUT: List<String> = listOf(
"FREE 10C 6D 4C 7C 8H 9S 10C 10H FREE",
" 3H 8S 2H 9C AH 10S 4S 5H QH 4H",
" 3S AS KD KC AC KS 3D 10D 6D KH",
" 6H 3D 3C QC 7D 8H 9D 5S 4H 6C",
" AD 5D 8S 9S 4S 2D 10H QD 5D QC",
" 7H 9D QH 2C 4C AS AD 8C 6C QS",
" 2S 6S 8D KH 7C 7S 4D 7S 3H 3S",
" 10S 4D 7H AC 2H 2C 3C 6S 2S 7D",
" 8C 10D KD 5H 9H 5C QS 8D 9H 9C",
"FREE 6H KS 2D AH 5S QD KC 5C FREE",
)
/** Card printed on each square, or null for the four free corners. */
val cells: List<Card?> = LAYOUT.flatMap { row ->
row.trim().split(Regex("\\s+")).map { token ->
if (token == "FREE") null else Card.parse(token)
}
}.also { parsed ->
require(parsed.size == BOARD_CELLS) { "Board must have $BOARD_CELLS squares" }
}
/** Squares showing a given card. Every non-jack card occupies exactly two. */
val squaresByCard: Map<Card, List<Int>> = cells
.withIndex()
.filter { it.value != null }
.groupBy({ it.value!! }, { it.index })
fun isCorner(cell: Int): Boolean = cells[cell] == null
fun rowOf(cell: Int): Int = cell / BOARD_SIZE
fun colOf(cell: Int): Int = cell % BOARD_SIZE
fun cellAt(row: Int, col: Int): Int = row * BOARD_SIZE + col
}
/** Jacks do not appear on the board; they are the two wild actions instead. */
fun isTwoEyedJack(card: Card): Boolean =
card.rank == Rank.JACK && (card.suit == Suit.DIAMONDS || card.suit == Suit.CLUBS)
fun isOneEyedJack(card: Card): Boolean =
card.rank == Rank.JACK && (card.suit == Suit.HEARTS || card.suit == Suit.SPADES)
@Serializable
data class SequenceOptions(
/** Two teams need two sequences; three teams need one. */
val teamCount: Int = 2,
val playersPerTeam: Int = 1,
val sequencesToWin: Int = 2,
/** Allow swapping a card whose squares are both taken. */
val deadCardExchange: Boolean = true,
) {
init {
require(teamCount in 2..3) { "Sequence supports two or three teams" }
require(playersPerTeam >= 1) { "Each team needs at least one player" }
require(sequencesToWin >= 1) { "sequencesToWin must be positive" }
}
val playerCount: Int get() = teamCount * playersPerTeam
}
/**
* Cards dealt per player, which shrinks as the table grows. These are the
* standard counts; unusual player counts fall back to the nearest band.
*/
fun handSizeFor(players: Int): Int = when {
players <= 2 -> 7
players <= 4 -> 6
players <= 6 -> 5
players <= 9 -> 4
else -> 3
}
@Serializable
enum class SequencePhase { PLAYING, GAME_OVER }
@Serializable
data class SequenceState(
val options: SequenceOptions,
val seed: Long,
/** Team index per seat. */
val teams: List<Int>,
/** Occupying team per square, or [NO_TEAM]. */
val chips: List<Int>,
/** Squares belonging to a completed sequence: safe from one-eyed jacks. */
val locked: List<Boolean>,
val hands: List<List<Card>>,
val handCounts: List<Int>,
val drawPile: List<Card>,
val discardPile: List<Card>,
val turn: Int,
val sequencesByTeam: List<Int>,
val winner: Int?,
val phase: SequencePhase,
/** Set once per turn when a dead card has already been exchanged. */
val exchangedThisTurn: Boolean,
val lastPlacedCell: Int?,
val log: List<String>,
) {
val playerCount: Int get() = teams.size
fun teamOf(seat: Int): Int = teams[seat]
}
@Serializable
sealed interface SequenceMove
@Serializable
@SerialName("place")
data class PlaceChip(val card: Card, val cell: Int) : SequenceMove
@Serializable
@SerialName("remove")
data class RemoveChip(val card: Card, val cell: Int) : SequenceMove
@Serializable
@SerialName("exchange")
data class ExchangeDeadCard(val card: Card) : SequenceMove
@@ -0,0 +1,302 @@
package org.prolibertate.games.game.sequence
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.cards.Card
import org.prolibertate.games.game.cards.Decks
import org.prolibertate.games.game.cards.shuffledWith
import org.prolibertate.games.game.engine.GameRules
import org.prolibertate.games.game.engine.TableConfig
import kotlin.random.Random
/**
* Sequence as a pure state machine. See RULES-sequence.md for the ruleset and
* the caveat about the board layout.
*/
object SequenceRules : GameRules<SequenceState, SequenceMove> {
override val gameId: String = GameCatalog.SEQUENCE
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}
/** The four straight lines a run of five can follow. */
private val DIRECTIONS = listOf(
1 to 0, // horizontal
0 to 1, // vertical
1 to 1, // diagonal down-right
1 to -1, // diagonal down-left
)
override fun initialState(config: TableConfig): SequenceState {
val options = json.decodeFromString<SequenceOptions>(config.optionsJson)
require(config.seats.size == options.playerCount) {
"Seat count ${config.seats.size} does not match ${options.playerCount} players"
}
val random = Random(config.seed)
var deck = Decks.double52().shuffledWith(random)
val handSize = handSizeFor(options.playerCount)
val hands = mutableListOf<List<Card>>()
for (seat in 0 until options.playerCount) {
hands += deck.take(handSize)
deck = deck.drop(handSize)
}
// Seats alternate around the table so partners are never adjacent.
val teams = (0 until options.playerCount).map { it % options.teamCount }
return SequenceState(
options = options,
seed = config.seed,
teams = teams,
chips = List(BOARD_CELLS) { NO_TEAM },
locked = List(BOARD_CELLS) { false },
hands = hands,
handCounts = hands.map { it.size },
drawPile = deck,
discardPile = emptyList(),
turn = 0,
sequencesByTeam = List(options.teamCount) { 0 },
winner = null,
phase = SequencePhase.PLAYING,
exchangedThisTurn = false,
lastPlacedCell = null,
log = listOf("Sequence — ${options.teamCount} teams, first to ${options.sequencesToWin}."),
)
}
override fun currentSeat(state: SequenceState): Int? =
if (state.phase == SequencePhase.PLAYING) state.turn else null
// -----------------------------------------------------------------------
// Legal moves
// -----------------------------------------------------------------------
override fun legalMoves(state: SequenceState, seat: Int): List<SequenceMove> {
if (currentSeat(state) != seat) return emptyList()
val team = state.teamOf(seat)
val moves = mutableListOf<SequenceMove>()
for (card in state.hands[seat].distinct()) {
when {
isTwoEyedJack(card) ->
// Wild: any empty square on the board.
for (cell in 0 until BOARD_CELLS) {
if (!SequenceBoard.isCorner(cell) && state.chips[cell] == NO_TEAM) {
moves += PlaceChip(card, cell)
}
}
isOneEyedJack(card) ->
// Removes one opposing chip that is not part of a sequence.
for (cell in 0 until BOARD_CELLS) {
val occupant = state.chips[cell]
if (occupant != NO_TEAM && occupant != team && !state.locked[cell]) {
moves += RemoveChip(card, cell)
}
}
else -> {
val squares = SequenceBoard.squaresByCard[card].orEmpty()
val open = squares.filter { state.chips[it] == NO_TEAM }
if (open.isEmpty()) {
// Dead card: both printed squares are taken.
if (state.options.deadCardExchange && !state.exchangedThisTurn) {
moves += ExchangeDeadCard(card)
}
} else {
open.forEach { moves += PlaceChip(card, it) }
}
}
}
}
return moves
}
// -----------------------------------------------------------------------
// Move application
// -----------------------------------------------------------------------
override fun applyMove(state: SequenceState, seat: Int, move: SequenceMove): SequenceState {
require(currentSeat(state) == seat) { "Not seat $seat's turn" }
require(move in legalMoves(state, seat)) { "Illegal move $move for seat $seat" }
return when (move) {
is PlaceChip -> applyPlace(state, seat, move)
is RemoveChip -> applyRemove(state, seat, move)
is ExchangeDeadCard -> applyExchange(state, seat, move)
}
}
private fun applyPlace(state: SequenceState, seat: Int, move: PlaceChip): SequenceState {
val team = state.teamOf(seat)
val chips = state.chips.toMutableList()
chips[move.cell] = team
val locked = state.locked.toMutableList()
val newSequences = claimSequences(chips, locked, move.cell, team)
val sequences = state.sequencesByTeam.toMutableList()
sequences[team] = sequences[team] + newSequences
val afterCard = discardAndDraw(state, seat, move.card)
val won = sequences[team] >= state.options.sequencesToWin
return afterCard.copy(
chips = chips,
locked = locked,
sequencesByTeam = sequences,
lastPlacedCell = move.cell,
winner = if (won) team else null,
phase = if (won) SequencePhase.GAME_OVER else SequencePhase.PLAYING,
log = afterCard.log + buildString {
append("Seat $seat plays ${move.card.label}")
if (newSequences > 0) append(" — sequence!")
append(".")
},
).advanceTurn(skip = won)
}
private fun applyRemove(state: SequenceState, seat: Int, move: RemoveChip): SequenceState {
val chips = state.chips.toMutableList()
chips[move.cell] = NO_TEAM
return discardAndDraw(state, seat, move.card)
.copy(
chips = chips,
log = state.log + "Seat $seat removes a chip with ${move.card.label}.",
)
.advanceTurn(skip = false)
}
/** Swapping a dead card costs the card but not the turn. */
private fun applyExchange(
state: SequenceState,
seat: Int,
move: ExchangeDeadCard,
): SequenceState = discardAndDraw(state, seat, move.card).copy(
exchangedThisTurn = true,
log = state.log + "Seat $seat swaps dead card ${move.card.label}.",
)
/** Moves the played card to the discard pile and replaces it from the deck. */
private fun discardAndDraw(
state: SequenceState,
seat: Int,
card: Card,
): SequenceState {
val hands = state.hands.toMutableList()
hands[seat] = hands[seat] - card
var draw = state.drawPile
var discard = state.discardPile
if (draw.isEmpty() && discard.isNotEmpty()) {
// Deck exhausted: the discards are shuffled back in and play
// continues. This happens before the card just played joins the
// pile, so a swapped dead card can never come straight back —
// which would otherwise let a player exchange the same card
// forever.
val random = Random(state.seed + state.log.size)
draw = discard.shuffledWith(random)
discard = emptyList()
}
discard = discard + card
if (draw.isNotEmpty()) {
hands[seat] = hands[seat] + draw.first()
draw = draw.drop(1)
}
return state.copy(
hands = hands,
handCounts = hands.map { it.size },
drawPile = draw,
discardPile = discard,
)
}
private fun SequenceState.advanceTurn(skip: Boolean): SequenceState =
if (skip) this
else copy(turn = (turn + 1) % playerCount, exchangedThisTurn = false)
// -----------------------------------------------------------------------
// Sequence detection
// -----------------------------------------------------------------------
/**
* Counts and locks any runs of five completed by the chip just played at
* [cell].
*
* Two sequences may share at most one chip, so a candidate run is only
* accepted when at most one of its squares is already locked. Corners are
* free squares that count for every team.
*/
private fun claimSequences(
chips: List<Int>,
locked: MutableList<Boolean>,
cell: Int,
team: Int,
): Int {
fun ownedBy(c: Int): Boolean = SequenceBoard.isCorner(c) || chips[c] == team
val row = SequenceBoard.rowOf(cell)
val col = SequenceBoard.colOf(cell)
var found = 0
for ((dr, dc) in DIRECTIONS) {
// Every window of five that includes the new chip.
for (offset in -(RUN_LENGTH - 1)..0) {
val window = (0 until RUN_LENGTH).map { step ->
val r = row + (offset + step) * dr
val c = col + (offset + step) * dc
if (r !in 0 until BOARD_SIZE || c !in 0 until BOARD_SIZE) return@map -1
SequenceBoard.cellAt(r, c)
}
if (window.any { it < 0 }) continue
if (!window.all { ownedBy(it) }) continue
// Free corners are shared by everyone and never count as the
// already-locked chip for the shared-chip limit.
val lockedInWindow = window.count { locked[it] && !SequenceBoard.isCorner(it) }
if (lockedInWindow > 1) continue
window.forEach { locked[it] = true }
found++
break // At most one new sequence per direction.
}
}
return found
}
// -----------------------------------------------------------------------
// Results, redaction and wire format
// -----------------------------------------------------------------------
override fun isFinished(state: SequenceState): Boolean =
state.phase == SequencePhase.GAME_OVER
override fun summary(state: SequenceState): String = when (val winner = state.winner) {
null -> state.sequencesByTeam
.mapIndexed { team, count -> "Team $team: $count" }
.joinToString(" ")
else -> "Team $winner wins"
}
override fun viewFor(state: SequenceState, seat: Int): SequenceState = state.copy(
hands = state.hands.mapIndexed { index, hand -> if (index == seat) hand else emptyList() },
handCounts = state.handCounts,
// The deck order is hidden information too.
drawPile = emptyList(),
)
override fun encodeState(state: SequenceState): String = json.encodeToString(state)
override fun decodeState(json: String): SequenceState = this.json.decodeFromString(json)
override fun encodeMove(move: SequenceMove): String = json.encodeToString(move)
override fun decodeMove(json: String): SequenceMove = this.json.decodeFromString(json)
}