games/chess: local games end on fivefold and 75-move draws
- Commit
582755b4b687b2000a42d94780afea5c868bc1ce- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 21:34 UTC (5 days ago)
- Parents
c253a4f
Local games could be played forever: GameResult had no repetition or move-count draw, so shuffling knights back and forth (5th occurrence of the start position at ply 16) or 75 moves per side without a pawn move or capture never ended the game. The board had no such predicates and the ViewModel's terminal-result computation could not produce them. Board gains isFivefoldRepetition (replaying the recorded history, comparing placement + side-to-move + castling rights + actually capturable en-passant target — the 'same possible moves' definition) and isSeventyFiveMoveDraw (150 trailing quiet plies). resultFor tests checkmate/insufficient/stalemate first, then the two draws; restored games pick this up by re-deriving status. Threefold and fifty-move are claim-only under FIDE and the app has no claim UI, so auto-ending at 3 occurrences would itself be a rules violation — only the mandatory forms are implemented. Regression tests pin the 3rd-vs-5th occurrence, 100/149/150 ply edges and pawn/capture resets, plus a ViewModel knight-shuffle end-to-end. Move legality was validated against known perft positions (Kiwipete, en-passant pin, castling suites — exact matches). Verified: :games:chess:testDevUnitTest 163 tests pass, lint green.
Diff
games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.ktindex e7e5d44d50..d76916b62e 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessFen.kt@@ -18,6 +18,80 @@ fun Board.toFen(): String { return "$boardStr $turn ${castling.ifEmpty { "-" }} $enPassant 0 1" } +private const val FIVEFOLD_OCCURRENCES = 5+private const val SEVENTY_FIVE_MOVE_PLIES = 150++/**+ * Draw under the seventy-five-move rule: the last 75 moves by each player (150 plies)+ * contained no pawn move and no capture. This is the mandatory form of the fifty-move+ * rule — at 50 moves a player may only *claim* a draw, and this game has no claim+ * mechanism, so play correctly continues until 75. A checkmate on the final move+ * still wins; callers must test mate before this.+ *+ * Reads only [Board.moves], so it is meaningful only for boards whose move list is+ * the full game history from the initial position (local games), not puzzle boards.+ */+fun Board.isSeventyFiveMoveDraw(): Boolean =+ moves.takeLastWhile { it.piece.type != PieceType.PAWN && it.capturedPiece == null }+ .size >= SEVENTY_FIVE_MOVE_PLIES++/**+ * Draw by fivefold repetition: the current position, with [sideToMove] to play, has+ * occurred at least five times in this game. This is the mandatory form of threefold+ * repetition — the third occurrence only entitles a player to claim, so the game+ * correctly continues until the fifth.+ *+ * Occurrences are counted by replaying [Board.moves] from the initial position and+ * comparing position keys (placement, side to move, castling rights, and en-passant+ * capture availability), so this is meaningful only for boards whose move list is the+ * full game history from the initial position (local games), not puzzle boards.+ */+fun Board.isFivefoldRepetition(sideToMove: PieceColor): Boolean {+ if (moves.isEmpty()) return false+ val target = repetitionKey(sideToMove)+ var occurrences = 0+ var replay = Board.initialState+ var turn = PieceColor.WHITE+ if (replay.repetitionKey(turn) == target) occurrences+++ for (move in moves) {+ replay = replay.movePiece(move.start, move.end, move.promotedTo)+ turn = turn.opposite+ if (replay.repetitionKey(turn) == target) occurrences+++ }+ return occurrences >= FIVEFOLD_OCCURRENCES+}++/**+ * Identity of a position for repetition purposes. The en-passant field of [toFen] is+ * set after every pawn double-step, but two positions differ under the Laws only when+ * the same moves are possible in both, so the target square counts only when a legal+ * en-passant capture actually exists for the side to move.+ */+private fun Board.repetitionKey(sideToMove: PieceColor): String {+ val fields = toFen().split(" ")+ val enPassant = if (hasLegalEnPassantCapture(sideToMove)) fields[3] else "-"+ val turnField = if (sideToMove == PieceColor.WHITE) "w" else "b"+ return "${fields[0]} $turnField ${fields[2]} $enPassant"+}++private fun Board.hasLegalEnPassantCapture(sideToMove: PieceColor): Boolean {+ val last = lastMove ?: return false+ if (last.piece.type != PieceType.PAWN) return false+ if (abs(last.start.row - last.end.row) != PAWN_DOUBLE_STEP) return false+ val target = Position((last.start.row + last.end.row) / 2, last.start.col)+ for (col in listOf(target.col - 1, target.col + 1)) {+ if (col !in 0 until BOARD_SIZE) continue+ val pawnPos = Position(last.end.row, col)+ val pawn = pieces[pawnPos.row][pawnPos.col]+ if (pawn?.type == PieceType.PAWN && pawn.color == sideToMove &&+ isValidMove(pawnPos, target)+ ) {+ return true+ }+ }+ return false+}+ /** UCI text for this move (`e2e4`, `e7e8q`): the move-list encoding saved games persist. */ fun Move.toUci(): String = buildString { append(getFileChar(start.col)); append(getRankChar(start.row))
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.ktindex 107281ad12..ac8afb5911 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt@@ -8,6 +8,8 @@ import com.vayunmathur.games.chess.data.PieceColor import com.vayunmathur.games.chess.data.PieceType import com.vayunmathur.games.chess.data.Position import com.vayunmathur.games.chess.data.opposite+import com.vayunmathur.games.chess.data.isFivefoldRepetition+import com.vayunmathur.games.chess.data.isSeventyFiveMoveDraw import com.vayunmathur.games.chess.data.parseUciMove import com.vayunmathur.games.chess.data.toFen import com.vayunmathur.games.chess.data.toUci@@ -45,6 +47,10 @@ sealed class GameResult { data object Stalemate : GameResult() /** Singleton holding insufficient material state and operations. */ data object InsufficientMaterial : GameResult()+ /** Singleton holding fivefold repetition state and operations. */+ data object FivefoldRepetition : GameResult()+ /** Singleton holding seventy-five-move state and operations. */+ data object SeventyFiveMove : GameResult() val isGameOver: Boolean get() = true }@@ -377,9 +383,13 @@ class ChessViewModel(application: Application) : AndroidViewModel(application), /** Terminal result for [board] when it is [turn]'s move, or null if play continues. */ private fun resultFor(board: Board, turn: PieceColor): GameResult? = when {+ // Checkmate first: a mating move wins even when it is also the move that+ // completes the fifth repetition or the seventy-fifth move without progress. board.isCheckmate(turn) -> GameResult.Checkmate(turn.opposite) board.isInsufficientMaterial() -> GameResult.InsufficientMaterial board.isStalemate(turn) -> GameResult.Stalemate+ board.isFivefoldRepetition(turn) -> GameResult.FivefoldRepetition+ board.isSeventyFiveMoveDraw() -> GameResult.SeventyFiveMove else -> null } @@ -393,6 +403,8 @@ class ChessViewModel(application: Application) : AndroidViewModel(application), else ctx.getString(R.string.black_wins) GameResult.Stalemate -> ctx.getString(R.string.stalemate) GameResult.InsufficientMaterial -> ctx.getString(R.string.draw_insufficient_material)+ GameResult.FivefoldRepetition -> ctx.getString(R.string.draw_fivefold_repetition)+ GameResult.SeventyFiveMove -> ctx.getString(R.string.draw_seventy_five_move) null -> if (board.isKingInCheck(turn)) ctx.getString(R.string.check) else null } return result to text
games/chess/src/main/res/values/strings.xml
diff --git a/games/chess/src/main/res/values/strings.xml b/games/chess/src/main/res/values/strings.xmlindex dca0299562..48b20d8b77 100644--- a/games/chess/src/main/res/values/strings.xml+++ b/games/chess/src/main/res/values/strings.xml@@ -33,6 +33,10 @@ <string name="stalemate">Stalemate! It\'s a draw.</string> <!-- ChessViewModel: Game over insufficient material draw. Sentence --> <string name="draw_insufficient_material">Draw — insufficient material.</string>+ <!-- ChessViewModel: Game over fivefold repetition draw. Sentence -->+ <string name="draw_fivefold_repetition">Draw — same position five times.</string>+ <!-- ChessViewModel: Game over seventy-five-move draw. Sentence -->+ <string name="draw_seventy_five_move">Draw — seventy-five moves without a pawn move or capture.</string> <!-- ChessBoard: Accessibility content description for white king piece. Noun phrase --> <string name="piece_white_king">White King</string>
games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessDrawRulesTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessDrawRulesTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessDrawRulesTest.ktnew file mode 100644index 0000000000..15dd019ae8--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/data/ChessDrawRulesTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.games.chess.data++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The mandatory draw rules the local game must end on by itself: fivefold+ * repetition and the seventy-five-move rule. Their claim-only forms (threefold,+ * fifty-move) must NOT end the game, so the third repetition and the 50-move+ * (100-ply) mark are asserted to keep playing.+ */+class ChessDrawRulesTest {+ private fun sq(file: Char, rank: Int) = Position(8 - rank, file - 'a')++ /** One knight-shuffle cycle: returns to the initial position in four plies. */+ private fun shuffleCycle(board: Board): Board {+ var b = board+ b = b.movePiece(sq('g', 1), sq('f', 3)) // Nf3+ b = b.movePiece(sq('g', 8), sq('f', 6)) // Nf6+ b = b.movePiece(sq('f', 3), sq('g', 1)) // Ng1+ b = b.movePiece(sq('f', 6), sq('g', 8)) // Ng8+ return b+ }++ @Test+ fun `fivefold repetition is a draw but the third occurrence is not`() {+ // FEN: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -+ // Sequence: (Nf3 Nf6 Ng1 Ng8) repeated. The start position occurs at+ // plies 0, 4, 8, 12, 16 — the fifth occurrence must end the game.+ var board = Board.initialState+ repeat(2) { board = shuffleCycle(board) }+ assertFalse(+ board.isFivefoldRepetition(PieceColor.WHITE),+ "third occurrence (8 plies) is claim-only, not an automatic draw",+ )+ repeat(2) { board = shuffleCycle(board) }+ assertTrue(+ board.isFivefoldRepetition(PieceColor.WHITE),+ "fifth occurrence (16 plies) is an automatic draw",+ )+ }++ @Test+ fun `repetition needs the same side to move`() {+ var board = Board.initialState+ repeat(4) { board = shuffleCycle(board) }+ assertFalse(board.isFivefoldRepetition(PieceColor.BLACK))+ }++ @Test+ fun `seventy five moves without pawn move or capture is a draw`() {+ val quiet = Move(+ sq('g', 1), sq('f', 3),+ Piece(PieceType.KNIGHT, PieceColor.WHITE),+ )+ fun boardWith(moves: List<Move>) = Board(Board.initialState.pieces, moves = moves)++ assertFalse(boardWith(List(100) { quiet }).isSeventyFiveMoveDraw(), "50 moves: claim only")+ assertFalse(boardWith(List(149) { quiet }).isSeventyFiveMoveDraw())+ assertTrue(boardWith(List(150) { quiet }).isSeventyFiveMoveDraw())++ val pawnMove = Move(+ sq('e', 2), sq('e', 4),+ Piece(PieceType.PAWN, PieceColor.WHITE),+ )+ assertFalse(+ boardWith(List(150) { quiet } + pawnMove).isSeventyFiveMoveDraw(),+ "a pawn move resets the count",+ )+ val capture = quiet.copy(capturedPiece = Piece(PieceType.PAWN, PieceColor.BLACK))+ assertFalse(+ boardWith(listOf(capture) + List(149) { quiet }).isSeventyFiveMoveDraw(),+ "a capture resets the count",+ )+ }+}
games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessViewModelTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessViewModelTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessViewModelTest.ktindex 02a795a042..de8b46cf40 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessViewModelTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/util/ChessViewModelTest.kt@@ -80,6 +80,22 @@ class ChessViewModelTest { assertNull(vm.uiState.value.selectedPiece) } + @Test fun `fifth repetition of the start position ends the game as a draw`() {+ val vm = ChessViewModel(app)+ fun cycle() {+ fun move(f1: Char, r1: Int, f2: Char, r2: Int) {+ vm.onSquareClick(sq(f1, r1)); vm.onSquareClick(sq(f2, r2))+ }+ move('g', 1, 'f', 3); move('g', 8, 'f', 6)+ move('f', 3, 'g', 1); move('f', 6, 'g', 8)+ }+ repeat(2) { cycle() }+ assertNull(vm.uiState.value.gameResult, "third occurrence is claim-only: play continues")+ repeat(2) { cycle() }+ assertEquals(GameResult.FivefoldRepetition, vm.uiState.value.gameResult)+ assertTrue(vm.uiState.value.gameStatus?.isNotBlank() == true)+ }+ @Test fun `vs ai as black flips board and promote without pending promotion is ignored`() { val vm = ChessViewModel(app) vm.onNewGame(GameMode.VsAI(PieceColor.BLACK, Difficulty.BEGINNER))