Chesslib

repository·master·Indexed 43 days ago

https://github.com/bhlangonijr/chesslib

A high-performance Java library for chess engine development, UI building, and move validation. Version 1.3.7 provides support for move generation, PGN/FEN parsing, Chess960, and bitboards for high-performance operations. It includes utilities for Zobrist hashing, Perft validation, and PgnIterator for processing large chess databases.

Tokens
2K
Snippets
7
Records
12
Agent score
5%

What's inside Chesslib

  1. Support Chess960 (Fischer Random)

    master

    Chesslib provides full support for Chess960, including move generation, validation, and FEN round-trips.

    Detection and Loading

    Chess960 is automatically detected when loading FENs with non-standard king positions. You can also force it explicitly:

    board.loadFromFen("bnqbrnkr/pppppppp/8/8/8/8/PPPPPPPP/BNQBRNKR w KQkq - 0 1", true);

    UCI Notation for Chess960

    Because Chess960 castling uses king-to-rook encoding, use the specialized UCI methods:

    • board.toUci(Move move): Converts a move to UCI string.
    • board.fromUci(String uciString): Parses a UCI string into a Move.
    Board board = new Board();
    board.loadFromFen("bnqbrnkr/pppppppp/8/8/8/8/PPPPPPPP/BNQBRNKR w KQkq - 0 1");
    Move oo = board.getContext().getoo(Side.WHITE);
    board.toUci(oo);    // "g1h1" (king→rook)
    Move parsed = board.fromUci("g1h1");  // returns the O-O castle move
  2. Install Chesslib via Maven or Gradle

    master

    To use Chesslib in your Java project, add the JitPack repository and the dependency to your build configuration. Use version 1.3.7 for the current stable release.

    #### Maven
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
    
    <dependency>
        <groupId>com.github.bhlangonijr</groupId>
        <artifactId>chesslib</artifactId>
        <version>1.3.7</version>
    </dependency>
    
    #### Gradle
    ```groovy
    repositories { maven { url 'https://jitpack.io' } }
    dependencies { implementation 'com.github.bhlangonijr:chesslib:1.3.7' }
  3. Parse large PGN files with PgnIterator

    master

    For processing large chess databases, use PgnIterator to stream games one by one, preventing memory exhaustion.

    // Iterate through a PGN file game by game
    PgnIterator games = new PgnIterator("grandmaster_games.pgn");
    
    for (Game game : games) {
        System.out.println("Event: " + game.getEvent());
        System.out.println("White: " + game.getWhitePlayer().getName());
        System.out.println("Black: " + game.getBlackPlayer().getName());
        
        // Load the moves to replay them
        game.loadMoveText();
        MoveList moves = game.getHalfMoves();
    }
  4. Make moves on a Board

    master

    The Board class is the primary entry point. You can initialize a new board in the starting position and execute moves using either Standard Algebraic Notation (SAN) strings or Move objects containing Square constants.

    import com.github.bhlangonijr.chesslib.*;
    
    public class Main {
        public static void main(String[] args) {
            // Create a new board in the starting position
            Board board = new Board();
    
            // Make a move using SAN (Standard Algebraic Notation)
            board.doMove("e4"); 
            
            // Make a move using Square constants
            board.doMove(new Move(Square.E7, Square.E5));
    
            // Print the board to console
            System.out.println(board.toString());
        }
    }
  5. Convert between SAN and MoveList

    master

    Use MoveList to handle sequences of moves in standard algebraic notation.

    // Load a game sequence from a string
    MoveList list = new MoveList();
    list.loadFromSan("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6");
    
    // Export to SAN array
    String[] sanMoves = list.toSanArray();
    
    // Apply all moves to a board
    Board board = new Board();
    for (Move move : list) {
        board.doMove(move);
    }
  6. Compare boards and use Zobrist hashing

    master

    For rapid lookups and repetition detection:

    • board.getZobristKey(): Returns the Zobrist hash (long) for use in transposition tables.
    • board.strictEquals(Board otherBoard): Compares both the position and the move history (essential for detecting 3-fold repetition).
  7. Inspect Board state and game status

    master

    The Board class provides methods to inspect the current position and check for game-ending conditions:

    • board.getSideToMove(): Returns Side.WHITE or Side.BLACK.
    • board.getPiece(Square square): Returns the Piece at a square (or Piece.NONE).
    • board.getPieceLocation(Piece piece): Returns a List<Square> where the specified piece is located.
    • board.isMated(): Returns true if the side to move is checkmated.
    • board.isStaleMate(): Returns true if the position is a stalemate.
    • board.isKingAttacked(): Returns true if the current King is in check.
    • board.isDraw(): Checks all draw rules (repetition, 50-move rule, insufficient material).
  8. Listen to Board events

    master

    You can attach event listeners to a Board to trigger actions (like UI updates) when the state changes.

    board.addEventListener(BoardEventType.ON_MOVE, event -> {
        Move move = (Move) event;
        System.out.println("Move played: " + move);
        // Trigger GUI update here...
    });
  9. Manipulate Board state and history

    master

    Use the Board class to execute moves, undo them, or validate legality.

    • board.doMove(String san): Parses and executes a SAN move string (e.g., "Nf3").
    • board.doMove(Move move): Executes a Move object (more performant than SAN).
    • board.undoMove(): Reverts the last move and returns the undone Move.
    • board.legalMoves(): Returns a List<Move> of all valid moves.
    • board.isMoveLegal(Move move, boolean check): Returns boolean indicating if a specific move is valid.
  10. Access Bitboards for high-performance engine development

    master

    For engine developers, Board provides access to 64-bit integer (long) representations of piece positions for bitwise operations.

    • board.getBitboard(Piece piece): Returns a bitmask of all squares occupied by the specified piece.
    • board.getBitboard(): Returns a bitmask of all occupied squares on the board.
  11. Persist and load board positions using FEN

    master

    Use Forsyth-Edwards Notation (FEN) to export or import board states.

    • board.getFen(): Exports the current board state as a FEN string.
    • board.loadFromFen(String fenString): Resets the board to the state described by the FEN string.
  12. Validate move generator with Perft

    master

    Use the Perft class to validate the move generator by calculating node counts at specific depths.

    // Calculate nodes at depth 5 (Standard Start Position)
    // Should return 4,865,609
    long nodes = Perft.perft(board, 5);