Board
The Board class represents the positions of pieces on a chessboard at a specific moment. It tracks which Piece occupies each of the 64 squares, if any. This class focuses solely on the arrangement of pieces and provides methods for querying and updating positions, applying moves to generate new board configurations, and accessing pieces by square or algebraic notation. It does not track additional game state details such as castling rights, en passant targets, or move history.
Overview
Each square is uniquely identified by its File (column) and Rank (row).
The board state is internally managed using a mutable map, allowing efficient access and updates.
The class supports algebraic notation (e.g., "e4") for intuitive square referencing.
Special chess rules such as castling, en passant, and pawn promotion are handled seamlessly.
Internal Implementation Details
Board State Storage
The board state is stored in a MutableMap<Square, Piece?> called squaresMap. Each key is a Square (which combines a File and Rank), and the value is either a Piece (if a piece occupies that square) or null (if the square is empty). All 64 squares are always present as keys in the map.
Access Patterns
By Square: You can access or modify a square directly using the Square object.
By File and Rank: Overloaded operators allow access via File and Rank parameters.
By Algebraic Notation: You can use algebraic notation (e.g.,
"e4") to get or set a piece, which is internally converted to a Square.
Manipulation
Setting a Piece: Assigning a Piece (or
null) to a square updates the corresponding entry insquaresMap.Applying Moves: The applyMove method creates a deep copy of the board, applies the move (including special rules like promotion, en passant, and castling), and returns the new board.
Immutability: Although
squaresMapis mutable for internal convenience, the class is designed to be used immutably: most operations return a newBoardinstance, preserving the original.Copying: The copy method creates a deep copy of the board and all pieces, ensuring no shared mutable state between board instances.
Example of Internal Access
// Access by file and rank
val piece = board[File('e'), Rank(4)]
// Set by square
board[Square("e4")] = Piece(PieceType.QUEEN, PieceColor.WHITE)
// Access by algebraic notation
val pawn = board["e2"]Usage Example
// Initializing a chess board and applying a move
val board = Board.initialBoard()
val move = Move("e2","e4")
val newBoard = board.applyMove(move)Functions
Gets the Piece at the square specified by algebraic notation.
Returns the Square occupied by the king of the given PieceColor, or null if not found.
Sets the Piece at the square specified by algebraic notation.