chess.js
chess.js is a Javascript chess library that is 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.
Example Code
The code below plays a complete game of chess ... randomly.
var util = ch = ; var chess = ; while !chess util; var moves = chess; var move = movesMath; chess; util;
Need a user interface? Try Chris Oakman's excellent chessboard.js library. See chessboard.js - Random vs Random for an example integration of chess.js with chessboard.js.
API
Constructor: Chess([ fen ])
The Chess() constructor takes a optional parameter which specifies the board configuration in Forsyth-Edwards Notation.
// board defaults to the starting position when called with no parametersvar chess = ; // pass in a FEN string to load a particular positionvar chess = 'r1k4r/p2nb1p1/2b4p/1p1n1p2/2PP4/3Q1NB1/1P3PPP/R5K1 b - c3 0 19';
.ascii()
Returns a string containing an ASCII diagram of the current position.
var chess = ; // make some moveschess;chess;chess; chess;// -> ' +------------------------+// 8 | r n b q k b n r |// 7 | p p p p . p p p |// 6 | . . . . . . . . |// 5 | . . . . p . . . |// 4 | . . . . P P . . |// 3 | . . . . . . . . |// 2 | P P P P . . P P |// 1 | R N B Q K B N R |// +------------------------+// a b c d e f g h'
.clear()
Clears the board.
chessclear;chess;// -> '8/8/8/8/8/8/8/8 w - - 0 1' <- empty board
.fen()
Returns the FEN string for the current position.
var chess = ; // make some moveschess;chess;chess; chess;// -> 'rnbqkbnr/pppp1ppp/8/4p3/4PP2/8/PPPP2PP/RNBQKBNR b KQkq f3 0 2'
.game_over()
Returns true if the game has ended via checkmate, stalemate, draw, threefold repetition, or insufficient material. Otherwise, returns false.
var chess = ;chess;// -> false chess;chess;// -> true (stalemate) chess;chess;// -> true (checkmate)
.get(square)
Returns the piece on the square:
chessclear;chess // put a black pawn on a5 chess;// -> { type: 'p', color: 'b' },chess;// -> null
.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.
var chess = ;chess;chess;chess;chess; chesshistory;// -> ['e4', 'e5', 'f4', 'exf4'] chesshistory verbose: true ;// -> [{ color: 'w', from: 'e2', to: 'e4', flags: 'b', piece: 'p', san: 'e4' },// { color: 'b', from: 'e7', to: 'e5', flags: 'b', piece: 'p', san: 'e5' },// { color: 'w', from: 'f2', to: 'f4', flags: 'b', piece: 'p', san: 'f4' },// { color: 'b', from: 'e5', to: 'f4', flags: 'c', piece: 'p', captured: 'p', san: 'exf4' }]
.in_check()
Returns true or false if the side to move is in check.
var chess = 'rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3';chess;// -> true
.in_checkmate()
Returns true or false if the side to move has been checkmated.
var chess = 'rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3';chess;// -> true
.in_draw()
Returns true or false if the game is drawn (50-move rule or insufficient material).
var chess = '4k3/4P3/4K3/8/8/8/8/8 b - - 0 78';chess;// -> true
.in_stalemate()
Returns true or false if the side to move has been stalemated.
var chess = '4k3/4P3/4K3/8/8/8/8/8 b - - 0 78';chess;// -> true
.in_threefold_repetition()
Returns true or false if the current board position has occurred three or more times.
var chess = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';// -> true// rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq occurs 1st timechess;// -> false chess; chess; chess; chess;// rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq occurs 2nd timechess;// -> false chess; chess; chess; chess;// rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq occurs 3rd timechess;// -> true
.header()
Allows header information to be added to PGN output. Any number of key/value pairs can be passed to .header().
chess;chess; // or chess;
.insufficient_material()
Returns true if the game is drawn due to insufficient material (K vs. K, K vs. KB, or K vs. KN); otherwise false.
var chess = 'k7/8/n7/8/8/8/8/7K b - - 0 1';chess// -> true
.load(fen)
The board is cleared and the FEN string is loaded. Returns true if position was successfully loaded, otherwise false.
var chess = ;chess;// -> true chess;// -> false, bad piece X
.load_pgn(pgn, [ options ])
Load the moves of a game stored in Portable Game Notation. Options is a optional parameter that contains a 'newline_char' which is a string representation of a RegExp (and should not be pre-escaped) and defaults to '\r?\n'). Returns true if the PGN was parsed successfully, otherwise false.
var chess = ;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;// -> true chess// -> 1r3kr1/pbpBBp1p/1b3P2/8/8/2P2q2/P4PPP/3R2K1 b - - 0 24 chess// -> ' +------------------------+// 8 | . r . . . k r . |// 7 | p b p B B p . p |// 6 | . b . . . P . . |// 5 | . . . . . . . . |// 4 | . . . . . . . . |// 3 | . . P . . q . . |// 2 | P . . . . P P P |// 1 | . . . R . . K . |// +------------------------+// a b c d e f g h'
.move(move)
Attempts to make a move on the board, returning a move object if the move was legal, otherwise null. The .move function can be called two ways, by passing a string in Standard Algebraic Notation (SAN):
var chess = ; chess// -> { color: 'w', from: 'e2', to: 'e4', flags: 'b', piece: 'p', san: 'e4' } chess // SAN is case sensitive!!// -> null chess// -> { color: 'b', from: 'g8', to: 'f6', flags: 'n', piece: 'n', san: 'Nf6' }
Or by passing .move() a move object (only the 'to', 'from', and when necessary 'promotion', fields are needed):
var chess = ; chess;// -> { color: 'w', from: 'g2', to: 'g3', flags: 'n', piece: 'p', san: 'g3' }
.moves([ options ])
Returns a list of legals moves from the current position. The function takes an optional parameter which controls the single-square move generation and verbosity.
var chess = ;chess;// -> ['a3', 'a4', 'b3', 'b4', 'c3', 'c4', 'd3', 'd4', 'e3', 'e4',// 'f3', 'f4', 'g3', 'g4', 'h3', 'h4', 'Na3', 'Nc3', 'Nf3', 'Nh3'] chess;// -> ['e3', 'e4'] chess; // invalid square// -> [] chess;// -> [{ color: 'w', from: 'a2', to: 'a3',// flags: 'n', piece: 'p', san 'a3'// # a captured: key is included when the move is a capture// # a promotion: key is included when the move is a promotion// },// ...// ]
The piece, captured, and promotion fields contain the lowercase representation of the applicable piece.
The flags field in verbose mode may contain one or more of the following values:
- 'n' - a non-capture
- 'b' - a pawn push of two squares
- 'e' - an en passant capture
- 'c' - a standard capture
- 'p' - a promotion
- 'k' - kingside castling
- 'q' - queenside castling
A flag 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.
var chess = ;chess;chess;chess;chess;chess; chess;// -> '[White "Plunky"]<br />[Black "Plinkie"]<br /><br />1. e4 e5<br />2. Nc3 Nc6'
.put(piece, square)
Place a piece on square where piece is an object with the form
{ type: ..., color: ... }. Returns true if 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.
chessclear; chess // put a black pawn on a5// -> truechess // shorthand// -> true chess;// -> '8/8/8/p7/8/8/8/7K w - - 0 0' chess // invalid piece// -> false chessclear; chess// -> true chess // fail - two kings// -> false
.remove(square)
Remove and return the piece on square.
chessclear;chess // put a black pawn on a5chess // put a white king on h1 chess;// -> { type: 'p', color: 'b' },chess;// -> { type: 'k', color: 'w' },chess;// -> null
.reset()
Reset the board to the initial starting position.
.square_color(square)
Returns the color of the square ('light' or 'dark').
var chess = ;chess// -> 'light'chess// -> 'dark'chess// -> null
.turn()
Returns the current side to move.
chesschess// -> 'b'
.undo()
Takeback the last half-move, returning a move object if successful, otherwise null.
var chess = ; chess;// -> 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'chess;chess;// -> 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' chess;// -> { color: 'w', from: 'e2', to: 'e4', flags: 'b', piece: 'p', san: 'e4' }chess;// -> 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'chess;// -> null
.validate_fen(fen):
Returns a validation object specifying validity or the errors found within the FEN string.
chess;// -> { valid: true, error_number: 0, error: 'No errors.' } chess;// -> { valid: false, error_number: 9,// error: '1st field (piece positions) is invalid [invalid piece].' }
CONTRIBUTORS
Special thanks to the following developers for their patches and contributions (alphabetically):
- Steve Bragg
- Matt Flaschen
- E. Azer Koçulu
- Falco Nogatz
- jdponomarev
- Tom Offermann
- David Moises Paz Reyes
- Raminder Singh
- Stiff
- Seb Vincent
- Linmiao Xu
- Jonathan Zacsh
Musical support provided by:
BUGS
- The en passant square and castling flags aren't adjusted when using the put/remove functions (workaround: use .load() instead)
TODO
- Add AI (basic alpha-beta search w/ primitive position evaluation). The AI should probably be internal to the underlying Chess() object to take full advantage of 0x88 move generation.
- Add jQuery chessboard widget. (see widget branch for prototype)
- Investigate the use of piece lists (this may shave a few cycles off generate_moves() and attacked())