chess.js

repository·master·Indexed 26 days ago

https://github.com/jhlywa/chess.js

A TypeScript library for chess move generation, validation, execution, and game state detection (check, checkmate, stalemate). Version 1.4.0 provides functionality for managing game state via the Chess class, including FEN and PGN loading, legal move generation, and board state manipulation. It handles the logic of the game but does not include an AI engine.

Tokens
2.7K
Snippets
4
Records
35
Agent score
88%

What's inside chess.js

  1. Play a random game of chess with chess.js

    master

    You can use the Chess class to manage game state, generate valid moves, and detect game over conditions. The following example demonstrates how to instantiate a new game, loop through valid moves randomly until the game ends, and output the final game in PGN format.

    import { Chess } from 'chess.js'
    
    const chess = new Chess()
    
    while (!chess.isGameOver()) {
      const moves = chess.moves()
      const move = moves[Math.floor(Math.random() * moves.length)]
      chess.move(move)
    }
    console.log(chess.pgn())
  2. Make a move in Chess

    master

    Use the move() method to execute a move. The method accepts several formats:

    • A SAN (Standard Algebraic Notation) string (e.g., 'e4').
    • An object specifying { from, to, promotion }.
    • null (to represent a null move).

    You can pass an optional { strict: boolean } configuration object. If strict is true, the move must be valid according to chess rules.

  3. Check game state (Check, Checkmate, Draw, etc.)

    master

    The Chess class provides several methods to query the current state of the game:

    • inCheck(): Returns true if the current player's king is in check.
    • isCheckmate(): Returns true if the game is over via checkmate.
    • isDraw(): Returns true if the game is a draw.
    • isGameOver(): Returns true if the game has ended.
    • isStalemate(): Returns true if the game is a stalemate.
    • isThreefoldRepetition(): Returns true if the game is a draw by threefold repetition.
    • isInsufficientMaterial(): Returns true if there is insufficient material to force a mate.
  4. Get available legal moves

    master

    The moves() method returns an array of legal moves. You can filter moves by square, piece, or request verbose move objects.

    Options:

    • square: Filter moves starting from a specific Square.
    • piece: Filter moves for a specific PieceSymbol.
    • verbose: If true, returns an array of Move objects instead of SAN strings.