Seafarers: rules tests and engine self-play, AI heads for new islands

This commit is contained in:
Claude
2026-10-24 17:15:16 +00:00
parent b5b4afa731
commit 5d36b7bd62
2 changed files with 331 additions and 0 deletions
@@ -130,6 +130,12 @@ class CatanAi : GameAi<CatanState, CatanMove> {
spotValue(state, it.vertex) spotValue(state, it.vertex)
}?.let { return it } }?.let { return it }
// Seafarers: a ship toward an island nobody has landed on is worth more than a card.
legal.filterIsInstance<BuildShip>()
.filter { shipValue(state, seat, it.edge) > 0.5 }
.maxByOrNull { shipValue(state, seat, it.edge) }
?.let { return it }
// A knight is worth playing whenever one is playable: it blocks an // A knight is worth playing whenever one is playable: it blocks an
// opponent's best hex and marches toward Largest Army. // opponent's best hex and marches toward Largest Army.
legal.filterIsInstance<PlayKnight>().firstOrNull()?.let { return it } legal.filterIsInstance<PlayKnight>().firstOrNull()?.let { return it }
@@ -0,0 +1,325 @@
package org.prolibertate.games.game.catan
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.prolibertate.games.game.GameCatalog
import org.prolibertate.games.game.engine.PlayerKind
import org.prolibertate.games.game.engine.PlayerSlot
import org.prolibertate.games.game.engine.TableConfig
class CatanSeafarersTest {
private val json = Json { encodeDefaults = true }
private fun options(players: Int = 3) =
CatanOptions(playerCount = players, pointsToWin = 12, ruleSet = CatanRuleSet.SEAFARERS)
private fun config(options: CatanOptions, seed: Long) = TableConfig(
gameId = GameCatalog.CATAN,
seats = (0 until options.playerCount).map {
PlayerSlot(seat = it, name = "P$it", kind = PlayerKind.AI, team = it)
},
optionsJson = json.encodeToString(options),
seed = seed,
)
private fun start(players: Int = 3, seed: Long = 7L): CatanState =
CatanRules.initialState(config(options(players), seed))
/** A mid-game table on seat 0's turn with plenty of cards. */
private fun playing(seed: Long = 7L, adjust: CatanState.() -> CatanState = { this }): CatanState =
start(seed = seed).copy(
phase = CatanPhase.PLAYING,
turn = 0,
turnNumber = 1,
resources = List(3) { Resource.entries.associateWith { 5 } },
).adjust()
private fun CatanState.settle(vertex: Int, seat: Int, type: BuildingType = BuildingType.SETTLEMENT) =
copy(buildings = buildings.toMutableList().also { it[vertex] = CatanBuilding(type, seat) })
private fun CatanState.withShip(edge: Int, seat: Int) =
copy(sea = sea!!.let { it.copy(ships = it.ships.toMutableList().also { l -> l[edge] = seat }) })
private fun CatanState.withRoad(edge: Int, seat: Int) =
copy(roads = roads.toMutableList().also { it[edge] = seat })
/** A home-island vertex that touches open water, with a sea edge leaving it. */
private fun CatanState.coastVertex(): Int {
val topo = topo
return (0 until topo.VERTEX_COUNT).first { v ->
topo.vertexIsland[v] == sea!!.home &&
topo.VERTEX_EDGES[v].any { topo.edgeSea[it] && !topo.edgeLand[it] }
}
}
// --- The map -------------------------------------------------------------
@Test
fun `the new shores map is a big home island and three small ones`() {
val topo = SeaBoards.topology(SeaScenario.NEW_SHORES)
assertEquals(4, topo.islandCount)
val sizes = (0 until topo.islandCount).map { i -> topo.islandOf.count { it == i } }.sorted()
assertEquals(listOf(2, 3, 3, 21), sizes)
// Every coast is closed: nothing on land touches the edge of the frame.
for (e in 0 until topo.EDGE_COUNT) {
if (topo.EDGE_HEXES[e].size == 1) assertFalse("land on the frame edge at $e", topo.land[topo.EDGE_HEXES[e][0]])
}
}
@Test
fun `a new game has gold, a desert, numbers on every other land hex, a pirate at sea and nine harbours`() {
repeat(5) { i ->
val s = start(seed = 100L + i)
val topo = s.topo
assertEquals(2, s.terrains.count { it == Terrain.GOLD })
assertEquals(1, s.terrains.count { it == Terrain.DESERT })
for (h in 0 until topo.HEX_COUNT) {
val land = s.terrains[h] != Terrain.SEA
assertEquals("hex $h", topo.land[h], land)
assertEquals("hex $h", land && s.terrains[h] != Terrain.DESERT, s.numbers[h] != 0)
}
assertEquals(Terrain.SEA, s.terrains[s.sea!!.pirate])
assertTrue(s.terrains[s.robber] == Terrain.DESERT)
assertEquals(9, s.ports.size)
// The red numbers are never neighbours.
val reds = (0 until topo.HEX_COUNT).filter { s.numbers[it] == 6 || s.numbers[it] == 8 }
for (a in reds) for (b in reds) if (a < b) assertFalse(topo.hexesAdjacent(a, b))
}
}
@Test
fun `setup places both settlements on the home island, with roads rather than ships`() {
val s = start()
val moves = CatanRules.legalMoves(s, 0).filterIsInstance<SetupPlace>()
assertTrue(moves.isNotEmpty())
assertTrue(moves.all { s.topo.vertexIsland[it.vertex] == s.sea!!.home })
assertTrue(moves.all { s.topo.edgeLand[it.edge] })
}
@Test
fun `the state survives its wire format`() {
val s = playing().let { it.settle(it.coastVertex(), 0) }
assertEquals(s, CatanRules.decodeState(CatanRules.encodeState(s)))
}
// --- Ships ---------------------------------------------------------------
@Test
fun `a ship launches from a harbour town onto a sea edge and costs a lumber and a wool`() {
val s = playing().let { it.settle(it.coastVertex(), 0) }
val ships = CatanRules.legalMoves(s, 0).filterIsInstance<BuildShip>()
assertTrue(ships.isNotEmpty())
assertTrue(ships.all { s.topo.edgeSea[it.edge] })
val after = CatanRules.applyMove(s, 0, ships.first())
assertEquals(0, after.sea!!.ships.indexOfFirst { it == 0 }.let { if (it == ships.first().edge) 0 else 1 })
assertEquals(4, after.resources[0].getValue(Resource.LUMBER))
assertEquals(4, after.resources[0].getValue(Resource.WOOL))
assertEquals(5, after.resources[0].getValue(Resource.BRICK))
}
@Test
fun `no ship without the cards, and none sails out of nothing`() {
val bare = playing().let { it.settle(it.coastVertex(), 0) }
.let { it.copy(resources = it.resources.toMutableList().also { r -> r[0] = Resource.entries.associateWith { 0 } }) }
assertTrue(CatanRules.legalMoves(bare, 0).none { it is BuildShip })
// Nobody has a town or a fleet: there is nowhere to start from.
val nothing = playing()
assertTrue(CatanRules.legalMoves(nothing, 0).none { it is BuildShip })
}
@Test
fun `the pirate keeps ships off the edges round its hex`() {
val s = playing().let { it.settle(it.coastVertex(), 0) }
val ship = CatanRules.legalMoves(s, 0).filterIsInstance<BuildShip>().first()
val seaHex = s.topo.EDGE_HEXES[ship.edge].first { !s.topo.land[it] }
val blocked = s.copy(sea = s.sea!!.copy(pirate = seaHex))
assertTrue(CatanRules.legalMoves(blocked, 0).filterIsInstance<BuildShip>().none { seaHex in s.topo.EDGE_HEXES[it.edge] })
}
@Test
fun `a ship cannot sail the turn it is built, but can the next, from the open end only`() {
val s0 = playing().let { it.settle(it.coastVertex(), 0) }
val first = CatanRules.legalMoves(s0, 0).filterIsInstance<BuildShip>().first()
val s1 = CatanRules.applyMove(s0, 0, first)
assertTrue(CatanRules.legalMoves(s1, 0).none { it is MoveShip })
// Next turn (after the others pass), the lone ship is at an open end and can sail.
val s2 = s1.copy(sea = s1.sea!!.copy(builtThisTurn = emptyList(), shipMoved = false))
val sails = CatanRules.legalMoves(s2, 0).filterIsInstance<MoveShip>()
assertTrue(sails.isNotEmpty())
assertTrue(sails.all { it.from == first.edge && it.to != first.edge })
// Sailing uses the turn's one move.
val s3 = CatanRules.applyMove(s2, 0, sails.first())
assertTrue(s3.sea!!.shipMoved)
assertEquals(NO_PLAYER, s3.sea!!.ships[first.edge])
assertEquals(0, s3.sea!!.ships[sails.first().to])
assertTrue(CatanRules.legalMoves(s3, 0).none { it is MoveShip })
}
@Test
fun `a ship in the middle of a route is stuck`() {
// Town - ship A - ship B: A has the town at one end and B at the other, so only B is at an open end.
val s0 = playing().let { it.settle(it.coastVertex(), 0) }
val a = CatanRules.legalMoves(s0, 0).filterIsInstance<BuildShip>().first().edge
var s = s0.withShip(a, 0)
val far = s.topo.EDGE_VERTICES[a].toList().first { s.buildings[it] == null }
val b = s.topo.VERTEX_EDGES[far].first { it != a && s.topo.edgeSea[it] && s.roads[it] == NO_PLAYER }
s = s.withShip(b, 0)
val movers = CatanRules.legalMoves(s, 0).filterIsInstance<MoveShip>().map { it.from }.toSet()
assertEquals(setOf(b), movers)
}
@Test
fun `a settlement can rise at the end of a ship route, and the first on a new island scores the bonus`() {
val base = playing()
val topo = base.topo
val sea = base.sea!!
// A vertex on a small island, and a ship chain reaching it is too long to build by hand,
// so give the player the ship on the edge beside that vertex.
val vertex = (0 until topo.VERTEX_COUNT).first { v ->
val island = topo.vertexIsland[v]
island != -1 && island != sea.home &&
topo.VERTEX_EDGES[v].any { topo.edgeSea[it] }
}
val edge = topo.VERTEX_EDGES[vertex].first { topo.edgeSea[it] }
var s = base.withShip(edge, 0)
assertTrue(CatanRules.legalMoves(s, 0).any { it == BuildSettlement(vertex) })
val before = CatanRules.publicVictoryPoints(s)[0]
s = CatanRules.applyMove(s, 0, BuildSettlement(vertex))
assertEquals(before + 1 + SeaRules.ISLAND_BONUS, CatanRules.publicVictoryPoints(s)[0])
assertEquals(0, s.sea!!.islandBonus[topo.vertexIsland[vertex]])
// A second settlement on that island scores no second bonus.
val again = SeaRules.claimIsland(s, 1, vertex)
assertEquals(0, again.sea!!.islandBonus[topo.vertexIsland[vertex]])
}
@Test
fun `a road and a ship join a route only at a town of your own`() {
val base = playing()
val topo = base.topo
val v = base.coastVertex()
val road = topo.VERTEX_EDGES[v].first { topo.edgeLand[it] }
val ship = topo.VERTEX_EDGES[v].first { topo.edgeSea[it] && !topo.edgeLand[it] }
// With a town at the junction, road + ship is one route of two.
val withTown = base.settle(v, 0).withRoad(road, 0).withShip(ship, 0)
assertEquals(2, SeaRules.longestRouteFor(withTown, 0))
// Without it, they are two separate pieces.
val noTown = base.withRoad(road, 0).withShip(ship, 0)
assertEquals(1, SeaRules.longestRouteFor(noTown, 0))
}
// --- Pirate --------------------------------------------------------------
@Test
fun `on a seven the roller may move the robber to land or the pirate to sea, and the pirate robs a ship's owner`() {
val s0 = playing().let { it.settle(it.coastVertex(), 1) }
val ship = SeaRules.buildShipMoves(s0, 1).first().edge
val s = s0.withShip(ship, 1).copy(phase = CatanPhase.ROBBER)
val moves = CatanRules.legalMoves(s, 0)
assertTrue(moves.any { it is MoveRobber })
assertTrue(moves.any { it is MovePirate })
// Robber moves are on land only.
assertTrue(moves.filterIsInstance<MoveRobber>().all { s.topo.land[s.topo.hexIndex.getValue(it.hex)] })
assertTrue(moves.filterIsInstance<MovePirate>().all { !s.topo.land[s.topo.hexIndex.getValue(it.hex)] })
val robbery = moves.filterIsInstance<MovePirate>().first { it.victim == 1 }
val after = CatanRules.applyMove(s, 0, robbery)
assertEquals(CatanPhase.PLAYING, after.phase)
assertEquals(s.topo.hexIndex.getValue(robbery.hex), after.sea!!.pirate)
assertEquals(s.resourceCount(0) + 1, after.resourceCount(0))
assertEquals(s.resourceCount(1) - 1, after.resourceCount(1))
}
// --- Gold ----------------------------------------------------------------
@Test
fun `gold pays a resource of the owner's choice`() {
val base = playing()
val topo = base.topo
val goldHex = base.terrains.indexOf(Terrain.GOLD)
val number = base.numbers[goldHex]
val v = topo.HEX_CORNERS[goldHex].first { topo.vertexLand[it] }
// Seat 0's town beside the gold field; nothing else of theirs produces on that number.
val s = base.settle(v, 0).copy(
robber = (0 until topo.HEX_COUNT).first { topo.land[it] && it != goldHex && v !in topo.HEX_CORNERS[it] },
resources = List(3) { Resource.entries.associateWith { 0 } },
phase = CatanPhase.AWAIT_ROLL,
)
val dice = if (number <= 7) listOf(number - 1, 1) else listOf(6, number - 6)
val rolled = CatanRules.applyMove(s, 0, RollDice(forced = dice))
assertEquals(CatanPhase.GOLD, rolled.phase)
assertEquals(0, CatanRules.currentSeat(rolled))
val picks = CatanRules.legalMoves(rolled, 0)
assertEquals(Resource.entries.size, picks.size)
val after = CatanRules.applyMove(rolled, 0, PickGold(listOf(Resource.ORE)))
assertEquals(CatanPhase.PLAYING, after.phase)
assertEquals(1, after.resources[0].getValue(Resource.ORE))
}
// --- Whole games ---------------------------------------------------------
private data class Report(val seed: Long, val moves: Int, val ships: Int, val islandsTaken: Int, val points: List<Int>)
private fun playOut(options: CatanOptions, seed: Long, cap: Int = 20_000): Pair<CatanState, Report> {
val ai = CatanAi()
var state = CatanRules.initialState(config(options, seed))
var moves = 0
while (!CatanRules.isFinished(state)) {
assertTrue("seed $seed ran past $cap moves; log tail: ${state.log.takeLast(8)}", moves++ < cap)
val seat = CatanRules.currentSeat(state)
?: error("seed $seed: nobody on the clock in ${state.phase}; log tail: ${state.log.takeLast(8)}")
val legal = CatanRules.legalMoves(state, seat)
assertTrue("seed $seed: seat $seat has no legal move in ${state.phase}", legal.isNotEmpty())
val move = ai.chooseMove(state, seat, legal)
assertTrue(
"seed $seed: seat $seat chose the illegal move $move in ${state.phase}; log tail: ${state.log.takeLast(5)}",
CatanRules.isLegalMove(state, seat, move),
)
val next = CatanRules.applyMove(state, seat, move)
// The wire format must carry everything, every step.
if (moves % 25 == 0) assertEquals(next, CatanRules.decodeState(CatanRules.encodeState(next)))
state = next
}
val sea = state.sea!!
return state to Report(
seed, moves,
ships = sea.ships.count { it != NO_PLAYER },
islandsTaken = sea.islandBonus.count { it != NO_PLAYER },
points = CatanRules.publicVictoryPoints(state),
)
}
@Test
fun `engines finish Seafarers games at three and four players`() {
val reports = mutableListOf<Report>()
for ((players, seeds) in listOf(3 to listOf(1L, 2L, 3L, 4L), 4 to listOf(5L, 6L, 7L))) {
for (seed in seeds) {
val (state, report) = playOut(options(players), seed)
assertEquals("seed $seed", CatanPhase.GAME_OVER, state.phase)
val winner = state.winner
assertTrue("seed $seed finished without a winner", winner != null)
assertTrue(
"seed $seed: the winner fell short of the target",
CatanRules.victoryPoints(state, winner!!) >= state.options.pointsToWin,
)
reports += report
}
}
println("Seafarers self-play: " + reports.joinToString("; ") {
"seed ${it.seed}: ${it.moves} moves, ${it.ships} ships, ${it.islandsTaken} islands, points ${it.points}"
})
// The engines must actually go to sea in at least some of the games.
assertNotEquals("no engine ever built a ship", 0, reports.sumOf { it.ships })
}
}