Add Ta Yü

Rivers laid out from the centre of an 18x18 board on 1x3 tiles, each with
three mouths that must line up with whatever they touch. One side runs water
north and south, the other east and west, and a side's score is one edge
multiplied by the other — so reaching only one of your two edges is worth
nothing, which is the whole tension of the game.

Two things fell out of the geometry rather than needing to be tabulated. The
tile set is generated: three mouths chosen from the eight places one can sit
on a 1x3 tile gives 56 arrangements, turning a tile end for end pairs them
off with none fixed, so there are exactly 28 distinct tiles and the box's 84
is three of each. And because every tile joins the network by a mouth while
all three of its own mouths interconnect, the board is always one connected
river system — so scoring never traces connectivity, and a mouth at the edge
is an exit by construction. Both properties are asserted over whole games.

The placement check is one comparison doing two jobs: where a new tile abuts
an old one, both sides must agree. That refuses a river dead-ending against
stone and, read the other way, refuses a blank flank that would wall off a
river already down.

18x18 comes out under 20dp a cell on a phone, too fine to tap, so laying a
tile is a tap to line it up and a button to commit. Tapping the same cell
again cycles the other legal ways the tile could cover it, which is also how
it gets turned — a rotate control would have landed on illegal positions. A
tap on a cell the tile cannot cover is ignored rather than treated as a
deselection, so a fingertip one cell wide of the mark does not throw away a
placement.

Two AI settings, not three. A blocking-heavy variant was written and dropped
because it played the full setting dead even over 30 games; shipping it as a
step up would have been a claim that could not be backed. What ships is held
to measured numbers: full strength won 20 of 20 against random placement from
either axis, gentle beats random about three games in four and loses to full
strength about four in five, and random against random comes out even, which
is what makes the rest of those numbers mean anything.

