chess.js
chess.js is a TypeScript chess library used for chess move
generation/validation, piece placement/movement, and check/checkmate/stalemate
detection - basically everything but the AI.
chess.js has been extensively tested in node.js and most modern browsers.
Installation
Run the following command to install the most recent version of chess.js from
NPM:
npm install chess.js
Importing
Import (as ESM)
import { Chess } from 'chess.js'
ECMAScript modules (ESM) can be directly imported in a browser:
<script type="module">
import { Chess } from 'chess.js'
</script>
Import (as CommonJS)
const { Chess } = require('chess.js')
Example Code
The code below plays a random game of chess:
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())
User Interface
By design, chess.js is a headless library and does not include user interface
elements. Many developers have successfully integrated chess.js with the
chessboard.js library. See
chessboard.js - Random vs Random for an
example.
Parsers (permissive / strict)
This library includes two parsers (permissive
and strict
) which are used to
parse different forms of chess move notation. The permissive
parser (the
default) is able to handle many non-standard derivatives of algebraic notation
(e.g. Nf3
, g1f3
, g1-f3
, Ng1f3
, Ng1-f3
, Ng1xf3
). The strict
parser
only accepts moves in Standard Algebraic Notation and requires that they
strictly adhere to the specification. The strict
parser runs slightly faster
but will not parse any non-standard notation.
API
Constants
The following constants are exported from the top-level module:
export const WHITE = 'w'
export const BLACK = 'b'
export const PAWN = 'p'
export const KNIGHT = 'n'
export const BISHOP = 'b'
export const ROOK = 'r'
export const QUEEN = 'q'
export const KING = 'k'
export const DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
export const SQUARES = ['a8', 'b8', 'c8', ..., 'f1', 'g1', 'h1']
Constructor: Chess([ fen ])
The Chess() constructor takes an optional parameter which specifies the board
configuration in
Forsyth-Edwards Notation (FEN).
Throws an exception if an invalid FEN string is provided.
import { Chess } from 'chess.js'
let chess = new Chess()
let chess = new Chess(
'r1k4r/p2nb1p1/2b4p/1p1n1p2/2PP4/3Q1NB1/1P3PPP/R5K1 b - - 0 19',
)
.ascii()
Returns a string containing an ASCII diagram of the current position.
const chess = new Chess()
chess.move('e4')
chess.move('e5')
chess.move('f4')
chess.ascii()
.board()
Returns an 2D array representation of the current position. Empty squares are
represented by null
.
const chess = new Chess()
chess.board()
{square: 'b8', type: 'n', color: 'b'},
{square: 'c8', type: 'b', color: 'b'},
{square: 'd8', type: 'q', color: 'b'},
{square: 'e8', type: 'k', color: 'b'},
{square: 'f8', type: 'b', color: 'b'},
{square: 'g8', type: 'n', color: 'b'},
{square: 'h8', type: 'r', color: 'b'}],
[...],
[...],
[...],
[...],
[...],
[{square: 'a1', type: 'r', color: 'w'},
{square: 'b1', type: 'n', color: 'w'},
{square: 'c1', type: 'b', color: 'w'},
{square: 'd1', type: 'q', color: 'w'},
{square: 'e1', type: 'k', color: 'w'},
{square: 'f1', type: 'b', color: 'w'},
{square: 'g1', type: 'n', color: 'w'},
{square: 'h1', type: 'r', color: 'w'}]]
Clears the board.
chess.clear()
chess.fen()
Delete and return the comment for the current position, if it exists.
const chess = new Chess()
chess.loadPgn('1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 {giuoco piano} *')
chess.getComment()
chess.deleteComment()
chess.getComment()
Delete and return comments for all positions.
const chess = new Chess()
chess.loadPgn(
"1. e4 e5 {king's pawn opening} 2. Nf3 Nc6 3. Bc4 Bc5 {giuoco piano} *",
)
chess.deleteComments()
chess.getComments()
.fen()
Returns the FEN string for the current position. Note, the en passant square is
only included if the side-to-move can legally capture en passant.
const chess = new Chess()
chess.move('e4')
chess.move('e5')
chess.move('f4')
chess.fen()
.get(square)
Returns the piece on the square:
chess.put({ type: PAWN, color: BLACK }, 'a5')
chess.get('a5')
chess.get('a6')
.getCastlingRights(color)
Gets the castling rights for the given color. An object is returned which
indicates whether the right is available or not for both kingside and queenside.
Note this does not indicate if such a move is legal or not in the current
position as checks etc. also need to be considered.
const chess = new Chess()
chess.getCastlingRights(BLACK)
Retrieve the comment for the current position, if it exists.
const chess = new Chess()
chess.loadPgn('1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 {giuoco piano} *')
chess.getComment()
Retrieve comments for all positions.
const chess = new Chess()
chess.loadPgn(
"1. e4 e5 {king's pawn opening} 2. Nf3 Nc6 3. Bc4 Bc5 {giuoco piano} *",
)
chess.getComments()
Allows header information to be added to PGN output. Any number of key/value
pairs can be passed to .header().
chess.header('White', 'Robert James Fischer')
chess.header('Black', 'Mikhail Tal')
chess.header('White', 'Morphy', 'Black', 'Anderssen', 'Date', '1858-??-??')
Calling .header() without any arguments returns the header information as an
object.
chess.header()
.history([ options ])
Returns a list containing the moves of the current game. Options is an optional
parameter which may contain a 'verbose' flag. See .moves() for a description of
the verbose move fields. A FEN string of the position prior to the move being
made is added to the verbose history output.
const chess = new Chess()
chess.move('e4')
chess.move('e5')
chess.move('f4')
chess.move('exf4')
chess.history()
chess.history({ verbose: true })
.inCheck()
Returns true or false if the side to move is in check.
const chess = new Chess(
'rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3',
)
chess.inCheck()
.isAttacked(square, color)
Returns true if the square is attacked by any piece of the given color.
const chess = new Chess()
chess.isAttacked('f3', WHITE)
chess.isAttacked('f6', BLACK)
chess.load(DEFAULT_POSITION)
chess.isAttacked('e2', WHITE)
chess.load('4k3/4n3/8/8/8/8/4R3/4K3 w - - 0 1')
chess.isAttacked('c6', BLACK)
.isCheckmate()
Returns true or false if the side to move has been checkmated.
const chess = new Chess(
'rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3',
)
chess.isCheckmate()
.isDraw()
Returns true or false if the game is drawn (50-move rule or insufficient
material).
const chess = new Chess('4k3/4P3/4K3/8/8/8/8/8 b - - 0 78')
chess.isDraw()
.isInsufficientMaterial()
Returns true if the game is drawn due to insufficient material (K vs. K, K vs.
KB, or K vs. KN) otherwise false.
const chess = new Chess('k7/8/n7/8/8/8/8/7K b - - 0 1')
chess.isInsufficientMaterial()
.isGameOver()
Returns true if the game has ended via checkmate, stalemate, draw, threefold
repetition, or insufficient material. Otherwise, returns false.
const chess = new Chess()
chess.isGameOver()
chess.load('4k3/4P3/4K3/8/8/8/8/8 b - - 0 78')
chess.isGameOver()
chess.load('rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3')
chess.isGameOver()
.isStalemate()
Returns true or false if the side to move has been stalemated.
const chess = new Chess('4k3/4P3/4K3/8/8/8/8/8 b - - 0 78')
chess.isStalemate()
.isThreefoldRepetition()
Returns true or false if the current board position has occurred three or more
times.
const chess = new Chess('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1')
chess.isThreefoldRepetition()
chess.move('Nf3') chess.move('Nf6') chess.move('Ng1') chess.move('Ng8')
chess.isThreefoldRepetition()
chess.move('Nf3') chess.move('Nf6') chess.move('Ng1') chess.move('Ng8')
chess.isThreefoldRepetition()
Clears the board and loads the provided FEN string. The castling rights, en
passant square and move numbers are defaulted to - - 0 1
if omitted. Throws an
exception if the FEN is invalid.
const chess = new Chess()
chess.load('4r3/8/2p2PPk/1p6/pP2p1R1/P1B5/2P2K2/3r4 w - - 1 45')
try {
chess.load('8/4p3/8/8/8/8/4P3/6K1 w - - 1 45')
} catch (e) {
console.log(e)
}
chess.load('8/4p3/8/8/8/8/4P3/6K1 w - - 1 45', { skipValidation: true })
.loadPgn(pgn, [ options ])
Load the moves of a game stored in
Portable Game Notation.
pgn
should be a string. Options is an optional object which may contain a
string newlineChar
and a boolean strict
.
The newlineChar
is a string representation of a valid RegExp fragment and is
used to process the PGN. It defaults to \r?\n
. Special characters should not
be pre-escaped, but any literal special characters should be escaped as is
normal for a RegExp. Keep in mind that backslashes in JavaScript strings must
themselves be escaped (see sloppyPgn
example below). Avoid using a
newlineChar
that may occur elsewhere in a PGN, such as .
or x
, as this
will result in unexpected behavior.
The strict
flag is a boolean (default: false
) that instructs chess.js to
only parse moves in Standard Algebraic Notation form. See .move
documentation
for more information about non-SAN notations.
The method will throw and exception if the PGN fails to parse.
const chess = new Chess()
const pgn = [
'[Event "Casual Game"]',
'[Site "Berlin GER"]',
'[Date "1852.??.??"]',
'[EventDate "?"]',
'[Round "?"]',
'[Result "1-0"]',
'[White "Adolf Anderssen"]',
'[Black "Jean Dufresne"]',
'[ECO "C52"]',
'[WhiteElo "?"]',
'[BlackElo "?"]',
'[PlyCount "47"]',
'',
'1.e4 e5 2.Nf3 Nc6 3.Bc4 Bc5 4.b4 Bxb4 5.c3 Ba5 6.d4 exd4 7.O-O',
'd3 8.Qb3 Qf6 9.e5 Qg6 10.Re1 Nge7 11.Ba3 b5 12.Qxb5 Rb8 13.Qa4',
'Bb6 14.Nbd2 Bb7 15.Ne4 Qf5 16.Bxd3 Qh5 17.Nf6+ gxf6 18.exf6',
'Rg8 19.Rad1 Qxf3 20.Rxe7+ Nxe7 21.Qxd7+ Kxd7 22.Bf5+ Ke8',
'23.Bd7+ Kf8 24.Bxe7# 1-0',
]
chess.loadPgn(pgn.join('\n'))
chess.ascii()
const sloppyPgn = [
'[Event "Wijk aan Zee (Netherlands)"]',
'[Date "1971.01.26"]',
'[Result "1-0"]',
'[White "Tigran Vartanovich Petrosian"]',
'[Black "Hans Ree"]',
'[ECO "A29"]',
'',
'1. Pc2c4 Pe7e5',
'2. Nc3 Nf6',
'3. Nf3 Nc6',
'4. g2g3 Bb4',
'5. Nd5 Nxd5',
'6. c4xd5 e5-e4',
'7. dxc6 exf3',
'8. Qb3 1-0',
].join(':')
chess.loadPgn(sloppyPgn, { newlineChar: ':' })
chess.loadPgn(sloppyPgn, { newlineChar: ':', strict: true })
.move(move, [ options ])
Makes a move on the board and returns a move object if the move was legal. The
move argument can be either a string in Standard Algebraic Notation (SAN) or a
move object. Throws an 'Illegal move' exception if the move was illegal.
.move() - Standard Algebraic Notation (SAN)
const chess = new Chess()
chess.move('e4')
chess.move('nf6')
chess.move('Nf6')
.move() - Object Notation
A move object contains to
, from
and, promotion
(only when necessary)
fields.
const chess = new Chess()
chess.move({ from: 'g2', to: 'g3' })
.move() - Permissive Parser
The permissive (default) move parser can be used to parse a variety of
non-standard move notations. Users may specify an { strict: true }
flag to
verify that all supplied moves adhere to the Standard Algebraic Notation
specification.
const chess = new Chess()
chess.move('e2e4')
chess.move('e7-e5')
chess.move('Pf2-f4')
chess.move('ef4')
chess.move('Ng1-f3')
chess.move('d7xd6')
chess.move('d4')
chess.load('r2qkbnr/ppp2ppp/2n5/1B2pQ2/4P3/8/PPP2PPP/RNB1K2R b KQkq - 3 7')
chess.move('Nge7')
chess.undo()
chess.move('Nge7', { strict: true })
.moveNumber()
Returns the current move number.
chess.load('4r1k1/p1prnpb1/Pp1pq1pp/3Np2P/2P1P3/R4N2/1PP2PP1/3QR1K1 w - - 2 20')
chess.moveNumber()
.moves({ piece?: Piece, square?: Square, verbose = false} = {})
Returns a list of legal moves from the current position. This function takes an
optional object which can be used to generate detailed move objects or to
restrict the move generator to specific squares or pieces.
const chess = new Chess()
chess.moves()
chess.moves({ square: 'e2' })
chess.moves({ piece: 'n' })
chess.moves({ verbose: true })
Move Objects (e.g. when { verbose: true })
The color
field indicates the color of the moving piece (w
or b
).
The from
and to
fields are from and to squares in algebraic notation.
The piece
, captured
, and promotion
fields contain the lowercase
representation of the applicable piece (pnbrqk
). The captured
and
promotion
fields are only present when the move is a valid capture or
promotion.
The san
field is the move in Standard Algebraic Notation (SAN). The lan
field is the move in Long Algebraic Notation (LAN).
The before
and after
keys contain the FEN of the position before and after
the move.
The flags
field contains one or more of the string values:
n
- a non-captureb
- a pawn push of two squarese
- an en passant capturec
- a standard capturep
- a promotionk
- kingside castlingq
- queenside castling
A flags
value of pc
would mean that a pawn captured a piece on the 8th rank
and promoted.
.pgn([ options ])
Returns the game in PGN format. Options is an optional parameter which may
include max width and/or a newline character settings.
const chess = new Chess()
chess.header('White', 'Plunky', 'Black', 'Plinkie')
chess.move('e4')
chess.move('e5')
chess.move('Nc3')
chess.move('Nc6')
chess.pgn({ maxWidth: 5, newline: '<br />' })
.put(piece, square)
Place a piece on the square where piece is an object with the form { type: ...,
color: ... }. Returns true if the piece was successfully placed, otherwise, the
board remains unchanged and false is returned. put()
will fail when passed an
invalid piece or square, or when two or more kings of the same color are placed.
chess.clear()
chess.put({ type: PAWN, color: BLACK }, 'a5')
chess.put({ type: 'k', color: 'w' }, 'h1')
chess.fen()
chess.put({ type: 'z', color: 'w' }, 'a1')
chess.clear()
chess.put({ type: 'k', color: 'w' }, 'a1')
chess.put({ type: 'k', color: 'w' }, 'h1')
.remove(square)
Remove and return the piece on square.
chess.clear()
chess.put({ type: PAWN, color: BLACK }, 'a5')
chess.put({ type: KING, color: WHITE }, 'h1')
chess.remove('a5')
chess.remove('h1')
chess.remove('e1')
.reset()
Reset the board to the initial starting position.
.setCastlingRights(color, rights)
Sets the castling rights for the given color. Returns true if the change was
successfully made. False will be returned when the position doesn't allow the
requested change i.e. if the corresponding king or rook is not on it's starting
square.
chess.setCastlingRights(WHITE, { [KING]: false, [QUEEN]: true })
Comment on the current position.
const chess = new Chess()
chess.move('e4')
chess.setComment("king's pawn opening")
chess.pgn()
.squareColor(square)
Returns the color of the square ('light' or 'dark').
const chess = Chess()
chess.squareColor('h1')
chess.squareColor('a7')
chess.squareColor('bogus square')
.turn()
Returns the current side to move.
chess.load('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1')
chess.turn()
.undo()
Takeback the last half-move, returning a move object if successful, otherwise
null.
const chess = new Chess()
chess.fen()
chess.move('e4')
chess.fen()
chess.undo()
chess.fen()
chess.undo()
validateFen(fen):
This static function returns a validation object specifying validity or the
errors found within the FEN string.
import { validateFen } from 'chess.js'
validateFen('2n1r3/p1k2pp1/B1p3b1/P7/5bP1/2N1B3/1P2KP2/2R5 b - - 4 25')
validateFen('4r3/8/X12XPk/1p6/pP2p1R1/P1B5/2P2K2/3r4 w - - 1 45')