Katan rules engine + AI (WALA-119)
CI / Build and check (pull_request) Failing after 8s

The island game as a pure-Kotlin state machine under game/catan/, wired to
the upstream GameRules / GameAi contract and fully unit-tested on the JVM.

- game/catan/: CatanModel (state, moves, phases), CatanBoard (19-hex
  geometry, seeded island generation with the 6/8 separation rule, shared
  vertex/edge graph), CatanRules (setup, production, the seven and the
  robber, domestic and maritime trade, building, development cards,
  Longest Road, Largest Army, win detection), CatanAi (a heuristic opponent
  that reads only public information).
- GameRules.isLegalMove: a defaulted structural legality check so a game
  with a combinatorial move space (Catan's trade offers) is gated the same
  way as one with an enumerated move list; MatchController uses it.
- GameCatalog.CATAN: the catalogue entry, listed but not yet available
  (descriptor and screen land with the screen task).
- Tests: 51 across CatanBoardTest, CatanRulesTest and CatanAiTest —
  geometry invariants, generation balance, setup, production, the
  seven/robber, both trade types, development-card timing, Longest Road
  edge cases, Largest Army, win detection, and AI games played to a result.
- docs/RULES-catan.md, in the per-game style, with the rule choices and
  the known gaps called out.

Two real engine bugs found and fixed while getting the suite green:
VERTEX_EDGES counted each shared edge once per adjacent hex, so an
interior vertex looked like it had six edges (which also double-counted
segments in the Longest Road search and duplicated setup moves); and the
applyRoll seven-transition was a discarded expression, so a seven never
left AWAIT_ROLL. Three test fixtures rolled from the PLAYING phase and two
assumed a two-seat rotation; corrected to the phases and seat order the
engine actually uses.

Verified: ./gradlew :app:testDebugUnitTest --offline — 679 tests, 0 failures.

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
adrianoftyriel
2026-10-14 15:13:36 +00:00
co-authored by Paperclip
parent 5c797c8807
commit 3a930f5423
12 changed files with 3376 additions and 2 deletions
@@ -0,0 +1,319 @@
package org.prolibertate.games.game.catan
import org.prolibertate.games.game.engine.GameAi
/**
* A heuristic Catan opponent.
*
* It plays a legal, mildly strategic game: it settles on the best-producing
* intersections it can reach, raises cities, chases Largest Army with its
* knights, spends its progress cards when they complete something, trades
* its surplus to the bank or the table to close a one-card gap, and robs
* whoever is winning.
*
* Honesty is a design constraint, not an accident: this runs on the host,
* where the authoritative state is fully visible. It reads only public
* information — terrain, numbers, buildings, roads, resource counts,
* dev-card counts, knights played — plus its own hand, and never looks
* into the deck, another seat's development cards, or the seed beyond the
* roll the rules derive from it.
*/
class CatanAi : GameAi<CatanState, CatanMove> {
override fun chooseMove(state: CatanState, seat: Int, legal: List<CatanMove>): CatanMove {
require(legal.isNotEmpty() || state.phase == CatanPhase.PLAYING) {
"No legal move for seat $seat"
}
return when (state.phase) {
CatanPhase.SETUP_FIRST, CatanPhase.SETUP_SECOND ->
chooseSetup(state, seat, legal.filterIsInstance<SetupPlace>())
CatanPhase.AWAIT_ROLL -> legal.first { it is RollDice }
CatanPhase.DISCARDING -> chooseDiscard(state, seat, legal.filterIsInstance<Discard>())
CatanPhase.ROBBER -> chooseRobber(state, seat, legal.filterIsInstance<MoveRobber>())
CatanPhase.FREE_ROADS -> chooseFreeRoad(state, seat, legal)
CatanPhase.TRADE_PENDING -> chooseResponse(state, seat, legal)
CatanPhase.PLAYING -> choosePlaying(state, seat, legal)
CatanPhase.GAME_OVER -> legal.firstOrNull()
?: error("The game is over; nobody chooses a move")
}
}
// -----------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------
private fun chooseSetup(state: CatanState, seat: Int, places: List<SetupPlace>): SetupPlace {
require(places.isNotEmpty()) { "No legal settlement placement" }
return places.maxByOrNull { place ->
spotValue(state, place.vertex) +
0.25 * placeDirection(state, place)
} ?: places.first()
}
/**
* Where the setup road points: the best settlement spot two edges out
* through the far end of the road. The vertex next to the new
* settlement can never hold one (the distance rule), so what a road is
* worth is what it reaches past it.
*/
private fun placeDirection(state: CatanState, place: SetupPlace): Double {
val far = CatanBoard.otherEnd(place.edge, place.vertex)
return CatanBoard.VERTEX_NEIGHBORS[far]
.filter { it != place.vertex && it !in CatanBoard.VERTEX_NEIGHBORS[place.vertex] }
.maxOfOrNull { spotValue(state, it) }
?: 0.0
}
// -----------------------------------------------------------------------
// Dice, discards and the robber
// -----------------------------------------------------------------------
private fun chooseDiscard(state: CatanState, seat: Int, discards: List<Discard>): Discard {
require(discards.isNotEmpty()) { "No legal discard" }
// Throw away what it wants least; grain and ore are the city, wool
// is mostly a dev-card tax.
return discards.minByOrNull { discard ->
discard.cards.sumOf { want(it) }
} ?: discards.first()
}
private fun chooseRobber(state: CatanState, seat: Int, moves: List<MoveRobber>): MoveRobber {
require(moves.isNotEmpty()) { "No legal robber move" }
val points = CatanRules.publicVictoryPoints(state)
return moves.maxByOrNull { move ->
val hex = CatanBoard.hexIndex.getValue(move.hex)
var score = 0.0
for (v in CatanBoard.HEX_CORNERS[hex]) {
val building = state.buildings[v] ?: continue
if (building.owner == seat) continue
val worth = if (building.type == BuildingType.CITY) 2 else 1
score += worth * CatanBoard.numberOdds(state.numbers[hex]) / 36.0
}
if (move.victim != null) {
score += 0.15 * state.resourceCount(move.victim) +
0.3 * points[move.victim]
}
score
} ?: moves.first()
}
// -----------------------------------------------------------------------
// The main phase
// -----------------------------------------------------------------------
private fun choosePlaying(state: CatanState, seat: Int, legal: List<CatanMove>): CatanMove {
// A city doubles the best production the seat already owns.
legal.filterIsInstance<BuildCity>().maxByOrNull {
spotValue(state, it.vertex)
}?.let { return it }
legal.filterIsInstance<BuildSettlement>().maxByOrNull {
spotValue(state, it.vertex)
}?.let { return it }
// A knight is worth playing whenever one is playable: it blocks an
// opponent's best hex and marches toward Largest Army.
legal.filterIsInstance<PlayKnight>().firstOrNull()?.let { return it }
yearOfPlenty(state, legal)?.let { return it }
monopoly(state, legal)?.let { return it }
// Road Building is worth two free segments whenever there is
// somewhere to put them.
if (legal.filterIsInstance<PlayRoadBuilding>().isNotEmpty() &&
legal.filterIsInstance<BuildRoad>().size >= 2
) {
return legal.filterIsInstance<PlayRoadBuilding>().first()
}
legal.filterIsInstance<BuyDevCard>().firstOrNull()?.let { return it }
// A paid road only when it reaches toward a spot worth settling.
legal.filterIsInstance<BuildRoad>()
.filter { roadValue(state, it) > 0.1 }
.maxByOrNull { roadValue(state, it) }
?.let { return it }
// A bank trade only when it completes a build this turn; trading
// four for one on spec is how hands evaporate.
legal.filterIsInstance<MaritimeTrade>()
.filter { completesBuild(state, seat, it) }
.maxByOrNull { CatanRules.bestPortRatio(state, seat, it.give) * -1.0 }
?.let { return it }
offer(state, seat)?.let { return it }
return legal.lastOrNull { it is EndTurn } ?: legal.first()
}
/** Year of Plenty: two of whatever the nearest build is shortest of. */
private fun yearOfPlenty(state: CatanState, legal: List<CatanMove>): PlayYearOfPlenty? {
val takes = legal.filterIsInstance<PlayYearOfPlenty>()
if (takes.isEmpty()) return null
val shortage = shortage(state) ?: return null
return takes.maxByOrNull { take ->
take.take.count { it == shortage } * 2 + take.take.size
}
}
/** Monopoly: declare the resource everyone else is hoarding, of the ones wanted. */
private fun monopoly(state: CatanState, legal: List<CatanMove>): PlayMonopoly? {
val plays = legal.filterIsInstance<PlayMonopoly>()
if (plays.isEmpty()) return null
val best = plays.maxByOrNull {
19 - CatanRules.bankSupply(state, it.resource) + want(it.resource)
} ?: return null
// Only worth the card when the table is actually holding a pile.
return if (19 - CatanRules.bankSupply(state, best.resource) >= 10) best else null
}
/** What the seat is shortest of for its next city, else its next settlement. */
private fun shortage(state: CatanState): Resource? {
val seat = state.turn
val targets = listOf(CatanRules.CITY_COST, CatanRules.SETTLEMENT_COST)
for (cost in targets) {
val missing = cost.entries.filter { (res, need) ->
(state.resources[seat][res] ?: 0) < need
}
if (missing.isNotEmpty()) {
return missing.maxByOrNull { (res, need) -> need - (state.resources[seat][res] ?: 0) }?.key
}
}
return null
}
private fun completesBuild(state: CatanState, seat: Int, move: MaritimeTrade): Boolean {
val hand = state.resources[seat].toMutableMap()
val ratio = CatanRules.bestPortRatio(state, seat, move.give)
hand[move.give] = (hand[move.give] ?: 0) - ratio
hand[move.get] = (hand[move.get] ?: 0) + 1
return covers(hand, CatanRules.CITY_COST) || covers(hand, CatanRules.SETTLEMENT_COST)
}
private fun covers(hand: Map<Resource, Int>, cost: Map<Resource, Int>): Boolean =
cost.all { (res, need) -> (hand[res] ?: 0) >= need }
/**
* A domestic offer for exactly the card that closes a build, paid for
* with two of the surplus — offered to whoever visibly holds the most
* of what is missing. Constructed rather than enumerated (see
* [OfferTrade]), so it is checked against the rules before it is spoken.
*
* At most one offer a turn: a declined offer changes nothing, so
* re-offering it would only bounce between the same two seats forever.
*/
private fun offer(state: CatanState, seat: Int): OfferTrade? {
if (offeredThisTurn(state, seat)) return null
val seatHand = state.resources[seat]
val builds = listOf(CatanRules.CITY_COST, CatanRules.SETTLEMENT_COST)
for (cost in builds) {
val missing = cost.entries.filter { (res, need) -> (seatHand[res] ?: 0) < need }
if (missing.size != 1) continue
val need = missing.first().key
val surplus = Resource.entries
.filter { it != need }
.filter { (seatHand[it] ?: 0) > (cost[it] ?: 0) }
.sortedByDescending { seatHand[it] ?: 0 }
if (surplus.isEmpty()) continue
val target = (0 until state.playerCount)
.filter { it != seat }
.filter { (state.resources[it][need] ?: 0) > 0 }
.maxByOrNull { state.resources[it][need] ?: 0 }
?: continue
val give = listOf(surplus.first(), surplus.first())
val trade = OfferTrade(to = target, give = give, get = listOf(need))
if (CatanRules.isLegalMove(state, seat, trade)) return trade
}
return null
}
/**
* Whether [seat] has already put an offer on the table this turn, read
* from the public log: the lines after this seat's last roll are this
* turn's, and an offer can only be spoken on the offerer's own turn.
*/
private fun offeredThisTurn(state: CatanState, seat: Int): Boolean {
val sinceRoll = state.log
.drop(state.log.indexOfLast { it.startsWith("Seat $seat rolls") } + 1)
return sinceRoll.any { it.startsWith("Seat $seat offers") }
}
// -----------------------------------------------------------------------
// Free roads and trade responses
// -----------------------------------------------------------------------
private fun chooseFreeRoad(state: CatanState, seat: Int, legal: List<CatanMove>): CatanMove {
val roads = legal.filterIsInstance<BuildRoad>()
.filter { roadValue(state, it) > 0.05 }
.maxByOrNull { roadValue(state, it) }
return roads ?: legal.firstOrNull { it is EndFreeRoads }
?: legal.filterIsInstance<BuildRoad>().firstOrNull()
?: legal.first()
}
private fun chooseResponse(state: CatanState, seat: Int, legal: List<CatanMove>): CatanMove {
val accept = legal.filterIsInstance<AcceptTrade>().firstOrNull() ?: run {
return legal.first { it is DeclineTrade }
}
val offer = state.pendingTrade ?: return legal.first()
// Accept when what arrives is worth more than what leaves: a mild
// table, not a shark.
val incoming = offer.get.sumOf { want(it) }
val outgoing = offer.give.sumOf { want(it) }
return if (incoming > outgoing) accept else legal.first { it is DeclineTrade }
}
// -----------------------------------------------------------------------
// Valuations
// -----------------------------------------------------------------------
/** What a seat would think of building on [vertex]: production and ports. */
private fun spotValue(state: CatanState, vertex: Int): Double {
if (state.buildings[vertex] != null) return -1.0
var value = 0.0
val kinds = mutableSetOf<Resource>()
for (h in CatanBoard.VERTEX_HEXES[vertex]) {
val resource = state.terrains[h].produces ?: continue
value += CatanBoard.numberOdds(state.numbers[h]) / 36.0 * want(resource)
kinds += resource
}
value += 0.12 * kinds.size // variety keeps a build plan alive
for (e in CatanBoard.VERTEX_EDGES[vertex]) {
val port = state.ports.firstOrNull { it.edge == e } ?: continue
value += if (port.resource == null) 0.1 else 0.2
}
return value
}
/**
* What a road on this edge leads to: the best settlement spot it brings
* within reach, discounted for being one step further out.
*/
private fun roadValue(state: CatanState, move: BuildRoad): Double {
var best = 0.0
val (from, to) = CatanBoard.EDGE_VERTICES[move.edge]
for (endpoint in listOf(from, to)) {
for (near in CatanBoard.VERTEX_NEIGHBORS[endpoint]) {
best = maxOf(best, spotValue(state, near) * 0.8)
}
}
return best
}
/** How much the AI wants to hold one card of [resource]. */
private fun want(resource: Resource): Double = when (resource) {
Resource.ORE -> 1.20 // the city
Resource.GRAIN -> 1.15 // the city and the dev cards
Resource.LUMBER -> 1.0 // every road and settlement
Resource.BRICK -> 0.95
Resource.WOOL -> 0.85 // abundant and only half of a dev card
}
}
@@ -0,0 +1,322 @@
package org.prolibertate.games.game.catan
import kotlinx.serialization.Serializable
import kotlin.math.atan2
import kotlin.random.Random
/**
* The island as geometry: the 19 hexes, the 54 shared vertices, the 72
* shared edges, the coast and the nine harbour positions.
*
* Everything is derived once, deterministically, from axial coordinates —
* there is no randomness and no state here; the layout of a particular
* game (which terrain and number sits on which hex) is [generate], and the
* live state lives in [CatanState].
*
* Coordinates: hexes are addressed axially ((q, r), pointy-top). Every
* position is kept on an exact integer lattice so vertices shared by
* neighbouring hexes are recognised by position instead of by floating
* point: the centre of hex (q, r) is at lattice point (2q + r, 3r), and its
* six corners follow the offsets in [CORNER_OFFSETS]. Vertex positions are
* in half-units of the hex grid; rendering scales and flips them (lattice
* +Y is toward the top of the board).
*/
object CatanBoard {
/** The 19 hexes: every (q, r) within distance 2 of the centre. */
val HEXES: List<HexCoord> = buildList {
for (r in -2..2) {
for (q in -2..2) {
if (hexDistance(q, r, 0, 0) <= 2) add(HexCoord(q, r))
}
}
}
val HEX_COUNT: Int = HEXES.size
val hexIndex: Map<HexCoord, Int> = HEXES.withIndex().associate { (i, hex) -> hex to i }
/**
* Corner k of a hex, as a lattice offset from its centre. Pointy-top:
* corner 0 is the top corner, then clockwise.
*/
private val CORNER_OFFSETS = listOf(
0 to 2, 1 to 1, 1 to -1, 0 to -2, -1 to -1, -1 to 1,
)
/** Unit steps to a hex's six neighbours, matching the corner order. */
private val NEIGHBOR_STEPS = listOf(
0 to 1, 1 to 0, 1 to -1, 0 to -1, -1 to 0, -1 to 1,
)
/** The six board-corner hexes: pairwise non-adjacent by construction. */
private val CORNER_HEXES = listOf(
HexCoord(2, 0), HexCoord(0, 2), HexCoord(-2, 2),
HexCoord(-2, 0), HexCoord(0, -2), HexCoord(2, -2),
)
// -----------------------------------------------------------------------
// Vertices and edges
// -----------------------------------------------------------------------
/** Lattice position of each vertex, by vertex id. */
val VERTEX_POS: List<Pair<Int, Int>>
val VERTEX_COUNT: Int
/** Vertex ids of hex h's six corners, corner 0 first (see [CORNER_OFFSETS]). */
val HEX_CORNERS: List<List<Int>>
/** Both endpoints of each edge, as vertex ids, low id first. */
val EDGE_VERTICES: List<Pair<Int, Int>>
val EDGE_COUNT: Int
/** Edges touching each vertex. */
val VERTEX_EDGES: List<List<Int>>
/** Vertices one edge away from each vertex: the distance rule's horizon. */
val VERTEX_NEIGHBORS: List<List<Int>>
/** Hexes touching each vertex. */
val VERTEX_HEXES: List<List<Int>>
/** Hexes touching each edge: two for interior edges, one on the coast. */
val EDGE_HEXES: List<List<Int>>
/** Edges adjacent to each edge (sharing a vertex). */
val EDGE_NEIGHBORS: List<List<Int>>
/** Hexes adjacent to each hex, in [NEIGHBOR_STEPS] order. */
val HEX_NEIGHBORS: List<List<Int>>
/** The coastal edges (those with only one hex) in ring order. */
val COASTAL: List<Int>
/** The nine fixed harbour positions, spread around the coast. */
val PORT_POSITIONS: List<Int>
init {
// Vertices: assign ids in first-seen order over hexes then corners.
val vertexIds = mutableMapOf<Pair<Int, Int>, Int>()
val vertexPos = mutableListOf<Pair<Int, Int>>()
val hexCorners = HEXES.map { hex ->
val cx = 2 * hex.q + hex.r
val cy = 3 * hex.r
CORNER_OFFSETS.map { (dx, dy) ->
val pos = (cx + dx) to (cy + dy)
vertexIds.getOrPut(pos) {
vertexPos += pos
vertexPos.size - 1
}
}
}
VERTEX_POS = vertexPos
VERTEX_COUNT = vertexPos.size
HEX_CORNERS = hexCorners
// Edges between a hex's consecutive corners, deduplicated by the
// pair of vertex ids.
val edgeIds = mutableMapOf<Pair<Int, Int>, Int>()
val edgeVertices = mutableListOf<Pair<Int, Int>>()
hexCorners.forEach { corners ->
for (k in 0..5) {
val a = corners[k]
val b = corners[(k + 1) % 6]
val key = minOf(a, b) to maxOf(a, b)
edgeIds.getOrPut(key) {
edgeVertices += key
edgeVertices.size - 1
}
}
}
EDGE_VERTICES = edgeVertices
EDGE_COUNT = edgeVertices.size
val vertexEdges = List(VERTEX_COUNT) { mutableListOf<Int>() }
val vertexHexes = List(VERTEX_COUNT) { mutableSetOf<Int>() }
val edgeHexes = List(EDGE_COUNT) { mutableSetOf<Int>() }
hexCorners.forEachIndexed { h, corners ->
corners.forEach { v -> vertexHexes[v] += h }
for (k in 0..5) {
val a = corners[k]
val b = corners[(k + 1) % 6]
val key = minOf(a, b) to maxOf(a, b)
val e = edgeIds.getValue(key)
edgeHexes[e] += h
vertexEdges[a] += e
vertexEdges[b] += e
}
}
// Distinct: an interior edge is walked once from each of the two hexes
// it separates, so without this every shared edge would be counted
// twice and an interior vertex would appear to have six edges.
VERTEX_EDGES = vertexEdges.map { it.distinct() }
VERTEX_HEXES = vertexHexes.map { it.sorted() }
EDGE_HEXES = edgeHexes.map { it.sorted() }
VERTEX_NEIGHBORS = List(VERTEX_COUNT) { v ->
VERTEX_EDGES[v].map { otherEnd(it, v) }.distinct().sorted()
}
EDGE_NEIGHBORS = List(EDGE_COUNT) { e ->
val (a, b) = EDGE_VERTICES[e]
(VERTEX_EDGES[a] + VERTEX_EDGES[b]).distinct().filter { it != e }.sorted()
}
HEX_NEIGHBORS = HEXES.map { hex ->
NEIGHBOR_STEPS.mapNotNull { (dq, dr) ->
hexIndex[HexCoord(hex.q + dq, hex.r + dr)]
}
}
// The coast in walking order: sort the coastal edges by the angle of
// their midpoint around the board centre, which is the lattice
// origin. The board is a hexagon, so this yields one closed ring.
COASTAL = EDGE_HEXES.withIndex()
.filter { it.value.size == 1 }
.map { (e, _) -> e }
.sortedBy { e -> angleOf(midpoint(e)) }
// Harbours sit roughly every third or fourth coastal edge, like the
// physical frame: nine positions, steps summing to the whole ring.
PORT_POSITIONS = buildList {
var at = 0
for (step in listOf(3, 4, 3, 3, 4, 3, 3, 4, 3)) {
add(COASTAL[at % COASTAL.size])
at += step
}
}.distinct()
check(HEX_COUNT == 19) { "A Catan island has 19 hexes, found $HEX_COUNT" }
check(VERTEX_COUNT == 54) { "A Catan island has 54 vertices, found $VERTEX_COUNT" }
check(EDGE_COUNT == 72) { "A Catan island has 72 edges, found $EDGE_COUNT" }
check(COASTAL.size == 30) { "The coast has 30 edges, found ${COASTAL.size}" }
check(PORT_POSITIONS.size == 9) { "Nine harbours, found ${PORT_POSITIONS.size}" }
check(PORT_POSITIONS.all { EDGE_HEXES[it].size == 1 }) { "Harbours must be coastal" }
}
/** The other endpoint of [edge], given one [vertex] on it. */
fun otherEnd(edge: Int, vertex: Int): Int {
val (a, b) = EDGE_VERTICES[edge]
return if (vertex == a) b else a
}
/** Lattice position of hex h's centre. */
fun hexCenter(h: Int): Pair<Int, Int> {
val hex = HEXES[h]
return (2 * hex.q + hex.r) to (3 * hex.r)
}
/** Whether two hexes share an edge. */
fun hexesAdjacent(a: Int, b: Int): Boolean = b in HEX_NEIGHBORS[a]
/** Hex-grid distance between two axial positions. */
fun hexDistance(q1: Int, r1: Int, q2: Int, r2: Int): Int {
val dq = q1 - q2
val dr = r1 - r2
return maxOf(kotlin.math.abs(dq), kotlin.math.abs(dr), kotlin.math.abs(dq + dr))
}
/**
* How often a number is expected to come up, in thirty-sixths. A 6 or an
* 8 comes up five times in thirty-six, a 2 or a 12 once.
*/
fun numberOdds(number: Int): Int = 6 - kotlin.math.abs(7 - number)
private fun midpoint(edge: Int): Pair<Double, Double> {
val (a, b) = EDGE_VERTICES[edge]
val pa = VERTEX_POS[a]
val pb = VERTEX_POS[b]
return ((pa.first + pb.first) / 2.0) to ((pa.second + pb.second) / 2.0)
}
private fun angleOf(point: Pair<Double, Double>): Double =
atan2(point.second, point.first)
// -----------------------------------------------------------------------
// Island generation
// -----------------------------------------------------------------------
/**
* The island layout for one game: terrain and number per hex, the robber
* on the desert, and the nine harbours.
*/
@Serializable
data class Generated(
val terrains: List<Terrain>,
/** 0 where there is no token (the desert). */
val numbers: List<Int>,
val robber: Int,
val ports: List<Port>,
)
/** The terrain tile mix: four forests, four pastures, four fields, three hills, three mountains, one desert. */
private val TERRAIN_TILES: List<Terrain> = listOf(
Terrain.FOREST, Terrain.FOREST, Terrain.FOREST, Terrain.FOREST,
Terrain.PASTURE, Terrain.PASTURE, Terrain.PASTURE, Terrain.PASTURE,
Terrain.FIELDS, Terrain.FIELDS, Terrain.FIELDS, Terrain.FIELDS,
Terrain.HILLS, Terrain.HILLS, Terrain.HILLS,
Terrain.MOUNTAINS, Terrain.MOUNTAINS, Terrain.MOUNTAINS,
Terrain.DESERT,
)
/** The 18 number tokens, the two hardest numbers withheld: 7 never appears. */
private val RED_TOKENS = listOf(6, 6, 8, 8)
private val OTHER_TOKENS = listOf(2, 3, 3, 4, 4, 5, 5, 9, 9, 10, 10, 11, 11, 12)
/** Shuffle attempts before falling back to the corner placement for 6s and 8s. */
private const val RED_ATTEMPTS = 60
/**
* Generates the island from [seed].
*
* Terrain is shuffled over the hexes, exactly as shuffling the land
* tiles face down does. Number tokens are shuffled over the land hexes
* with one repair rule: no two of the red tokens (6 and 8) may sit on
* adjacent hexes, the balance convention the published game asks for.
* The robber starts on the desert. Harbour *positions* are fixed (the
* physical frame is not shuffled); the nine harbour *types* — five
* 2:1 resource ports and four 3:1 ports — are shuffled onto them.
*
* The 6/8 separation is guaranteed, not merely probable: if no shuffled
* placement separates them (about one shuffle in five does), the red
* tokens go to four of the six board-corner hexes, which are pairwise
* non-adjacent, and at most one corner can be desert.
*/
fun generate(seed: Long): Generated {
val random = Random(seed)
val terrains = TERRAIN_TILES.shuffled(random)
val desert = terrains.indexOf(Terrain.DESERT)
val land = terrains.indices.filter { it != desert }
var redHexes: List<Int>? = null
var attempt = 0
while (redHexes == null && attempt < RED_ATTEMPTS) {
val candidate = land.shuffled(random).take(4)
val separated = candidate.withIndex().all { (i, a) ->
candidate.drop(i + 1).none { hexesAdjacent(a, it) }
}
if (separated) redHexes = candidate
attempt++
}
val reds = redHexes ?: CORNER_HEXES
.mapNotNull { hexIndex[it] }
.filter { it != desert }
.shuffled(random)
.take(4)
val numbers = IntArray(HEX_COUNT)
RED_TOKENS.forEachIndexed { i, token -> numbers[reds[i]] = token }
val rest = land.filter { it !in reds }.shuffled(random)
OTHER_TOKENS.forEachIndexed { i, token -> numbers[rest[i]] = token }
val portTypes = (
listOf(
Resource.LUMBER, Resource.BRICK, Resource.WOOL, Resource.GRAIN, Resource.ORE,
) + List(4) { null }
).shuffled(random)
val ports = PORT_POSITIONS.mapIndexed { i, edge ->
val resource = portTypes[i]
if (resource == null) Port(edge, null, 3) else Port(edge, resource, 2)
}
return Generated(terrains, numbers.toList(), desert, ports)
}
}
@@ -0,0 +1,307 @@
package org.prolibertate.games.game.catan
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/** Sentinel stored in [CatanState.roads] for an unclaimed road position. */
const val NO_PLAYER = -1
/** Road segments required to hold Longest Road. */
const val LONGEST_ROAD_MIN = 5
/** Knights required to take Largest Army. */
const val LARGEST_ARMY_MIN = 3
/** Resource cards of each type the bank starts with. */
const val BANK_PER_RESOURCE = 19
/**
* The five resources the island produces.
*
* Catan names two of them after the terrain rather than the commodity
* (wood becomes lumber, sheep become wool); those names travel with the
* trademark, so the engine speaks in resources only.
*/
@Serializable
enum class Resource { LUMBER, BRICK, WOOL, GRAIN, ORE }
/** One terrain type per hex; the desert produces nothing. */
@Serializable
enum class Terrain(val produces: Resource?) {
FOREST(Resource.LUMBER),
PASTURE(Resource.WOOL),
FIELDS(Resource.GRAIN),
HILLS(Resource.BRICK),
MOUNTAINS(Resource.ORE),
DESERT(null),
}
/** Axial coordinate of one hex on the board. See [CatanBoard]. */
@Serializable
data class HexCoord(val q: Int, val r: Int)
@Serializable
enum class BuildingType { SETTLEMENT, CITY }
/** What stands on one vertex: a settlement or city owned by one seat. */
@Serializable
data class CatanBuilding(val type: BuildingType, val owner: Int)
/**
* One harbour. A port sits on a coastal edge: a player who owns a
* settlement or city on *either* endpoint vertex of [edge] may trade at
* [ratio] (2 or 3) instead of the bank's 4:1. A resource port trades at 2:1
* for its own resource only; [resource] is null for a generic 3:1 harbour.
*/
@Serializable
data class Port(val edge: Int, val resource: Resource?, val ratio: Int)
@Serializable
enum class DevCardType { KNIGHT, ROAD_BUILDING, MONOPOLY, YEAR_OF_PLENTY, VICTORY_POINT }
/**
* One development card. [id] is stable for the life of the game (the deck
* is built once from the seed), so moves can name a card by id even after
* it moves from the deck into a hand. [boughtTurn] records when it was
* drawn: a card cannot be played on the turn it was bought.
*/
@Serializable
data class DevCard(val id: Int, val type: DevCardType, val boughtTurn: Int = 0)
/**
* A domestic trade offer on the table. [by] is the offering seat and [to]
* the only seat that may respond — v1 has no counter-offers and no open
* auctions, so an offer is always addressed to one player.
*/
@Serializable
data class TradeOffer(val by: Int, val to: Int, val give: List<Resource>, val get: List<Resource>)
/**
* Where the game stands. The phases that involve more than the player
* whose turn it is carry their own bookkeeping: [discardSeat] during
* [CatanPhase.DISCARDING], [pendingTrade] during [CatanPhase.TRADE_PENDING].
*/
@Serializable
enum class CatanPhase {
/** Snake order forward: settlement + road each, seats 0..n-1. */
SETUP_FIRST,
/** Snake order back: settlement + road each, seats n-1..0, plus income. */
SETUP_SECOND,
/** The player whose turn it is must roll the dice. */
AWAIT_ROLL,
/** Players holding more than 7 resource cards discard half. */
DISCARDING,
/** The roller must move the robber and steal. */
ROBBER,
/** Build, trade, buy and play development cards, or end the turn. */
PLAYING,
/** A played Road Building card: up to two roads remain to be placed. */
FREE_ROADS,
/** The offered seat must accept or decline. */
TRADE_PENDING,
GAME_OVER,
}
@Serializable
data class CatanOptions(
val playerCount: Int = 3,
val pointsToWin: Int = 10,
) {
init {
require(playerCount in 3..4) { "The island seats three or four players" }
require(pointsToWin >= 2) { "pointsToWin must be at least 2" }
}
}
/**
* The whole game as one immutable value.
*
* Public information (terrain, numbers, ports, buildings, roads, resource
* counts, dev-card counts, knights played) is stored directly. Hidden
* information — the deck's order and every hand's development cards — is
* here in full because the host owns the truth; [CatanRules.viewFor] is
* what keeps it off the wire.
*/
@Serializable
data class CatanState(
val options: CatanOptions,
val seed: Long,
val phase: CatanPhase,
/**
* The seat whose turn it is — not always the seat expected to move:
* during [CatanPhase.DISCARDING] and [CatanPhase.TRADE_PENDING] another
* seat acts on the turn owner's behalf.
*/
val turn: Int,
/** How many setup placements are done, 0 until 2 * playerCount. */
val setupIndex: Int,
/** Monotonic turn counter, 0 during setup, 1 from the first real turn. */
val turnNumber: Int,
/** Terrain per hex, indexed like [CatanBoard.HEXES]. */
val terrains: List<Terrain>,
/** Number token per hex, 0 where there is none (the desert). */
val numbers: List<Int>,
/** Hex the robber currently occupies. */
val robber: Int,
val ports: List<Port>,
/** What stands on each vertex, or null. */
val buildings: List<CatanBuilding?>,
/** Owning seat per edge, or [NO_PLAYER]. */
val roads: List<Int>,
/** Resource cards per seat. Card counts are public in Catan. */
val resources: List<Map<Resource, Int>>,
/** The bank's development cards, top first. Order is hidden. */
val devDeck: List<DevCard>,
/** Development cards per seat. Hidden from everyone but the holder. */
val devHands: List<List<DevCard>>,
/** Public mirror of the dev-hand sizes, for views and scoreboards. */
val devHandCounts: List<Int>,
/** Knights played (not merely held) per seat. */
val knightsPlayed: List<Int>,
/** Whether the turn owner has already played a development card. */
val devCardPlayedThisTurn: Boolean,
val pendingTrade: TradeOffer?,
/** Roads still owed on a played Road Building card. */
val pendingFreeRoads: Int,
/** Seat due to discard during [CatanPhase.DISCARDING]. */
val discardSeat: Int?,
val longestRoadOwner: Int?,
val largestArmyOwner: Int?,
/** The dice as last rolled, for the table display. */
val lastDice: List<Int>,
/**
* How many dice rolls and steals have happened so far. Random events are
* derived from the seed and this counter, so the same game replays
* identically without storing a random generator in the state.
*/
val rngStep: Int,
val winner: Int?,
val log: List<String>,
) {
val playerCount: Int get() = options.playerCount
/** Total resource cards held by [seat]. */
fun resourceCount(seat: Int): Int = resources[seat].values.sum()
/** [seat]'s resource cards as a flat list, one entry per card. */
fun handOf(seat: Int): List<Resource> =
Resource.entries.flatMap { res -> List(resources[seat][res] ?: 0) { res } }
/** Whether [seat] holds every card in [cards], counting duplicates. */
fun holdsAll(seat: Int, cards: List<Resource>): Boolean {
val need = cards.groupingBy { it }.eachCount()
return need.all { (res, n) -> (resources[seat][res] ?: 0) >= n }
}
}
@Serializable
sealed interface CatanMove
/** Setup placement: a settlement on [vertex] plus a road on [edge]. */
@Serializable
@SerialName("setup")
data class SetupPlace(val vertex: Int, val edge: Int) : CatanMove
/**
* Roll the dice.
*
* With [forced] null the roll is derived from the game seed, which is what
* the AI, the UI and the network always send. [forced] exists so tests and
* offline reviews can stage a specific number; it is not part of the
* enumerated move list, so the network driver's "is this move in the legal
* list" check rejects any forced roll a client tries to sneak through —
* only code holding the state directly (the host's own tests) can use it.
*/
@Serializable
@SerialName("roll")
data class RollDice(val forced: List<Int>? = null) : CatanMove
/** Discard exactly these cards. */
@Serializable
@SerialName("discard")
data class Discard(val cards: List<Resource>) : CatanMove
/** Move the robber to [hex] and steal from [victim], if anyone can be robbed. */
@Serializable
@SerialName("robber")
data class MoveRobber(val hex: HexCoord, val victim: Int? = null) : CatanMove
/** Build a road on [edge] — paid normally, or free during FREE_ROADS. */
@Serializable
@SerialName("road")
data class BuildRoad(val edge: Int) : CatanMove
@Serializable
@SerialName("settlement")
data class BuildSettlement(val vertex: Int) : CatanMove
@Serializable
@SerialName("city")
data class BuildCity(val vertex: Int) : CatanMove
@Serializable
@SerialName("buyCard")
data object BuyDevCard : CatanMove
/**
* Play a knight. The card is named by [card] id; the robber move follows as
* its own move once the phase has advanced.
*/
@Serializable
@SerialName("knight")
data class PlayKnight(val card: Int) : CatanMove
@Serializable
@SerialName("roadBuilding")
data class PlayRoadBuilding(val card: Int) : CatanMove
@Serializable
@SerialName("monopoly")
data class PlayMonopoly(val card: Int, val resource: Resource) : CatanMove
/** Take [take] (up to two cards) from the bank. */
@Serializable
@SerialName("plenty")
data class PlayYearOfPlenty(val card: Int, val take: List<Resource>) : CatanMove
/**
* Offer a domestic trade to [to]: [give] of ours for [get] of theirs.
*
* Like a forced dice roll this is a free-form intent rather than an
* enumerated move — the space of two card multisets is combinatorial — so
* it is validated structurally by [CatanRules.isLegalMove] instead of
* appearing in [CatanRules.legalMoves].
*/
@Serializable
@SerialName("offer")
data class OfferTrade(val to: Int, val give: List<Resource>, val get: List<Resource>) : CatanMove
@Serializable
@SerialName("accept")
data object AcceptTrade : CatanMove
@Serializable
@SerialName("decline")
data object DeclineTrade : CatanMove
/** Bank trade: [give] at the best ratio this seat can trade at for [get]. */
@Serializable
@SerialName("bank")
data class MaritimeTrade(val give: Resource, val get: Resource) : CatanMove
@Serializable
@SerialName("endTurn")
data object EndTurn : CatanMove
/** Forfeit any remaining free roads from a played Road Building card. */
@Serializable
@SerialName("endFreeRoads")
data object EndFreeRoads : CatanMove
@@ -0,0 +1,905 @@
package org.prolibertate.games.game.catan
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.engine.GameRules
import org.prolibertate.games.game.engine.TableConfig
import kotlin.random.Random
/**
* Catan as a pure state machine. See RULES-catan.md for the ruleset and the
* choices made where the published rules leave room.
*
* The rules the engine enforces come from the base game as published for
* three to four players: setup in snake order, one roll per turn,
* production weighted by number tokens, the robber on a seven, domestic
* and bank trade, building, development cards, Longest Road, Largest Army
* and victory at ten points.
*/
object CatanRules : GameRules<CatanState, CatanMove> {
override val gameId: String = GameCatalog.CATAN
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}
// -----------------------------------------------------------------------
// Public constants the AI and the UI plan with
// -----------------------------------------------------------------------
val ROAD_COST: Map<Resource, Int> = mapOf(Resource.LUMBER to 1, Resource.BRICK to 1)
val SETTLEMENT_COST: Map<Resource, Int> = mapOf(
Resource.LUMBER to 1, Resource.BRICK to 1, Resource.WOOL to 1, Resource.GRAIN to 1,
)
val CITY_COST: Map<Resource, Int> = mapOf(Resource.GRAIN to 2, Resource.ORE to 3)
val DEV_COST: Map<Resource, Int> = mapOf(Resource.WOOL to 1, Resource.GRAIN to 1, Resource.ORE to 1)
/** The 25 development cards in the bank's deck: 14 knights, two of each progress card, five victory points. */
val DEV_DECK: List<DevCardType> = List(14) { DevCardType.KNIGHT } +
List(2) { DevCardType.ROAD_BUILDING } +
List(2) { DevCardType.MONOPOLY } +
List(2) { DevCardType.YEAR_OF_PLENTY } +
List(5) { DevCardType.VICTORY_POINT }
// -----------------------------------------------------------------------
// Life cycle
// -----------------------------------------------------------------------
override fun initialState(config: TableConfig): CatanState {
val options = json.decodeFromString<CatanOptions>(config.optionsJson)
require(config.seats.size == options.playerCount) {
"Seat count ${config.seats.size} does not match ${options.playerCount} players"
}
val board = CatanBoard.generate(config.seed)
// A different random stream than the island, so the same seed still
// produces both a fixed island and a fixed deck.
val devDeck = DEV_DECK
.mapIndexed { id, type -> DevCard(id, type) }
.shuffled(Random(config.seed + 1))
return CatanState(
options = options,
seed = config.seed,
phase = CatanPhase.SETUP_FIRST,
turn = 0,
setupIndex = 0,
turnNumber = 0,
terrains = board.terrains,
numbers = board.numbers,
robber = board.robber,
ports = board.ports,
buildings = List(CatanBoard.VERTEX_COUNT) { null },
roads = List(CatanBoard.EDGE_COUNT) { NO_PLAYER },
resources = List(options.playerCount) {
Resource.entries.associateWith { 0 }
},
devDeck = devDeck,
devHands = List(options.playerCount) { emptyList() },
devHandCounts = List(options.playerCount) { 0 },
knightsPlayed = List(options.playerCount) { 0 },
devCardPlayedThisTurn = false,
pendingTrade = null,
pendingFreeRoads = 0,
discardSeat = null,
longestRoadOwner = null,
largestArmyOwner = null,
lastDice = emptyList(),
rngStep = 0,
winner = null,
log = listOf(
"Catan — ${options.playerCount} players, first to ${options.pointsToWin} victory points.",
),
)
}
override fun currentSeat(state: CatanState): Int? = when (state.phase) {
CatanPhase.GAME_OVER -> null
CatanPhase.SETUP_FIRST -> state.setupIndex
CatanPhase.SETUP_SECOND -> 2 * state.playerCount - 1 - state.setupIndex
CatanPhase.DISCARDING -> state.discardSeat
CatanPhase.TRADE_PENDING -> state.pendingTrade?.to
CatanPhase.AWAIT_ROLL, CatanPhase.ROBBER,
CatanPhase.PLAYING, CatanPhase.FREE_ROADS,
-> state.turn
}
// -----------------------------------------------------------------------
// Legality
// -----------------------------------------------------------------------
/**
* Structural legality, the form the network driver and the UI should
* gate through.
*
* Two moves are free-form intents rather than members of the enumerated
* move list, because enumerating them would explode combinatorially:
* a dice roll may carry forced values (tests and offline reviews only —
* over the network the driver's membership check rejects it), and a
* domestic trade offer names any two multisets of resource cards.
*/
override fun isLegalMove(state: CatanState, seat: Int, move: CatanMove): Boolean {
if (currentSeat(state) != seat) return false
return when (move) {
is RollDice -> state.phase == CatanPhase.AWAIT_ROLL &&
(move.forced == null ||
(move.forced.size == 2 && move.forced.all { it in 1..6 }))
is OfferTrade -> offerLegal(state, seat, move)
else -> move in legalMoves(state, seat)
}
}
override fun legalMoves(state: CatanState, seat: Int): List<CatanMove> {
if (currentSeat(state) != seat) return emptyList()
return when (state.phase) {
CatanPhase.SETUP_FIRST, CatanPhase.SETUP_SECOND -> setupMoves(state)
CatanPhase.AWAIT_ROLL -> listOf(RollDice())
CatanPhase.DISCARDING -> discardMoves(state, seat)
CatanPhase.ROBBER -> robberMoves(state, seat)
CatanPhase.PLAYING -> playingMoves(state, seat)
CatanPhase.FREE_ROADS ->
roadMoves(state, seat) + listOf<CatanMove>(EndFreeRoads)
CatanPhase.TRADE_PENDING -> tradeResponses(state, seat)
CatanPhase.GAME_OVER -> emptyList()
}
}
private fun setupMoves(state: CatanState): List<SetupPlace> {
val moves = mutableListOf<SetupPlace>()
for (v in 0 until CatanBoard.VERTEX_COUNT) {
if (!vertexOpenForSettlement(state, v)) continue
for (e in CatanBoard.VERTEX_EDGES[v]) {
if (state.roads[e] != NO_PLAYER) continue
moves += SetupPlace(v, e)
}
}
return moves
}
private fun discardMoves(state: CatanState, seat: Int): List<Discard> {
val total = state.resourceCount(seat)
if (total <= 7) return emptyList()
val half = total / 2
val held = state.resources[seat]
val moves = mutableListOf<Discard>()
fun walk(resourceIndex: Int, remaining: Int, acc: MutableList<Resource>) {
if (resourceIndex == Resource.entries.size) {
if (remaining == 0) moves += Discard(acc.toList())
return
}
val resource = Resource.entries[resourceIndex]
val have = held[resource] ?: 0
for (take in 0..minOf(have, remaining)) {
repeat(take) { acc += resource }
walk(resourceIndex + 1, remaining - take, acc)
repeat(take) { acc.removeAt(acc.size - 1) }
}
}
walk(0, half, mutableListOf())
return moves
}
private fun robberMoves(state: CatanState, seat: Int): List<MoveRobber> {
val moves = mutableListOf<MoveRobber>()
for (h in 0 until CatanBoard.HEX_COUNT) {
if (h == state.robber) continue
val victims = CatanBoard.HEX_CORNERS[h]
.mapNotNull { state.buildings[it] }
.map { it.owner }
.filter { it != seat }
.distinct()
.filter { state.resourceCount(it) > 0 }
if (victims.isEmpty()) {
moves += MoveRobber(CatanBoard.HEXES[h])
} else {
victims.forEach { moves += MoveRobber(CatanBoard.HEXES[h], it) }
}
}
return moves
}
private fun playingMoves(state: CatanState, seat: Int): List<CatanMove> {
val moves = mutableListOf<CatanMove>()
if (affordable(state, seat, ROAD_COST)) moves += roadMoves(state, seat)
if (affordable(state, seat, SETTLEMENT_COST)) {
moves += settlementVertices(state, seat).map { BuildSettlement(it) }
}
if (affordable(state, seat, CITY_COST)) {
moves += cityVertices(state, seat).map { BuildCity(it) }
}
if (state.devDeck.isNotEmpty() && affordable(state, seat, DEV_COST)) {
moves += BuyDevCard
}
if (!state.devCardPlayedThisTurn) {
for (card in state.devHands[seat]) {
if (card.boughtTurn == state.turnNumber) continue
when (card.type) {
DevCardType.KNIGHT -> moves += PlayKnight(card.id)
DevCardType.ROAD_BUILDING -> moves += PlayRoadBuilding(card.id)
DevCardType.MONOPOLY -> Resource.entries.forEach {
moves += PlayMonopoly(card.id, it)
}
DevCardType.YEAR_OF_PLENTY -> moves += plentyTakes(state).map {
PlayYearOfPlenty(card.id, it)
}
DevCardType.VICTORY_POINT -> Unit // revealed by winning, never played
}
}
}
for (give in Resource.entries) {
if ((state.resources[seat][give] ?: 0) < bestPortRatio(state, seat, give)) continue
for (get in Resource.entries) {
if (get == give || bankSupply(state, get) < 1) continue
moves += MaritimeTrade(give, get)
}
}
moves += EndTurn
return moves
}
/** Every take a Year of Plenty card could name: one card, or two. */
private fun plentyTakes(state: CatanState): List<List<Resource>> {
val takes = mutableListOf<List<Resource>>()
for (a in Resource.entries) {
if (bankSupply(state, a) >= 1) takes += listOf(a)
for (b in Resource.entries) {
// Two of a kind needs a bank that can pay both, not just one.
val needOfB = if (a == b) 2 else 1
if (bankSupply(state, a) >= 1 && bankSupply(state, b) >= needOfB) {
takes += listOf(a, b)
}
}
}
return takes
}
/** Road placements that connect to [seat]'s network, cost aside. */
private fun roadMoves(state: CatanState, seat: Int): List<BuildRoad> =
(0 until CatanBoard.EDGE_COUNT)
.filter { state.roads[it] == NO_PLAYER && roadConnects(state, seat, it) }
.map { BuildRoad(it) }
/**
* Settlement placements: an open vertex at least two edges from every
* building, connected to [seat]'s road network. (During setup the
* connection requirement does not apply — that is why setup uses its
* own move.)
*/
private fun settlementVertices(state: CatanState, seat: Int): List<Int> =
(0 until CatanBoard.VERTEX_COUNT).filter { v ->
vertexOpenForSettlement(state, v) &&
CatanBoard.VERTEX_EDGES[v].any { state.roads[it] == seat }
}
private fun cityVertices(state: CatanState, seat: Int): List<Int> =
(0 until CatanBoard.VERTEX_COUNT).filter { v ->
state.buildings[v] == CatanBuilding(BuildingType.SETTLEMENT, seat)
}
private fun tradeResponses(state: CatanState, seat: Int): List<CatanMove> {
val offer = state.pendingTrade ?: return emptyList()
val responses = mutableListOf<CatanMove>()
if (state.holdsAll(seat, offer.get) && state.holdsAll(offer.by, offer.give)) {
responses += AcceptTrade
}
responses += DeclineTrade
return responses
}
/** An empty vertex with no building on it or one edge away. */
private fun vertexOpenForSettlement(state: CatanState, v: Int): Boolean =
state.buildings[v] == null &&
CatanBoard.VERTEX_NEIGHBORS[v].all { state.buildings[it] == null }
/** A road on [edge] would join [seat]'s network of roads and buildings. */
private fun roadConnects(state: CatanState, seat: Int, edge: Int): Boolean {
val (a, b) = CatanBoard.EDGE_VERTICES[edge]
return CatanBoard.VERTEX_EDGES[a].any { state.roads[it] == seat } ||
CatanBoard.VERTEX_EDGES[b].any { state.roads[it] == seat } ||
state.buildings[a]?.owner == seat ||
state.buildings[b]?.owner == seat
}
private fun offerLegal(state: CatanState, seat: Int, move: OfferTrade): Boolean {
if (state.phase != CatanPhase.PLAYING || state.turn != seat) return false
if (move.to !in 0 until state.playerCount || move.to == seat) return false
if (move.give.isEmpty() || move.get.isEmpty()) return false
// Like-for-like is not a trade; the published game rejects it too.
if (countOf(move.give) == countOf(move.get)) return false
return state.holdsAll(seat, move.give)
}
// -----------------------------------------------------------------------
// Move application
// -----------------------------------------------------------------------
override fun applyMove(state: CatanState, seat: Int, move: CatanMove): CatanState {
require(currentSeat(state) == seat) {
"Not seat $seat's move in phase ${state.phase}"
}
require(isLegalMove(state, seat, move)) { "Illegal move $move for seat $seat" }
return when (move) {
is SetupPlace -> applySetup(state, seat, move)
is RollDice -> applyRoll(state, seat, move)
is Discard -> applyDiscard(state, seat, move)
is MoveRobber -> applyRobber(state, seat, move)
is BuildRoad -> applyBuildRoad(state, seat, move)
is BuildSettlement -> applyBuildSettlement(state, seat, move)
is BuildCity -> applyBuildCity(state, seat, move)
BuyDevCard -> applyBuyDevCard(state, seat)
is PlayKnight -> applyPlayKnight(state, seat, move)
is PlayRoadBuilding -> applyPlayRoadBuilding(state, seat, move)
is PlayMonopoly -> applyPlayMonopoly(state, seat, move)
is PlayYearOfPlenty -> applyPlayYearOfPlenty(state, seat, move)
is OfferTrade -> applyOfferTrade(state, seat, move)
AcceptTrade -> applyAcceptTrade(state, seat)
DeclineTrade -> applyDeclineTrade(state, seat)
is MaritimeTrade -> applyMaritimeTrade(state, seat, move)
EndTurn -> applyEndTurn(state, seat)
EndFreeRoads -> applyEndFreeRoads(state, seat)
}
}
private fun applySetup(state: CatanState, seat: Int, move: SetupPlace): CatanState {
val n = state.playerCount
val second = state.phase == CatanPhase.SETUP_SECOND
var s = state.copy(
buildings = state.buildings.toMutableList().also {
it[move.vertex] = CatanBuilding(BuildingType.SETTLEMENT, seat)
},
roads = state.roads.toMutableList().also { it[move.edge] = seat },
log = state.log + "Seat $seat settles at ${move.vertex} and lays a road on ${move.edge}.",
)
if (second) {
// The second settlement earns one card from each adjacent
// producing hex, supply permitting.
val adjacent = CatanBoard.VERTEX_HEXES[move.vertex].mapNotNull { state.terrains[it].produces }
val granted = adjacent.groupingBy { it }.eachCount().filter { (res, need) ->
need <= bankSupply(state, res)
}
if (granted.isNotEmpty()) {
s = s.copy(
resources = withCounts(s.resources, seat, granted, 1),
log = s.log + "Seat $seat banks ${describe(granted)} from the new lands.",
)
}
}
val newIndex = state.setupIndex + 1
s = s.copy(setupIndex = newIndex)
return when {
newIndex >= 2 * n -> s.copy(
phase = CatanPhase.AWAIT_ROLL,
turn = 0,
turnNumber = 1,
log = s.log + "Setup done — seat 0 leads.",
)
newIndex == n -> s.copy(phase = CatanPhase.SETUP_SECOND)
else -> s
}
}
private fun applyRoll(state: CatanState, seat: Int, move: RollDice): CatanState {
val dice = move.forced ?: derivedDice(state)
val total = dice[0] + dice[1]
val s = state.copy(lastDice = dice, rngStep = state.rngStep + 1)
return if (total == 7) {
val firstDiscarder = (0 until s.playerCount)
.firstOrNull { s.resourceCount(it) > 7 }
val robbed = if (firstDiscarder != null) {
s.copy(phase = CatanPhase.DISCARDING, discardSeat = firstDiscarder)
} else {
s.copy(phase = CatanPhase.ROBBER)
}
robbed.copy(log = robbed.log + "Seat $seat rolls 7 — the robber rides.")
} else {
applyProduction(s, total)
}
}
/** Dice derived from the seed and the count of random events so far. */
private fun derivedDice(state: CatanState): List<Int> {
val rng = Random(state.seed * 1_000_003L + state.rngStep)
return listOf(rng.nextInt(6) + 1, rng.nextInt(6) + 1)
}
private fun applyProduction(state: CatanState, number: Int): CatanState {
val gains = List(state.playerCount) { mutableMapOf<Resource, Int>() }
for (resource in Resource.entries) {
var demand = 0
for (h in 0 until CatanBoard.HEX_COUNT) {
if (state.numbers[h] != number) continue
if (h == state.robber) continue
if (state.terrains[h].produces != resource) continue
for (v in CatanBoard.HEX_CORNERS[h]) {
val building = state.buildings[v] ?: continue
val amount = if (building.type == BuildingType.CITY) 2 else 1
gains[building.owner][resource] = (gains[building.owner][resource] ?: 0) + amount
demand += amount
}
}
// Official ruling: when the bank cannot meet the demand, nobody
// receives that resource this roll.
if (demand > bankSupply(state, resource)) {
for (perSeat in gains) perSeat.remove(resource)
}
}
var s = state.copy(phase = CatanPhase.PLAYING)
val whoGot = mutableListOf<String>()
for (seat in 0 until s.playerCount) {
val got = gains[seat].filterValues { it > 0 }
if (got.isEmpty()) continue
s = s.copy(resources = withCounts(s.resources, seat, got, 1))
whoGot += "seat $seat takes ${describe(got)}"
}
val said = if (whoGot.isEmpty()) "nothing for anyone" else whoGot.joinToString(", ")
return s.copy(
log = s.log + "Seat ${state.turn} rolls ${state.lastDice.joinToString(" + ")} — $said.",
)
}
private fun applyDiscard(state: CatanState, seat: Int, move: Discard): CatanState {
var s = state.copy(resources = withCards(state.resources, seat, move.cards, -1))
val next = nextDiscarder(s, seat)
s = if (next != null) {
s.copy(discardSeat = next)
} else {
s.copy(phase = CatanPhase.ROBBER, discardSeat = null)
}
return s.copy(log = s.log + "Seat $seat discards ${describe(countOf(move.cards))}.")
}
private fun nextDiscarder(state: CatanState, after: Int): Int? =
((after + 1) until state.playerCount).firstOrNull { state.resourceCount(it) > 7 }
private fun applyRobber(state: CatanState, seat: Int, move: MoveRobber): CatanState {
val hex = CatanBoard.hexIndex[move.hex]
?: throw IllegalArgumentException("No hex at ${move.hex}")
var s = state.copy(robber = hex, rngStep = state.rngStep + 1)
var stolen: String? = null
if (move.victim != null) {
// One card at random from the victim's hand, derived like the
// dice: same seed, next random event.
val rng = Random(state.seed * 1_000_003L + state.rngStep)
val victimHand = state.handOf(move.victim)
val card = victimHand[rng.nextInt(victimHand.size)]
val less = withCards(s.resources, move.victim, listOf(card), -1)
s = s.copy(resources = withCards(less, seat, listOf(card), 1))
stolen = " and steals a ${card.name.lowercase()} from seat ${move.victim}"
}
return s.copy(
phase = CatanPhase.PLAYING,
log = s.log + "Seat $seat moves the robber to the ${terrainName(state.terrains[hex])}" +
" (${move.hex.q},${move.hex.r})$stolen.",
)
}
private fun applyBuildRoad(state: CatanState, seat: Int, move: BuildRoad): CatanState {
val free = state.phase == CatanPhase.FREE_ROADS
var s = state.copy(roads = state.roads.toMutableList().also { it[move.edge] = seat })
if (!free) s = payCost(s, seat, ROAD_COST)
s = refreshLongestRoad(s)
if (free) {
val left = s.pendingFreeRoads - 1
s = s.copy(pendingFreeRoads = left)
if (left == 0) s = s.copy(phase = CatanPhase.PLAYING)
}
return checkWin(s.copy(log = s.log + "Seat $seat builds a road on ${move.edge}."))
}
private fun applyBuildSettlement(state: CatanState, seat: Int, move: BuildSettlement): CatanState {
var s = state.copy(
buildings = state.buildings.toMutableList().also {
it[move.vertex] = CatanBuilding(BuildingType.SETTLEMENT, seat)
},
)
s = payCost(s, seat, SETTLEMENT_COST)
// A settlement can break another player's road, so the award is
// recomputed for everyone.
s = refreshLongestRoad(s)
return checkWin(s.copy(log = s.log + "Seat $seat builds a settlement at ${move.vertex}."))
}
private fun applyBuildCity(state: CatanState, seat: Int, move: BuildCity): CatanState {
var s = state.copy(
buildings = state.buildings.toMutableList().also {
it[move.vertex] = CatanBuilding(BuildingType.CITY, seat)
},
)
s = payCost(s, seat, CITY_COST)
return checkWin(s.copy(log = s.log + "Seat $seat raises a city at ${move.vertex}."))
}
private fun applyBuyDevCard(state: CatanState, seat: Int): CatanState {
val card = state.devDeck.first().copy(boughtTurn = state.turnNumber)
val hands = state.devHands.toMutableList().also { it[seat] = it[seat] + card }
return payCost(state, seat, DEV_COST).copy(
devDeck = state.devDeck.drop(1),
devHands = hands,
devHandCounts = hands.map { it.size },
// What was bought is not announced — only that something was.
log = state.log + "Seat $seat buys a development card.",
)
}
private fun applyPlayKnight(state: CatanState, seat: Int, move: PlayKnight): CatanState {
val hands = removeCard(state, seat, move.card)
val played = state.knightsPlayed.toMutableList().also { it[seat] = it[seat] + 1 }
var s = state.copy(
devHands = hands,
devHandCounts = hands.map { it.size },
knightsPlayed = played,
devCardPlayedThisTurn = true,
phase = CatanPhase.ROBBER,
)
s = refreshLargestArmy(s, seat)
return s.copy(log = s.log + "Seat $seat plays a knight.")
}
private fun applyPlayRoadBuilding(state: CatanState, seat: Int, move: PlayRoadBuilding): CatanState {
val hands = removeCard(state, seat, move.card)
return state.copy(
devHands = hands,
devHandCounts = hands.map { it.size },
devCardPlayedThisTurn = true,
phase = CatanPhase.FREE_ROADS,
pendingFreeRoads = 2,
log = state.log + "Seat $seat plays Road Building.",
)
}
private fun applyPlayMonopoly(state: CatanState, seat: Int, move: PlayMonopoly): CatanState {
val resource = move.resource
var resources = state.resources
var seized = 0
for (other in 0 until state.playerCount) {
if (other == seat) continue
val held = state.resources[other][resource] ?: 0
if (held == 0) continue
resources = withCounts(withCards(resources, other, List(held) { resource }, -1), seat, mapOf(resource to held), 1)
seized += held
}
val hands = removeCard(state, seat, move.card)
return state.copy(
resources = resources,
devHands = hands,
devHandCounts = hands.map { it.size },
devCardPlayedThisTurn = true,
log = state.log + "Seat $seat plays Monopoly — seizes $seized ${resource.name.lowercase()}.",
)
}
private fun applyPlayYearOfPlenty(state: CatanState, seat: Int, move: PlayYearOfPlenty): CatanState {
val hands = removeCard(state, seat, move.card)
return state.copy(
resources = withCards(state.resources, seat, move.take, 1),
devHands = hands,
devHandCounts = hands.map { it.size },
devCardPlayedThisTurn = true,
log = state.log + "Seat $seat plays Year of Plenty — takes ${describe(countOf(move.take))}.",
)
}
private fun applyOfferTrade(state: CatanState, seat: Int, move: OfferTrade): CatanState =
state.copy(
phase = CatanPhase.TRADE_PENDING,
pendingTrade = TradeOffer(by = seat, to = move.to, give = move.give, get = move.get),
log = state.log + "Seat $seat offers ${describe(countOf(move.give))} for " +
"${describe(countOf(move.get))} to seat ${move.to}.",
)
private fun applyAcceptTrade(state: CatanState, seat: Int): CatanState {
val offer = state.pendingTrade!!
var resources = withCards(state.resources, offer.to, offer.get, -1)
resources = withCards(resources, offer.by, offer.give, -1)
resources = withCards(resources, offer.by, offer.get, 1)
resources = withCards(resources, offer.to, offer.give, 1)
return state.copy(
phase = CatanPhase.PLAYING,
pendingTrade = null,
resources = resources,
log = state.log + "Seat $seat accepts — the cards cross the table.",
)
}
private fun applyDeclineTrade(state: CatanState, seat: Int): CatanState =
state.copy(
phase = CatanPhase.PLAYING,
pendingTrade = null,
log = state.log + "Seat $seat declines the offer.",
)
private fun applyMaritimeTrade(state: CatanState, seat: Int, move: MaritimeTrade): CatanState {
val ratio = bestPortRatio(state, seat, move.give)
val paid = withCards(state.resources, seat, List(ratio) { move.give }, -1)
val s = state.copy(resources = withCards(paid, seat, listOf(move.get), 1))
val via = if (ratio == 4) "the bank" else "a $ratio:1 harbour"
return s.copy(
log = s.log + "Seat $seat trades $ratio ${move.give.name.lowercase()} for a " +
"${move.get.name.lowercase()} via $via.",
)
}
private fun applyEndTurn(state: CatanState, seat: Int): CatanState {
// Defensive: a player already at the target wins rather than passes.
val settled = checkWin(state)
if (settled.phase == CatanPhase.GAME_OVER) return settled
val next = (state.turn + 1) % state.playerCount
val s = state.copy(
turn = next,
turnNumber = state.turnNumber + 1,
phase = CatanPhase.AWAIT_ROLL,
devCardPlayedThisTurn = false,
pendingTrade = null,
)
// Someone can cross the target on another player's turn (a broken
// Longest Road re-awarded to a third player); they win when their
// own turn arrives.
return checkWin(s)
}
private fun applyEndFreeRoads(state: CatanState, seat: Int): CatanState =
state.copy(
phase = CatanPhase.PLAYING,
pendingFreeRoads = 0,
log = state.log + "Seat $seat forfeits the remaining free road.",
)
// -----------------------------------------------------------------------
// Scoring
// -----------------------------------------------------------------------
/**
* Victory points everyone at the table can count: buildings, the two
* awards, and nothing hidden. Hidden victory-point cards are added on
* top by [victoryPoints], which is only meaningful for the holder's own
* view or the host's copy.
*/
fun publicVictoryPoints(state: CatanState): List<Int> {
val points = IntArray(state.playerCount)
state.buildings.forEach { building ->
if (building != null) {
points[building.owner] += if (building.type == BuildingType.CITY) 2 else 1
}
}
state.longestRoadOwner?.let { points[it] += 5 }
state.largestArmyOwner?.let { points[it] += 5 }
return points.toList()
}
fun victoryPoints(state: CatanState, seat: Int): Int =
publicVictoryPoints(state)[seat] +
state.devHands[seat].count { it.type == DevCardType.VICTORY_POINT }
private fun checkWin(state: CatanState): CatanState {
if (state.phase == CatanPhase.GAME_OVER) return state
val seat = state.turn
val points = victoryPoints(state, seat)
if (points < state.options.pointsToWin) return state
return state.copy(
phase = CatanPhase.GAME_OVER,
winner = seat,
log = state.log + "Seat $seat reveals $points victory points and wins.",
)
}
/**
* Recomputes everyone's road lengths and re-awards Longest Road.
*
* The award needs a strictly longer road than the holder's; equal length
* leaves it where it is, exactly as the published rule keeps the first
* builder ahead of a builder who merely matches them. If the holder's
* road falls below five segments the award reopens to the longest road
* of five or more, lowest seat first on a tie.
*/
private fun refreshLongestRoad(state: CatanState): CatanState {
val lengths = (0 until state.playerCount).map { longestRoadFor(state, it) }
val holder = state.longestRoadOwner
val best = lengths
.withIndex()
.filter { it.value >= LONGEST_ROAD_MIN }
.maxByOrNull { it.value } // first of the maximum: lowest seat on a tie
val newOwner = when {
holder != null && lengths[holder] >= LONGEST_ROAD_MIN &&
(best == null || best.value <= lengths[holder]) -> holder
else -> best?.index
}
if (newOwner == holder) return state
val line = if (newOwner == null) {
"Longest Road falls vacant."
} else {
"Seat $newOwner takes Longest Road (${lengths[newOwner]} segments)."
}
return state.copy(longestRoadOwner = newOwner, log = state.log + line)
}
/**
* The seat's longest single road: a simple path over its own edges that
* never passes through an opponent's building and never revisits a
* vertex (so a figure of two loops sharing an intersection counts as
* one road, not two — the intersection is a branch).
*/
fun longestRoadFor(state: CatanState, seat: Int): Int {
var best = 0
val blocked = BooleanArray(CatanBoard.VERTEX_COUNT)
for (v in 0 until CatanBoard.VERTEX_COUNT) {
val building = state.buildings[v]
if (building != null && building.owner != seat) blocked[v] = true
}
for (start in 0 until CatanBoard.VERTEX_COUNT) {
if (CatanBoard.VERTEX_EDGES[start].none { state.roads[it] == seat }) continue
val visited = BooleanArray(CatanBoard.VERTEX_COUNT)
best = maxOf(best, roadDfs(state, seat, start, blocked, visited))
}
return best
}
private fun roadDfs(
state: CatanState,
seat: Int,
v: Int,
blocked: BooleanArray,
visited: BooleanArray,
): Int {
visited[v] = true
var best = 0
for (e in CatanBoard.VERTEX_EDGES[v]) {
if (state.roads[e] != seat) continue
val w = CatanBoard.otherEnd(e, v)
if (visited[w]) continue
if (blocked[w]) {
// The segment may run up to an opponent's building, but not
// through it.
best = maxOf(best, 1)
} else {
best = maxOf(best, 1 + roadDfs(state, seat, w, blocked, visited))
}
}
visited[v] = false
return best
}
/**
* Recomputes Largest Army: first to three knights takes it, and it is
* stolen only by a strictly larger army.
*/
private fun refreshLargestArmy(state: CatanState, seat: Int): CatanState {
val holder = state.largestArmyOwner
val newOwner = when {
holder == null && state.knightsPlayed[seat] >= LARGEST_ARMY_MIN -> seat
holder != null && holder != seat &&
state.knightsPlayed[seat] > state.knightsPlayed[holder] -> seat
else -> holder
}
if (newOwner == holder) return state
return state.copy(
largestArmyOwner = newOwner,
log = state.log + "Seat $newOwner takes Largest Army (${state.knightsPlayed[seat]} knights).",
)
}
// -----------------------------------------------------------------------
// Resources
// -----------------------------------------------------------------------
/** The bank's remaining cards of [resource]: what is not in players' hands. */
fun bankSupply(state: CatanState, resource: Resource): Int =
BANK_PER_RESOURCE - state.resources.sumOf { it[resource] ?: 0 }
private fun affordable(state: CatanState, seat: Int, cost: Map<Resource, Int>): Boolean =
cost.all { (resource, need) -> (state.resources[seat][resource] ?: 0) >= need }
private fun payCost(state: CatanState, seat: Int, cost: Map<Resource, Int>): CatanState =
state.copy(resources = withCounts(state.resources, seat, cost, -1))
private fun countOf(cards: List<Resource>): Map<Resource, Int> =
cards.groupingBy { it }.eachCount()
/** Hands with [delta] of each resource added to (or, with negative sign, removed from) [seat]'s. */
private fun withCounts(
resources: List<Map<Resource, Int>>,
seat: Int,
delta: Map<Resource, Int>,
sign: Int,
): List<Map<Resource, Int>> {
val hand = resources[seat].toMutableMap()
for ((resource, n) in delta) hand[resource] = (hand[resource] ?: 0) + sign * n
return resources.toMutableList().also { it[seat] = hand }
}
/** Hands with each card of [cards] added to (or removed from) [seat]'s. */
private fun withCards(
resources: List<Map<Resource, Int>>,
seat: Int,
cards: List<Resource>,
sign: Int,
): List<Map<Resource, Int>> = withCounts(resources, seat, countOf(cards), sign)
/** The card with id [card], removed from [seat]'s hand. */
private fun removeCard(state: CatanState, seat: Int, card: Int): List<List<DevCard>> =
state.devHands.toMutableList().also { hands ->
hands[seat] = hands[seat].filterNot { it.id == card }
}
/**
* The best ratio [seat] can trade [give] at: 2:1 through a matching
* resource harbour, 3:1 through a generic one, otherwise the bank's 4:1.
*/
fun bestPortRatio(state: CatanState, seat: Int, give: Resource): Int {
var best = 4
for (port in state.ports) {
if (port.resource != null && port.resource != give) continue
if (port.ratio >= best) continue
val (a, b) = CatanBoard.EDGE_VERTICES[port.edge]
val mine = state.buildings[a]?.owner == seat || state.buildings[b]?.owner == seat
if (mine) best = port.ratio
}
return best
}
// -----------------------------------------------------------------------
// Results, redaction and wire format
// -----------------------------------------------------------------------
override fun isFinished(state: CatanState): Boolean = state.phase == CatanPhase.GAME_OVER
override fun summary(state: CatanState): String = when (val winner = state.winner) {
null -> publicVictoryPoints(state)
.mapIndexed { seat, points -> "S$seat $points" }
.joinToString(" ")
else -> "Seat $winner wins"
}
override fun viewFor(state: CatanState, seat: Int): CatanState = state.copy(
// Hidden information stays with the holder and the host.
devDeck = emptyList(),
devHands = state.devHands.mapIndexed { index, hand ->
if (index == seat) hand else emptyList()
},
)
override fun encodeState(state: CatanState): String = json.encodeToString(state)
override fun decodeState(json: String): CatanState = this.json.decodeFromString(json)
override fun encodeMove(move: CatanMove): String = json.encodeToString(move)
override fun decodeMove(json: String): CatanMove = this.json.decodeFromString(json)
// -----------------------------------------------------------------------
// Wording
// -----------------------------------------------------------------------
private fun describe(counts: Map<Resource, Int>): String =
counts.entries.joinToString(" + ") { (resource, n) -> "$n ${resource.name.lowercase()}" }
private fun terrainName(terrain: Terrain): String =
terrain.name.lowercase().replace('_', ' ')
}
@@ -64,6 +64,21 @@ interface GameRules<S : Any, M : Any> {
fun legalMoves(state: S, seat: Int): List<M>
/**
* Whether [move] is currently legal for [seat].
*
* Defaults to membership in [legalMoves], which is everything a game
* with a small, enumerable move set needs. A game whose move space is
* combinatorial — Catan's trade offers name any two multisets of cards —
* overrides this and validates structurally instead, because enumerating
* every intent would explode the list the UI and the network driver work
* from. Gates that check a specific move should call this method rather
* than testing list membership directly, so both kinds of game behave the
* same way.
*/
fun isLegalMove(state: S, seat: Int, move: M): Boolean =
move in legalMoves(state, seat)
/**
* Applies [move] on behalf of [seat].
*
@@ -349,7 +349,7 @@ class MatchController<S : Any, M : Any>(
seatPeers[seat]?.let { peers[it]?.send(Rejected("It is not your turn.")) }
return
}
if (move !in rules.legalMoves(current, seat)) {
if (!rules.isLegalMove(current, seat, move)) {
seatPeers[seat]?.let { peers[it]?.send(Rejected("That move is not legal.")) }
return
}
@@ -424,7 +424,7 @@ class MatchController<S : Any, M : Any>(
// throws on a move that is no longer legal, and there is nothing
// above this to catch it.
if (rules.currentSeat(live) != seat) return@withLock false
if (move !in rules.legalMoves(live, seat)) return@withLock false
if (!rules.isLegalMove(live, seat, move)) return@withLock false
authoritative = rules.applyMove(live, seat, move)
publish()
true