The reconstruction's uncertainties stay called out in the rules doc rather
than being smoothed over now that the code exists: the 18x18 board reading,
the marked exits placed at 3, 8 and 13 by choice, and the three-player flood
variant left out because nothing found says how the flood scores.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015pyhC1KyFkQk6hUnnX2Tof
This commit is contained in:
Claude
2026-08-06 18:09:10 +00:00
parent 9f71e0844b
commit cdd515afc6
12 changed files with 2386 additions and 118 deletions
@@ -161,7 +161,7 @@ object GameCatalog {
teamBased = true,
blurb = "Lay river tiles out from the centre. Reach both your edges, " +
"because your score multiplies them.",
available = false,
available = true,
),
)
@@ -0,0 +1,86 @@
package org.prolibertate.games.game.tayu
import org.prolibertate.games.game.engine.GameAi
/**
* A heuristic Ta Yü opponent.
*
* It rates every legal placement on the board that placement would produce,
* weighing three things: what its own axis would score, what the opponent's
* would score, and which way the still-open river mouths are pointing.
*
* That last term is what makes it play sensibly at all. For most of a game both
* scores are flatly zero — a product needs *both* edges — so an opponent that
* looked only at the score would have nothing to choose between its first fifty
* placements. Counting open mouths, and how close each one already is to the
* edge it points at, gives it a reason to drive water towards its own sides and
* to turn the opponent's rivers away from theirs.
*
* [level] overrides the table's own setting, which is what the tests use;
* ordinarily it is left null and read from [TayuOptions.level].
*/
class TayuAi(private val level: TayuLevel? = null) : GameAi<TayuState, TayuMove> {
override fun chooseMove(state: TayuState, seat: Int, legal: List<TayuMove>): TayuMove {
require(legal.isNotEmpty()) { "No legal move for seat $seat" }
val setting = level ?: state.options.level
if (legal.size == 1) return legal.first()
return legal.maxByOrNull { rate(state, seat, it, setting) } ?: legal.first()
}
private fun rate(state: TayuState, seat: Int, move: TayuMove, setting: TayuLevel): Int {
val after = TayuRules.previewPlacement(state, seat, move)
val mine = state.axisOf(seat)
val theirs = if (mine == Axis.NORTH_SOUTH) Axis.EAST_WEST else Axis.NORTH_SOUTH
// Both edges get a +1 so that the first exit onto an empty edge is worth
// something. Without it every placement rates zero until an axis has
// broken through on both sides, and by then the game is decided.
val exits = TayuRules.exitsOf(after)
val ours = (exits.on(mine.first) + 1) * (exits.on(mine.second) + 1)
val opposing = (exits.on(theirs.first) + 1) * (exits.on(theirs.second) + 1)
// Skipped rather than multiplied by zero: the gentle setting is the whole
// reason to avoid walking the open mouths at all, and this runs for every
// one of a thousand-odd candidate placements.
val reach = if (setting.reachWeight == 0) {
0
} else {
(pull(after, mine) - pull(after, theirs)) / REACH_SCALE
}
return setting.ownWeight * ours -
setting.blockWeight * opposing +
setting.reachWeight * reach
}
/**
* How much of the open river is aimed at [axis]: every mouth with empty
* ground in front of it, counted more heavily the closer it already is to
* the edge it points at.
*/
private fun pull(state: TayuState, axis: Axis): Int =
TayuRules.openMouths(state).sumOf { (cell, direction) ->
if (direction != axis.first && direction != axis.second) {
0
} else {
BOARD_SIZE - distanceToEdge(cell, direction)
}
}
private fun distanceToEdge(cell: Int, direction: Facing): Int {
val row = TayuBoard.rowOf(cell)
val col = TayuBoard.colOf(cell)
return when (direction) {
Facing.NORTH -> row
Facing.SOUTH -> BOARD_SIZE - 1 - row
Facing.WEST -> col
Facing.EAST -> BOARD_SIZE - 1 - col
}
}
private companion object {
/** Brings the open-mouth term onto the same scale as the score term. */
const val REACH_SCALE = 8
}
}
@@ -0,0 +1,339 @@
package org.prolibertate.games.game.tayu
import kotlinx.serialization.Serializable
/**
* The board is 18 × 18. See RULES-tayu.md: sources disagree between this and
* 19 × 19, and 18 is the reading under which the opening tile going into "one
* of the four centre indentations" is true. If a rulebook ever settles it the
* other way this constant is the only thing that has to change.
*/
const val BOARD_SIZE = 18
const val BOARD_CELLS = BOARD_SIZE * BOARD_SIZE
/** Every tile is three cells long. */
const val TILE_LENGTH = 3
/** Sentinel in [TayuState.tileAt] for a cell with nothing on it. */
const val NO_TILE = -1
/**
* A compass direction, in clockwise order so that turning is arithmetic.
*
* Rows count from the north edge and columns from the west, so south is a
* larger row — the same convention as the screen.
*/
@Serializable
enum class Facing(val dr: Int, val dc: Int) {
NORTH(-1, 0),
EAST(0, 1),
SOUTH(1, 0),
WEST(0, -1);
val opposite: Facing get() = Facing.entries[(ordinal + 2) % 4]
val left: Facing get() = Facing.entries[(ordinal + 3) % 4]
val right: Facing get() = Facing.entries[(ordinal + 1) % 4]
}
/**
* Which flank of a tile a river mouth sits on, described relative to the tile's
* own length rather than to the board.
*
* A tile is laid pointing somewhere — [Facing] — and its three cells run that
* way from the anchor. [FRONT] is the far short end, [BACK] the near one, and
* [LEFT] and [RIGHT] are the two long flanks. Keeping mouths in these terms is
* what lets one stored tile be laid in any of four orientations without a
* lookup table per orientation.
*/
enum class Flank { LEFT, RIGHT, BACK, FRONT }
/** Where a mouth on [flank] points once the tile is laid pointing [tileFacing]. */
fun absoluteFacing(tileFacing: Facing, flank: Flank): Facing = when (flank) {
Flank.FRONT -> tileFacing
Flank.BACK -> tileFacing.opposite
Flank.LEFT -> tileFacing.left
Flank.RIGHT -> tileFacing.right
}
/**
* The eight places a river mouth can sit on a 1 × 3 tile: one above and one
* below each of the three cells, plus one at each short end.
*
* They are numbered so that a whole tile is a bitmask small enough to send as
* one integer.
*/
object TileSlots {
const val COUNT = 8
/** Which of the tile's three cells each slot sits on. */
private val CELL = intArrayOf(0, 1, 2, 0, 1, 2, 0, 2)
private val FLANK = arrayOf(
Flank.LEFT, Flank.LEFT, Flank.LEFT,
Flank.RIGHT, Flank.RIGHT, Flank.RIGHT,
Flank.BACK, Flank.FRONT,
)
/**
* Slot reached by turning the tile end for end. No slot maps to itself,
* which is exactly why the 56 possible mouth arrangements pair off cleanly
* into 28 distinct tiles rather than leaving some stranded.
*/
private val TURNED = intArrayOf(5, 4, 3, 2, 1, 0, 7, 6)
fun cellOf(slot: Int): Int = CELL[slot]
fun flankOf(slot: Int): Flank = FLANK[slot]
fun turned(slot: Int): Int = TURNED[slot]
}
/**
* The bag of tiles, generated rather than listed.
*
* A tile is a bitmask over [TileSlots]: exactly three of the eight slots carry
* a river mouth, and all three are joined to one another across the face of the
* tile, so water entering any mouth can leave by either of the others.
*
* Choosing three slots from eight gives 56 arrangements, and turning a tile end
* for end pairs them off with none left over, so there are exactly **28
* distinct tiles**. The reissued game holds three of each — 84 — and the 1999
* original held four, 112. Both counts being whole multiples of 28 is the
* evidence this geometry is the right one.
*/
object TayuTiles {
const val MOUTHS_PER_TILE = 3
/**
* Every tile that can exist, one entry each.
*
* Taking the smaller mask of each turned-over pair is enough to pick one
* representative apiece, because no arrangement of three mouths survives
* being turned end for end unchanged.
*/
val all: List<Int> = (0 until (1 shl TileSlots.COUNT))
.filter { it.countOneBits() == MOUTHS_PER_TILE }
.filter { it < turned(it) }
/** The same mask with the tile turned end for end. */
fun turned(mask: Int): Int {
var result = 0
for (slot in 0 until TileSlots.COUNT) {
if (hasMouth(mask, slot)) result = result or (1 shl TileSlots.turned(slot))
}
return result
}
fun hasMouth(mask: Int, slot: Int): Boolean = (mask shr slot) and 1 == 1
fun mouthSlots(mask: Int): List<Int> =
(0 until TileSlots.COUNT).filter { hasMouth(mask, it) }
/**
* True when the tile's three mouths sit on three different flanks of the
* rectangle. Twelve of the 28 do, which is what the concentric ring on the
* centre stud marks on the reissued tiles — so the same ring is drawn here.
*/
fun touchesThreeFlanks(mask: Int): Boolean =
mouthSlots(mask).map { TileSlots.flankOf(it) }.distinct().size == 3
/** The bag for a table: [copies] of every tile, shuffled by the caller. */
fun bag(copies: Int): List<Int> = List(copies) { all }.flatten()
}
object TayuBoard {
fun cellAt(row: Int, col: Int): Int = row * BOARD_SIZE + col
fun rowOf(cell: Int): Int = cell / BOARD_SIZE
fun colOf(cell: Int): Int = cell % BOARD_SIZE
fun onBoard(row: Int, col: Int): Boolean =
row in 0 until BOARD_SIZE && col in 0 until BOARD_SIZE
/** The four middle cells. The opening tile has to cover one of them. */
val centre: Set<Int> = setOf(
cellAt(BOARD_SIZE / 2 - 1, BOARD_SIZE / 2 - 1),
cellAt(BOARD_SIZE / 2 - 1, BOARD_SIZE / 2),
cellAt(BOARD_SIZE / 2, BOARD_SIZE / 2 - 1),
cellAt(BOARD_SIZE / 2, BOARD_SIZE / 2),
)
/**
* Exits along an edge that count double.
*
* Positions on the real board are not known — see RULES-tayu.md. These
* three give the board four-fold rotational symmetry, so no side is better
* served than another, which is the fairest guess available.
*/
val markedExits: Set<Int> = setOf(3, 8, 13)
/**
* Where along [edge] a river leaving cell ([row], [col]) runs off the
* board, counted clockwise from that edge's first cell.
*/
fun exitPosition(edge: Facing, row: Int, col: Int): Int = when (edge) {
Facing.NORTH -> col
Facing.EAST -> row
Facing.SOUTH -> BOARD_SIZE - 1 - col
Facing.WEST -> BOARD_SIZE - 1 - row
}
/** An ordinary exit is worth one; a marked one is worth two. */
fun exitValue(edge: Facing, row: Int, col: Int): Int =
if (exitPosition(edge, row, col) in markedExits) 2 else 1
/** The cell whose exit sits at [position] along [edge]: inverse of [exitPosition]. */
fun edgeCell(edge: Facing, position: Int): Int = when (edge) {
Facing.NORTH -> cellAt(0, position)
Facing.EAST -> cellAt(position, BOARD_SIZE - 1)
Facing.SOUTH -> cellAt(BOARD_SIZE - 1, BOARD_SIZE - 1 - position)
Facing.WEST -> cellAt(BOARD_SIZE - 1 - position, 0)
}
}
/** The three cells a tile laid by [move] would cover, from its anchor outwards. */
fun cellsOf(move: TayuMove): List<Int> = (0 until TILE_LENGTH).map {
TayuBoard.cellAt(move.row + it * move.facing.dr, move.col + it * move.facing.dc)
}
/** The two edges a side is trying to reach. */
enum class Axis(val label: String, val first: Facing, val second: Facing) {
NORTH_SOUTH("north and south", Facing.NORTH, Facing.SOUTH),
EAST_WEST("east and west", Facing.EAST, Facing.WEST),
}
/** Team 0 runs its rivers north and south, team 1 east and west. */
fun axisOfTeam(team: Int): Axis = if (team % 2 == 0) Axis.NORTH_SOUTH else Axis.EAST_WEST
/**
* How hard the computer plays.
*
* Only two settings, because only two could be shown to differ. [GENTLE] rates
* a placement purely on what it scores at that moment, which for most of a game
* is nothing at all, so it lays a reasonable-looking but aimless river: it beats
* random placement about three games in four, and loses to [FULL] about four in
* five. [FULL] adds blocking and, more to the point, notices which way the open
* river mouths are pointing. Both figures are held to by TayuAiTest.
*
* A third setting that blocked harder was tried and dropped: it played the full
* setting dead even, so shipping it as a step up would have been a claim that
* could not be backed.
*/
@Serializable
enum class TayuLevel(
val label: String,
val ownWeight: Int,
val blockWeight: Int,
val reachWeight: Int,
) {
/** Takes a score when it sees one and otherwise digs more or less anywhere. */
GENTLE("Gentle", ownWeight = 20, blockWeight = 0, reachWeight = 0),
/** Builds towards its own edges and spoils yours. */
FULL("Full strength", ownWeight = 20, blockWeight = 12, reachWeight = 2),
}
@Serializable
data class TayuOptions(
/** Two play head to head; four play as two partnerships across the axes. */
val playerCount: Int = 2,
val level: TayuLevel = TayuLevel.FULL,
/**
* Copies of each of the 28 tiles. Three is the reissued game's 84 tiles and
* four is the 1999 original's 112 — the publisher itself cut it to three to
* shorten the game, so two is offered on the same reasoning.
*/
val tileCopies: Int = 3,
) {
init {
require(playerCount == 2 || playerCount == 4) { "Ta Yü seats two or four" }
require(tileCopies in 2..4) { "tileCopies must be 2, 3 or 4" }
}
val tileCount: Int get() = tileCopies * TayuTiles.all.size
}
/** A tile on the board: its mouths, where its first cell sits, and which way it points. */
@Serializable
data class PlacedTile(
val mask: Int,
/** The tile's first cell; the other two run [facing] from here. */
val row: Int,
val col: Int,
val facing: Facing,
val seat: Int,
) {
/** The three cells this tile covers, from the anchor outwards. */
fun cells(): List<Int> = (0 until TILE_LENGTH).map {
TayuBoard.cellAt(row + it * facing.dr, col + it * facing.dc)
}
}
@Serializable
enum class TayuPhase { PLAYING, GAME_OVER }
@Serializable
data class TayuState(
val options: TayuOptions,
val seed: Long,
/** Team index per seat. */
val teams: List<Int>,
/** Index into [placed] for the tile covering each cell, or [NO_TILE]. */
val tileAt: List<Int>,
val placed: List<PlacedTile>,
/**
* Tiles still in the bag, in the order they will come out. The one piece of
* hidden information in the game, and the only thing [TayuRules.viewFor]
* has to strip.
*/
val bag: List<Int>,
/**
* The tile the seat on the clock has drawn and must place. Everyone can see
* it — on the table it is drawn out of the bag face up.
*/
val drawn: Int?,
val bagCount: Int,
/** Drawn tiles that had nowhere legal to go. They do not come back. */
val setAside: List<Int>,
val turn: Int,
val phase: TayuPhase,
val log: List<String>,
) {
val playerCount: Int get() = teams.size
fun teamOf(seat: Int): Int = teams[seat]
fun axisOf(seat: Int): Axis = axisOfTeam(teamOf(seat))
}
/**
* Laying a tile down: where its first cell goes and which way it points.
*
* The only move there is in Ta Yü, so there is no sealed hierarchy. Which tile
* is being laid is deliberately absent — it can only ever be [TayuState.drawn],
* and a move carrying its own copy could disagree with the state it is applied
* to.
*/
@Serializable
data class TayuMove(val row: Int, val col: Int, val facing: Facing)
/** Exits reached on each edge, already counting marked ones double. */
data class EdgeExits(val north: Int, val east: Int, val south: Int, val west: Int) {
fun on(edge: Facing): Int = when (edge) {
Facing.NORTH -> north
Facing.EAST -> east
Facing.SOUTH -> south
Facing.WEST -> west
}
/**
* What an axis has actually scored: its two edges multiplied together, so
* reaching only one of them is worth nothing at all.
*/
fun product(axis: Axis): Int = on(axis.first) * on(axis.second)
}
@@ -0,0 +1,375 @@
package org.prolibertate.games.game.tayu
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.prolibertate.games.game.GameCatalog
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
/**
* Ta Yü as a pure state machine. See RULES-tayu.md for the ruleset, and for
* which parts of it had to be reconstructed from an out-of-print rulebook.
*
* The one thing worth knowing before reading on: because every tile after the
* first has to join a river already down, and because all three mouths of a
* tile are connected across its face, everything on the board is always a
* single river system running back to the opening tile. Nothing here ever has
* to trace connectivity — a mouth at the board's edge is a scoring exit by
* construction.
*/
object TayuRules : GameRules<TayuState, TayuMove> {
override val gameId: String = GameCatalog.TAYU
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}
override fun initialState(config: TableConfig): TayuState {
val options = json.decodeFromString<TayuOptions>(config.optionsJson)
require(config.seats.size == options.playerCount) {
"Seat count ${config.seats.size} does not match ${options.playerCount} players"
}
val bag = TayuTiles.bag(options.tileCopies).shuffledWith(Random(config.seed))
val teams = (0 until options.playerCount).map { it % 2 }
val empty = TayuState(
options = options,
seed = config.seed,
teams = teams,
tileAt = List(BOARD_CELLS) { NO_TILE },
placed = emptyList(),
bag = bag,
drawn = null,
bagCount = bag.size,
setAside = emptyList(),
turn = 0,
phase = TayuPhase.PLAYING,
log = listOf(
"Ta Yü — ${options.tileCount} tiles. " +
"Seat 0 runs north and south, seat 1 east and west."
),
)
return openTurn(empty, seat = 0)
}
override fun currentSeat(state: TayuState): Int? =
if (state.phase == TayuPhase.PLAYING && state.drawn != null) state.turn else null
// -----------------------------------------------------------------------
// Legal moves
// -----------------------------------------------------------------------
override fun legalMoves(state: TayuState, seat: Int): List<TayuMove> {
if (currentSeat(state) != seat) return emptyList()
return placementsFor(state, state.drawn ?: return emptyList())
}
/**
* Every way [tile] can be laid on the board as it stands.
*
* Four orientations at every cell. The anchor is the tile's first cell, so
* laying the same three cells the other way round is a different facing
* from a different anchor rather than a special case.
*/
fun placementsFor(state: TayuState, tile: Int): List<TayuMove> {
val mouths = mouthMap(state)
val opening = state.placed.isEmpty()
val moves = mutableListOf<TayuMove>()
for (row in 0 until BOARD_SIZE) {
for (col in 0 until BOARD_SIZE) {
for (facing in Facing.entries) {
if (fits(state, mouths, opening, tile, row, col, facing)) {
moves += TayuMove(row, col, facing)
}
}
}
}
return moves
}
/**
* Whether a tile can be laid here.
*
* The interesting half is the mouth accounting. Walk the tile's eight
* perimeter slots; for each, look at what lies across it:
*
* - off the board — fine either way. A mouth there is a scoring exit, and a
* blank there is just shoreline.
* - an empty cell — fine either way. A river runs on into open ground.
* - another tile — then the two must agree. A mouth must meet a mouth, and
* a blank must meet a blank.
*
* That last comparison is doing double duty: it refuses a river that would
* dead-end against the flank of an existing tile, and in the same breath it
* refuses a placement whose own blank flank would wall off a river already
* on the board.
*/
private fun fits(
state: TayuState,
mouths: IntArray,
opening: Boolean,
tile: Int,
row: Int,
col: Int,
facing: Facing,
): Boolean {
val rows = IntArray(TILE_LENGTH)
val cols = IntArray(TILE_LENGTH)
for (i in 0 until TILE_LENGTH) {
rows[i] = row + i * facing.dr
cols[i] = col + i * facing.dc
if (!TayuBoard.onBoard(rows[i], cols[i])) return false
if (state.tileAt[TayuBoard.cellAt(rows[i], cols[i])] != NO_TILE) return false
}
// The opening tile has no river to join, only the centre to cover.
if (opening) {
return (0 until TILE_LENGTH).any {
TayuBoard.cellAt(rows[it], cols[it]) in TayuBoard.centre
}
}
var joins = 0
for (slot in 0 until TileSlots.COUNT) {
val i = TileSlots.cellOf(slot)
val direction = absoluteFacing(facing, TileSlots.flankOf(slot))
val neighbourRow = rows[i] + direction.dr
val neighbourCol = cols[i] + direction.dc
if (!TayuBoard.onBoard(neighbourRow, neighbourCol)) continue
val neighbour = TayuBoard.cellAt(neighbourRow, neighbourCol)
if (state.tileAt[neighbour] == NO_TILE) continue
val ours = TayuTiles.hasMouth(tile, slot)
val theirs = hasMouth(mouths, neighbour, direction.opposite)
if (ours != theirs) return false
if (ours) joins++
}
// Every tile after the first has to join the river already down.
return joins > 0
}
// -----------------------------------------------------------------------
// Move application
// -----------------------------------------------------------------------
override fun applyMove(state: TayuState, seat: Int, move: TayuMove): TayuState {
require(currentSeat(state) == seat) { "Not seat $seat's turn" }
require(move in legalMoves(state, seat)) { "Illegal placement $move for seat $seat" }
val placed = previewPlacement(state, seat, move)
val gained = exitsOf(placed).product(placed.axisOf(seat)) -
exitsOf(state).product(state.axisOf(seat))
val noted = placed.copy(
log = placed.log + buildString {
append("Seat $seat lays a tile at ")
append(coordinate(move.row, move.col))
if (gained > 0) append(" — ${placed.axisOf(seat).label} now scores")
append(".")
},
)
return openTurn(noted, seat = (seat + 1) % state.playerCount)
}
/**
* The board with [move] laid on it, and nothing else changed — no draw, no
* change of turn.
*
* Public because the AI leans on it: rating a placement means looking at the
* board it would produce, and going through [applyMove] for that would also
* deal the next tile, which costs far more than the rating does.
*/
fun previewPlacement(state: TayuState, seat: Int, move: TayuMove): TayuState {
val tile = requireNotNull(state.drawn) { "No tile has been drawn" }
val placedTile = PlacedTile(
mask = tile,
row = move.row,
col = move.col,
facing = move.facing,
seat = seat,
)
val index = state.placed.size
val tileAt = state.tileAt.toMutableList()
placedTile.cells().forEach { tileAt[it] = index }
return state.copy(
tileAt = tileAt,
placed = state.placed + placedTile,
drawn = null,
)
}
/**
* Hands the next tile to [seat].
*
* A drawn tile that cannot be laid anywhere is set aside and the turn moves
* on, so this keeps drawing — and keeps passing the turn — until it finds a
* tile somebody can actually place. When the bag runs dry the game is over,
* which means the seat on the clock always has at least one legal move.
*/
private fun openTurn(state: TayuState, seat: Int): TayuState {
var bag = state.bag
var setAside = state.setAside
var log = state.log
var turn = seat
while (bag.isNotEmpty()) {
val tile = bag.first()
bag = bag.drop(1)
val candidate = state.copy(
bag = bag,
bagCount = bag.size,
drawn = tile,
setAside = setAside,
turn = turn,
log = log,
)
if (placementsFor(candidate, tile).isNotEmpty()) return candidate
setAside = setAside + tile
log = log + "Seat $turn draws a tile that will not fit anywhere. Set aside."
turn = (turn + 1) % state.playerCount
}
return state.copy(
bag = emptyList(),
bagCount = 0,
drawn = null,
setAside = setAside,
turn = turn,
phase = TayuPhase.GAME_OVER,
log = log + "The bag is empty. ${summaryOf(state)}",
)
}
// -----------------------------------------------------------------------
// Reading the board
// -----------------------------------------------------------------------
/**
* River mouths per cell, as a bitmask over [Facing.ordinal].
*
* Rebuilt from [TayuState.placed] on demand rather than carried in the
* state, so there is no second copy of the board that could drift out of
* step with the first.
*/
fun mouthMap(state: TayuState): IntArray {
val map = IntArray(BOARD_CELLS)
for (tile in state.placed) {
val cells = tile.cells()
for (slot in TayuTiles.mouthSlots(tile.mask)) {
val cell = cells[TileSlots.cellOf(slot)]
val direction = absoluteFacing(tile.facing, TileSlots.flankOf(slot))
map[cell] = map[cell] or (1 shl direction.ordinal)
}
}
return map
}
private fun hasMouth(mouths: IntArray, cell: Int, direction: Facing): Boolean =
(mouths[cell] shr direction.ordinal) and 1 == 1
/**
* Exits reached on each edge, marked ones already counted double.
*
* An exit is a mouth pointing off the board. It needs no connectivity check
* — see the note on [TayuRules].
*/
fun exitsOf(state: TayuState): EdgeExits {
val totals = IntArray(4)
for (tile in state.placed) {
val cells = tile.cells()
for (slot in TayuTiles.mouthSlots(tile.mask)) {
val cell = cells[TileSlots.cellOf(slot)]
val row = TayuBoard.rowOf(cell)
val col = TayuBoard.colOf(cell)
val direction = absoluteFacing(tile.facing, TileSlots.flankOf(slot))
if (TayuBoard.onBoard(row + direction.dr, col + direction.dc)) continue
totals[direction.ordinal] += TayuBoard.exitValue(direction, row, col)
}
}
return EdgeExits(
north = totals[Facing.NORTH.ordinal],
east = totals[Facing.EAST.ordinal],
south = totals[Facing.SOUTH.ordinal],
west = totals[Facing.WEST.ordinal],
)
}
/**
* Mouths with open ground in front of them: where the river can still grow.
*
* Returned as the cell the mouth is on and the way it points. The AI uses
* this to tell a river heading for its own edge from one heading for the
* opponent's.
*/
fun openMouths(state: TayuState): List<Pair<Int, Facing>> {
val open = mutableListOf<Pair<Int, Facing>>()
for (tile in state.placed) {
val cells = tile.cells()
for (slot in TayuTiles.mouthSlots(tile.mask)) {
val cell = cells[TileSlots.cellOf(slot)]
val direction = absoluteFacing(tile.facing, TileSlots.flankOf(slot))
val row = TayuBoard.rowOf(cell) + direction.dr
val col = TayuBoard.colOf(cell) + direction.dc
if (!TayuBoard.onBoard(row, col)) continue
if (state.tileAt[TayuBoard.cellAt(row, col)] != NO_TILE) continue
open += cell to direction
}
}
return open
}
/** Points scored by [team], which is its two edges multiplied together. */
fun scoreOf(state: TayuState, team: Int): Int =
exitsOf(state).product(axisOfTeam(team))
/** The winning team, or null for a draw. */
fun winnerOf(state: TayuState): Int? {
val northSouth = scoreOf(state, 0)
val eastWest = scoreOf(state, 1)
return when {
northSouth > eastWest -> 0
eastWest > northSouth -> 1
else -> null
}
}
// -----------------------------------------------------------------------
// Results, redaction and wire format
// -----------------------------------------------------------------------
override fun isFinished(state: TayuState): Boolean = state.phase == TayuPhase.GAME_OVER
override fun summary(state: TayuState): String = summaryOf(state)
private fun summaryOf(state: TayuState): String {
val exits = exitsOf(state)
return "North–south ${exits.north}×${exits.south} = ${exits.product(Axis.NORTH_SOUTH)} " +
"East–west ${exits.east}×${exits.west} = ${exits.product(Axis.EAST_WEST)}"
}
/**
* The bag's order is the only thing anybody is not entitled to see: the
* board is in front of everyone, and a drawn tile comes out face up.
*/
override fun viewFor(state: TayuState, seat: Int): TayuState =
state.copy(bag = emptyList())
override fun encodeState(state: TayuState): String = json.encodeToString(state)
override fun decodeState(json: String): TayuState = this.json.decodeFromString(json)
override fun encodeMove(move: TayuMove): String = json.encodeToString(move)
override fun decodeMove(json: String): TayuMove = this.json.decodeFromString(json)
/** Board coordinates the way a player would read them out: `f12`. */
fun coordinate(row: Int, col: Int): String = "${'a' + col}${row + 1}"
}