### .turn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Example of getting the current side to move.
```typescript
chess.load('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1')
chess.turn()
// -> 'b'
```
--------------------------------
### Default Starting Position
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Initializes the board to the standard starting position.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess()
// Board initialized to standard starting position
```
--------------------------------
### Install dependencies
Source: https://github.com/jhlywa/chess.js/blob/master/CONTRIBUTING.md
Install the project dependencies.
```bash
npm install
```
--------------------------------
### Installation
Source: https://github.com/jhlywa/chess.js/blob/master/README.md
Install the most recent version of chess.js from NPM.
```sh
npm install chess.js
```
--------------------------------
### Basic Usage
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
Demonstrates installation and basic usage of the chess.js library, including creating a game, playing moves, checking game state, getting legal moves, undoing moves, and exporting the game in PGN format.
```bash
npm install chess.js
```
```typescript
import { Chess } from 'chess.js'
// Create a game from the starting position
const chess = new Chess()
// Play moves
chess.move('e4') // SAN notation
chess.move({ from: 'c7', to: 'c5' }) // Coordinate notation
// Check game state
console.log(chess.isCheck()) // false
console.log(chess.isDraw()) // false
console.log(chess.isGameOver()) // false
// Get legal moves
const moves = chess.moves() // ['a3', 'a4', 'b3', ..., 'h3', 'h4']
const verboseMoves = chess.moves({ verbose: true }) // Detailed Move objects
// Undo moves
const undone = chess.undo() // Returns the Move that was undone
// Export game
const pgn = chess.pgn() // Standard PGN format
console.log(pgn)
// [White "]
// [Black "]
// ...
// 1. e4 c5 2. ...
```
--------------------------------
### clear() Options Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Clears the board, with an example showing header preservation and another showing header removal.
```typescript
const chess = new Chess()
chess.setHeader('Event', 'Tournament')
chess.clear({ preserveHeaders: true })
// Headers retained, board cleared
chess.clear() // or clear({}), clear({ preserveHeaders: false })
// Board cleared, headers also cleared (except null placeholders)
```
--------------------------------
### .squareColor() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Examples of getting the color of a chess square.
```typescript
const chess = Chess()
chess.squareColor('h1')
// -> 'light'
chess.squareColor('a7')
// -> 'dark'
chess.squareColor('bogus square')
// -> null
```
--------------------------------
### Missing FEN with SetUp Tag (Strict Mode)
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/errors.md
Demonstrates how chess.loadPgn with strict mode requires a FEN tag when SetUp is true.
```typescript
const chess = new Chess()
const pgn = `
[Event "Test"]
[SetUp "1"]
[White "?"]
[Black "?"]
1. e4 c5
`
try {
chess.loadPgn(pgn, { strict: true })
} catch (error) {
console.log(error.message)
// "Invalid PGN: FEN tag must be supplied with SetUp tag"
}
```
--------------------------------
### .setCastlingRights() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Example of setting castling rights for white, disallowing kingside castling but allowing queenside.
```typescript
// white can't castle kingside but can castle queenside
chess.setCastlingRights(WHITE, { [KING]: false, [QUEEN]: true })
```
--------------------------------
### getComments() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to get all comments and annotations in the game.
```typescript
const comments = chess.getComments()
console.log(comments)
// [
// { fen: '...', comment: 'Starting position', nags: [] },
// { fen: '...', comment: 'Best move!', nags: [1], suffixAnnotation: '!' }
// ]
```
--------------------------------
### .setHeader() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates setting header key/value pairs for PGN output.
```typescript
chess.setHeader('White', 'Robert James Fischer')
// { 'White': 'Robert James Fischer' }
chess.setHeader('Black', 'Mikhail Tal')
// { 'White': 'Robert James Fischer', 'Black': 'Mikhail Tal' }
```
--------------------------------
### load() Options Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Loads a new position while preserving existing PGN headers.
```typescript
const chess = new Chess()
chess.setHeader('White', 'Player A')
chess.setHeader('Black', 'Player B')
// Load with headers preserved
chess.load('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1', {
preserveHeaders: true
})
// Headers still exist
console.log(chess.getHeaders())
// { White: 'Player A', Black: 'Player B', ... }
```
--------------------------------
### ascii() example usage
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Example demonstrating how to use the ascii() function to get a board diagram.
```typescript
const chess = new Chess()
console.log(chess.ascii())
// Output:
// +------------------------+
// 8 | r | n | b | q | k | b | n | r |
// 7 | p | p | p | p | p | p | p | p |
// 6 | . | . | . | . | . | . | . | .
// 5 | . | . | . | . | . | . | . | .
// 4 | . | . | . | . | . | . | . | .
// 3 | . | . | . | . | . | . | . | .
// 2 | P | P | P | P | P | P | P | P |
// 1 | R | N | B | Q | K | B | N | R |
// +------------------------+
// a b c d e f g h
```
--------------------------------
### turn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Illustrates how to get the current player's turn and observe its change after a move.
```typescript
const chess = new Chess()
console.log(chess.turn()) // 'w'
chess.move('e4')
console.log(chess.turn()) // 'b'
```
--------------------------------
### moves() Options Examples
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Demonstrates various ways to filter and format move generation using the moves() method.
```typescript
const chess = new Chess()
// All moves as SAN strings (default)
const allMoves = chess.moves() // ['a3', 'a4', 'b3', ..., 'h3', 'h4']
// All moves as detailed objects
const verboseMoves = chess.moves({ verbose: true })
// Moves from specific square
const fromE2 = chess.moves({ square: 'e2' }) // ['e3', 'e4']
// Moves for specific piece type
const knightMoves = chess.moves({ piece: 'n' })
// Combined filters
const verboseKnightMoves = chess.moves({
verbose: true,
piece: 'n'
})
```
--------------------------------
### getCastlingRights() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to get and observe changes in castling rights for a given color.
```typescript
const chess = new Chess()
console.log(chess.getCastlingRights('w')) // { k: true, q: true }
chess.move('e2e4')
chess.move('e7e5')
chess.move('Ke2') // King moves, loses castling rights
console.log(chess.getCastlingRights('w')) // { k: false, q: false }
```
--------------------------------
### getSuffixAnnotation() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to get the suffix annotation at a position.
```typescript
chess.move('e4')
chess.setSuffixAnnotation('!')
console.log(chess.getSuffixAnnotation()) // '!'
```
--------------------------------
### perft() example usage
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Example demonstrating how to use the perft() function to test performance.
```typescript
const chess = new Chess()
console.log(chess.perft(1)) // 20 (initial position has 20 legal moves)
console.log(chess.perft(2)) // 400 (20 moves × 20 responses)
```
--------------------------------
### getHeaders() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to retrieve all non-null PGN headers.
```typescript
const chess = new Chess()
chess.setHeader('White', 'Kasparov')
console.log(chess.getHeaders()) // { White: 'Kasparov', ... }
```
--------------------------------
### history() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Provides an example of retrieving the move history as both SAN strings and verbose Move objects.
```typescript
const chess = new Chess()
chess.move('e4')
chess.move('c5')
chess.move('Nf3')
console.log(chess.history()) // ['e4', 'c5', 'Nf3']
console.log(chess.history({ verbose: true })[0].from) // 'e2'
```
--------------------------------
### getComment() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to get the comment at the current position.
```typescript
const chess = new Chess()
chess.move('e4')
chess.setComment('Best move!')
console.log(chess.getComment()) // 'Best move!'
```
--------------------------------
### .setTurn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates changing the side to move.
```typescript
chess.setTurn('b')
// -> true
chess.setTurn('b')
// -> false
```
--------------------------------
### loadPgn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Shows how to load a game from a PGN string and verify the loaded history.
```typescript
const chess = new Chess()
const pgn = "\n[White \"Kasparov\"]\n[Black \"Karpov\"]\n\n1. e4 c5 2. Nf3 d6\n"
chess.loadPgn(pgn)
console.log(chess.history()) // ['e4', 'c5', 'Nf3', 'd6']
```
--------------------------------
### validateFen() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Examples of using the static validateFen function to check FEN string validity.
```typescript
import { validateFen } from 'chess.js'
validateFen('2n1r3/p1k2pp1/B1p3b1/P7/5bP1/2N1B3/1P2KP2/2R5 b - - 4 25')
// -> { ok: true }
validateFen('4r3/8/X12XPk/1p6/pP2p1R1/P1B5/2P2K2/3r4 w - - 1 45')
// -> { ok: false,
// error: '1st field (piece positions) is invalid [invalid piece].' }
```
--------------------------------
### validateFen() Function Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Example of using the validateFen() utility function to validate a FEN string.
```typescript
import { validateFen } from 'chess.js'
const fen = 'invalid fen'
const result = validateFen(fen)
if (!result.ok) {
console.log(`Error: ${result.error}`)
// Use Chess constructor with skipValidation
// or provide corrected FEN
}
```
--------------------------------
### Invalid PGN Header Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/errors.md
Shows an example of an error that occurs when loading PGN with malformed headers.
```typescript
const chess = new Chess()
try {
chess.loadPgn('[Invalid Header') // Missing closing bracket
} catch (error) {
console.log(error.message)
// Parser error message
}
```
--------------------------------
### Working with Positions
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
Demonstrates how to load FEN strings, get the current FEN, reset the board, get, put, remove, and find pieces on the board.
```typescript
// Load from FEN
chess.load('r1bqkbnr/pppppppp/2n5/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1')
// Get FEN
const fen = chess.fen()
// Reset to start
chess.reset()
// Check piece on square
const piece = chess.get('e4') // { color: 'w', type: 'p' }
// Place piece
chess.put({ type: 'q', color: 'w' }, 'd4')
// Remove piece
const removed = chess.remove('d4')
// Find pieces
const queens = chess.findPiece({ type: 'q', color: 'w' })
```
--------------------------------
### move() Strict Mode Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Illustrates the difference between strict and non-strict mode when making a move, particularly with pinned pieces.
```typescript
const chess = new Chess('r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4')
// In this position, the c6 knight is pinned
// Non-strict (default) - accepts overly disambiguated move
const move1 = chess.move('Nge7', { strict: false }) // OK
// Strict mode - rejects overly disambiguated move
try {
const move2 = chess.move('Nge7', { strict: true })
// Will throw error - should be just 'Ne7'
} catch (error) {
console.error(error.message)
}
```
--------------------------------
### Import
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/README.md
Example of how to import and initialize the Chess class in TypeScript.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess()
```
--------------------------------
### setHeader() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to set a PGN header value.
```typescript
chess.setHeader('Event', 'World Championship')
chess.setHeader('Date', '2020.11.28')
```
--------------------------------
### Minimal Setup
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/imports.md
The most basic way to import and use the Chess class.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess()
chess.move('e4')
```
--------------------------------
### Example Code
Source: https://github.com/jhlywa/chess.js/blob/master/README.md
Play a random game of chess using chess.js.
```ts
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())
```
--------------------------------
### React Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/imports.md
A basic React component demonstrating the use of chess.js.
```typescript
import { useState } from 'react'
import { Chess } from 'chess.js'
export function ChessGame() {
const [chess] = useState(() => new Chess())
const [position, setPosition] = useState(chess.fen())
const handleMove = (moveStr: string) => {
try {
chess.move(moveStr)
setPosition(chess.fen())
} catch (error) {
console.error('Invalid move:', error)
}
}
return (
{chess.turn()} to move
)
}
```
--------------------------------
### nagToGlyph Example Usage
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/types.md
Example demonstrating how to use the nagToGlyph function to convert NAG numbers to symbols and display them.
```typescript
import { Chess, nagToGlyph } from 'chess.js'
const chess = new Chess()
chess.move('e4')
chess.addNag(18) // White is winning
chess.addNag(146) // Novelty
const nags = chess.getNags() // [18, 146]
// Convert to symbols
nags.forEach(nag => {
const symbol = nagToGlyph(nag)
console.log(`NAG ${nag}: ${symbol}`)
})
// Output:
// NAG 18: +−
// NAG 146: N
```
--------------------------------
### isPromotion() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Move.md
Checks if the move results in a pawn promotion.
```typescript
const chess = new Chess('4k3/P7/8/8/8/8/8/4K3 w - - 0 1')
const move = chess.move({ from: 'a7', to: 'a8', promotion: 'q' })
move.isPromotion() // true
```
--------------------------------
### PGN Viewer
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
An example demonstrating how to load PGN data and navigate through the moves using nextMove and previousMove functions.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess()
chess.loadPgn(pgnString)
let moveIndex = 0
const history = chess.history()
function nextMove() {
if (moveIndex < history.length) {
console.log(`${chess.moveNumber()}. ${history[moveIndex]}`)
moveIndex++
}
}
function previousMove() {
if (moveIndex > 0) {
chess.undo()
moveIndex--
}
}
```
--------------------------------
### FEN Validation Example Usage
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/types.md
Example demonstrating how to use the validateFen function and load a custom FEN string.
```typescript
import { Chess, validateFen, DEFAULT_POSITION } from 'chess.js'
// Validate a FEN string
const result = validateFen('invalid fen')
if (!result.ok) {
console.log(result.error) // Error message
}
// Use default position
const chess = new Chess(DEFAULT_POSITION)
// Load a custom position
const customFen = 'r1bqkbnr/pppppppp/2n5/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
chess.load(customFen)
```
--------------------------------
### Working with PGN
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
Covers loading PGN strings, adding headers, getting all headers, exporting to PGN format, and formatted PGN export.
```typescript
// Load from PGN
const pgn = `
[Event "World Championship"]
[White "Kasparov"]
[Black "Karpov"]
[Date "1985.10.09"]
[Result "1-0"]
1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 *
`
chess.loadPgn(pgn)
// Add headers
chess.setHeader('Event', 'Tournament Name')
chess.setHeader('White', 'Player A')
chess.setHeader('Black', 'Player B')
// Get all non-null headers
const headers = chess.getHeaders()
// Export to PGN
const exported = chess.pgn()
// With formatting
const formatted = chess.pgn({ maxWidth: 72, newline: '\n' })
```
--------------------------------
### Internal Use Example for xoroshiro128()
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/utilities.md
An example illustrating the internal usage of the `xoroshiro128` pseudorandom number generator, typically used for Zobrist hashing.
```typescript
// Example of how it's used internally (you typically won't need this)
import { Chess } from 'chess.js'
const chess = new Chess()
const hash = chess.hash() // Uses internal PRNG hash values
```
--------------------------------
### pgn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates exporting the current game state to PGN format, including headers and moves.
```typescript
const chess = new Chess()
chess.setHeader('White', 'Kasparov')
chess.setHeader('Black', 'Karpov')
chess.move('e4')
chess.move('c5')
console.log(chess.pgn())
// [White "Kasparov"]
// [Black "Karpov"]
//
// 1. e4 c5
```
--------------------------------
### .undo() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates taking back the last half-move and its return value.
```typescript
const chess = new Chess()
chess.fen()
// -> 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
chess.move('e4')
chess.fen()
// -> 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1'
chess.undo()
// {
// color: 'w',
// piece: 'p',
// from: 'e2',
// to: 'e4',
// san: 'e4',
// flags: 'b',
// lan: 'e2e4',
// before: 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
// after: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1'
// }
chess.fen()
// -> 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
chess.undo()
// -> null
```
--------------------------------
### setComment() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to set a comment at the current position.
```typescript
chess.move('e4')
chess.setComment('The standard opening')
```
--------------------------------
### .removeHeader() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates removing a field from the PGN header.
```typescript
chess.setHeader('White', 'Morphy')
chess.setHeader('Black', 'Anderssen')
chess.setHeader('Date', '1858-??-??')
chess.removeHeader('Date')
chess.getHeaders()
// -> { White: 'Morphy', Black: 'Anderssen'}
```
--------------------------------
### Tree-Shaking Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/imports.md
Demonstrates how bundlers can eliminate unused exports when using ES modules.
```typescript
// Only Chess and moves are bundled
import { Chess } from 'chess.js'
const chess = new Chess()
const moves = chess.moves()
```
--------------------------------
### setCastlingRights() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Shows how to set specific castling rights for a color.
```typescript
const chess = new Chess()
chess.clear()
chess.put({ type: 'k', color: 'w' }, 'e1')
chess.put({ type: 'r', color: 'w' }, 'h1')
chess.put({ type: 'k', color: 'b' }, 'e8')
chess.setCastlingRights('w', { k: true, q: true })
```
--------------------------------
### History of Moves
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates how to get a list of moves made in the game, both in standard algebraic notation (SAN) and in a verbose format including the board state before and after each move.
```typescript
const chess = new Chess()
chess.move('e4')
chess.move('e5')
chess.move('f4')
chess.move('exf4')
chess.history()
// -> ['e4', 'e5', 'f4', 'exf4']
chess.history({ verbose: true })
// -->
// [
// {
// before: 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
// after: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1',
// color: 'w',
// piece: 'p',
// from: 'e2',
// to: 'e4',
// san: 'e4',
// lan: 'e2e4',
// },
// {
// before: 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1',
// after: 'rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2',
// color: 'b',
// piece: 'p',
// from: 'e7',
// to: 'e5',
// san: 'e5',
// lan: 'e7e5',
// },
// {
// before: 'rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2',
// after: 'rnbqkbnr/pppp1ppp/8/4p3/4PP2/8/PPPP2PP/RNBQKBNR b KQkq - 0 2',
// color: 'w',
// piece: 'p',
// from: 'f2',
// to: 'f4',
// san: 'f4',
// lan: 'f2f4',
// },
// {
// before: 'rnbqkbnr/pppp1ppp/8/4p3/4PP2/8/PPPP2PP/RNBQKBNR b KQkq - 0 2',
// after: 'rnbqkbnr/pppp1ppp/8/8/4Pp2/8/PPPP2PP/RNBQKBNR w KQkq - 0 3',
// color: 'b',
// piece: 'p',
// from: 'e5',
// to: 'f4',
// san: 'exf4',
// lan: 'e5f4',
// captured: 'p'
// }
// ]
```
--------------------------------
### isCastle() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Move.md
Checks if the move is any form of castling.
```typescript
const move = chess.move('O-O')
move.isCastle() // true (combination of isKingsideCastle() || isQueensideCastle())
```
--------------------------------
### setTurn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates setting the turn to a specific color, useful for unusual game states.
```typescript
const chess = new Chess()
chess.setTurn('b') // true - makes it black's turn
```
--------------------------------
### Use Cases for nagToGlyph() - Convert PGN annotations
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/utilities.md
Example showing how to use `nagToGlyph` to convert NAGs found in PGN comments into their corresponding symbols.
```typescript
import { Chess, nagToGlyph } from 'chess.js'
const chess = new Chess()
chess.loadPgn(pgnString)
const comments = chess.getComments()
comments.forEach(entry => {
if (entry.nags && entry.nags.length > 0) {
const symbols = entry.nags
.map(nag => nagToGlyph(nag))
.filter(symbol => symbol !== undefined)
.join(' ')
console.log(`${entry.fen}: ${symbols}`)
}
})
```
--------------------------------
### isBigPawn() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Move.md
Checks if the move is a pawn's initial two-square advance.
```typescript
const chess = new Chess()
const move = chess.move('e4')
move.isBigPawn() // true
const move2 = chess.move('e5')
move2.isBigPawn() // true
```
--------------------------------
### Vue Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/imports.md
A basic Vue 3 component using Composition API with chess.js.
```typescript
```
--------------------------------
### Type-Only Imports Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/imports.md
Shows how to use TypeScript's type-only imports to prevent runtime overhead.
```typescript
import { Chess } from 'chess.js'
import type { Move, Color, Square } from 'chess.js'
// Move, Color, Square are erased at compile time
```
--------------------------------
### Initialize with Validation Best Practice
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Best practice for initializing the Chess instance with validation.
```typescript
import { Chess, validateFen } from 'chess.js'
const userFen = getUserInput()
// Validate before creating instance
const validation = validateFen(userFen)
if (!validation.ok) {
console.error(`Invalid FEN: ${validation.error}`)
return
}
const chess = new Chess(userFen)
```
--------------------------------
### moveNumber() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Shows how to retrieve the current move number, which increments after black's move.
```typescript
const chess = new Chess()
console.log(chess.moveNumber()) // 1
chess.move('e4')
console.log(chess.moveNumber()) // 1 (still white's move)
chess.move('c5')
console.log(chess.moveNumber()) // 2
```
--------------------------------
### Making Moves
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
Examples of making moves using different notations: SAN (Standard Algebraic Notation), coordinate notation, and with promotion. Also includes how to make a null move (pass).
```typescript
// SAN notation (Standard Algebraic Notation)
chess.move('e4') // Pawn to e4
chess.move('Nf3') // Knight to f3
chess.move('O-O') // Kingside castle
chess.move('O-O-O') // Queenside castle
// Coordinate notation
chess.move({ from: 'e2', to: 'e4' })
// With promotion
chess.move({ from: 'e7', to: 'e8', promotion: 'q' })
// Null move (pass)
chess.move(null)
```
--------------------------------
### Simple Game Loop
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
An example of a basic chess game loop that plays random moves until the game is over and then prints the PGN.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess()
while (!chess.isGameOver()) {
console.log(chess.ascii())
const moves = chess.moves()
const randomMove = moves[Math.floor(Math.random() * moves.length)]
console.log(`Playing ${randomMove}...`)
chess.move(randomMove)
}
console.log('Game over!')
console.log(chess.pgn())
```
--------------------------------
### Validate FEN before creating a Chess instance
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/utilities.md
Example of validating user input FEN before creating a Chess instance.
```typescript
import { Chess, validateFen } from 'chess.js';
const fen = getUserInput();
const validation = validateFen(fen);
if (!validation.ok) {
console.error(`Invalid FEN: ${validation.error}`);
return;
}
const chess = new Chess(fen);
```
--------------------------------
### Use Cases for nagToGlyph() - Display annotations with symbols
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/utilities.md
Example demonstrating how to use `nagToGlyph` to display Unicode symbols for Numeric Annotation Glyphs (NAGs) added to moves.
```typescript
import { Chess, nagToGlyph } from 'chess.js'
const chess = new Chess()
chess.move('e4')
chess.addNag(18) // White is winning
chess.addNag(146) // Novelty
const nags = chess.getNags()
nags.forEach(nag => {
const symbol = nagToGlyph(nag)
if (symbol) {
console.log(`${symbol}`)
}
})
```
--------------------------------
### Browser Usage - Via CDN
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/imports.md
Example of using chess.js via a CDN script tag in HTML.
```html
```
--------------------------------
### Use Cases for nagToGlyph() - Render move annotations
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/utilities.md
Example of a function that formats a move, including its SAN notation and any associated NAG symbols converted using `nagToGlyph`.
```typescript
import { Chess, nagToGlyph } from 'chess.js'
function formatMove(move, nags) {
let notation = move.san
// Add suffix annotation
if (move.san.endsWith('+') || move.san.endsWith('#')) {
// Don't add glyph to check/checkmate notation
} else if (move.suffixAnnotation) {
notation += move.suffixAnnotation
}
// Add NAG symbols
const symbols = nags
.map(nag => nagToGlyph(nag))
.filter(s => s !== undefined)
.join('')
return `${notation} ${symbols}`
}
```
--------------------------------
### Making a move using Standard Algebraic Notation (SAN)
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Illustrates how to make a move using Standard Algebraic Notation (SAN) and the expected return object, including a case for an invalid move.
```typescript
const chess = new Chess()
chess.move('e4')
// -> { color: 'w', from: 'e2', to: 'e4', piece: 'p', san: 'e4' }
chess.move('nf6') // SAN is case sensitive!!
// Error: Invalid move: nf6
chess.move('Nf6')
// -> { color: 'b', from: 'g8', to: 'f6', piece: 'n', san: 'Nf6' }
```
--------------------------------
### Create and Move
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/README.md
Demonstrates creating a new Chess game instance and making initial moves.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess()
chess.move('e4')
chess.move('c5')
```
--------------------------------
### Play Game and Export
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/README.md
Shows how to initialize a new game, set headers, make moves, and export the game to PGN format.
```typescript
const chess = new Chess()
chess.setHeader('White', 'Kasparov')
chess.setHeader('Black', 'Karpov')
chess.move('e4')
chess.move('c5')
chess.move('Nf3')
console.log(chess.pgn()) // Export to PGN format
```
--------------------------------
### Efficient Move Generation Best Practice
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Best practice for efficient move generation, distinguishing between checking legality and analyzing moves.
```typescript
const chess = new Chess()
// For checking if move is legal - use basic moves()
const legalMoves = chess.moves()
if (legalMoves.includes('e4')) {
chess.move('e4')
}
// For move analysis - use verbose mode
const verboseMoves = chess.moves({ verbose: true })
const captures = verboseMoves.filter(m => m.isCapture())
```
--------------------------------
### Board Representation
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/API_Overview.md
Explains how to get the full board state as a 2D array, generate an ASCII diagram of the board, and get the piece at a specific square.
```typescript
// Get full board state
const board = chess.board()
// 2D array: null for empty squares, { square, type, color } for pieces
// ASCII diagram
console.log(chess.ascii())
// Prints formatted board representation
// Get piece at square
const piece = chess.get('e4')
// Get board as 2D array
for (let rank = 0; rank < 8; rank++) {
for (let file = 0; file < 8; file++) {
console.log(board[rank][file])
}
}
```
--------------------------------
### Making a move using Object Notation
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates how to make a move by providing a move object with 'to' and 'from' properties.
```typescript
const chess = new Chess()
chess.move({ from: 'g2', to: 'g3' })
// -> { color: 'w', from: 'g2', to: 'g3', piece: 'p', san: 'g3' }
```
--------------------------------
### .removeComments() Example
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Demonstrates how to remove and retrieve all comments from all positions.
```typescript
const chess = new Chess()
chess.loadPgn(
"1. e4 e5 {king's pawn opening} 2. Nf3 Nc6 3. Bc4 Bc5 {giuoco piano} *",
)
chess.removeComments()
// -> [
// {
// fen: "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2",
// comment: "king's pawn opening"
// },
// {
// fen: "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3",
// comment: "giuoco piano"
// }
// ]
chess.getComments()
// -> []
```
--------------------------------
### Stalemate Detection
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Example of how to check if the current side to move is in stalemate.
```typescript
const chess = new Chess('4k3/4P3/4K3/8/8/8/8/8 b - - 0 78')
chess.isStalemate()
// -> true
```
--------------------------------
### Custom FEN Position
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Initializes the board to a specified FEN position.
```typescript
import { Chess } from 'chess.js'
const chess = new Chess('r1bqkbnr/pppppppp/2n5/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 1 2')
// Board initialized to specified position
```
--------------------------------
### Checkmate Detection
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Example of how to determine if the current side to move is in checkmate.
```typescript
const chess = new Chess(
'rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3',
)
chess.isCheckmate()
// -> true
```
--------------------------------
### Clone your fork
Source: https://github.com/jhlywa/chess.js/blob/master/CONTRIBUTING.md
Clone your forked repository locally.
```bash
git clone https://github.com//chess.js.git
```
--------------------------------
### Check Detection
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Example of how to check if the current side to move is in check.
```typescript
const chess = new Chess(
'rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3',
)
chess.inCheck()
// -> true
```
--------------------------------
### Use Cases for nagToGlyph() - Handle unknown NAGs gracefully
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/utilities.md
Example demonstrating how to use `nagToGlyph` and provide a fallback for unknown NAG codes, displaying them in the PGN format `$nag`.
```typescript
import { nagToGlyph } from 'chess.js'
function displayNag(nag) {
const symbol = nagToGlyph(nag)
if (symbol) {
return symbol
} else {
// Fallback for unknown NAGs
return `$${nag}` // PGN format for unknown NAGs
}
}
console.log(displayNag(18)) // '+−'
console.log(displayNag(9999)) // '$9999'
```
--------------------------------
### Loading a PGN string
Source: https://github.com/jhlywa/chess.js/blob/master/website/versioned_docs/version-v1.4.0/index.md
Shows how to load a game from a Portable Game Notation (PGN) string, including handling different newline characters and strict parsing.
```typescript
const chess = new Chess()
const pgn = [
'[Event "Casual Game"]',
'[Site "Berlin GER"]',
'[Date "1852 11 11"]',
'[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()
// -> ' +------------------------+
// 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'
// Parse non-standard move formats and unusual line separators
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', // non-standard
'2. Nc3 Nf6',
'3. Nf3 Nc6',
'4. g2g3 Bb4', // non-standard
'5. Nd5 Nxd5',
'6. c4xd5 e5-e4', // non-standard
'7. dxc6 exf3',
'8. Qb3 1-0',
].join(':')
chess.loadPgn(sloppyPgn, { newlineChar: ':' })
// works by default
chess.loadPgn(sloppyPgn, { newlineChar: ':', strict: true })
// Error: Invalid move in PGN: Pc2c4
```
--------------------------------
### removeComment() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Demonstrates how to remove the comment at the current position.
```typescript
const removed = chess.removeComment()
```
--------------------------------
### isNullMove() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Move.md
Checks if the move is a null move (pass).
```typescript
const chess = new Chess()
chess.move(null) // Pass the turn
const move = chess.history({ verbose: true })[0]
move.isNullMove() // true
```
--------------------------------
### isKingsideCastle() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Move.md
Checks if the move is kingside castling (O-O).
```typescript
const chess = new Chess('r1bqk1nr/ppppppbp/2n5/8/8/3P1N2/PPP1PPPP/RNBQKB1R w KQkq - 0 1')
// After moving knight and preparing kingside castle
chess.move('O-O') // White kingside castles
const move = chess.history({ verbose: true }).pop()
move.isKingsideCastle() // true
```
--------------------------------
### loadPgn() Options
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
Options for the loadPgn() function, including strict parsing and custom newline characters.
```typescript
loadPgn(pgn: string, options?: {
strict?: boolean
newlineChar?: string
}): void
```
```typescript
const chess = new Chess()
// Non-strict parsing (permissive)
const pgn1 = "\
[Event \"Test\"]\n[fen \"8/8/8/4k3/8/8/4K3/8 w - - 0 1\"] // lowercase fen tag\n[Result \"*\"]\n\n1. Ke2 Ke4\n"
chess.loadPgn(pgn1) // Works - auto-loads FEN
console.log(chess.history()) // ['Ke2', 'Ke4']
// Strict parsing (spec-compliant)
const pgn2 = "\
[Event \"Test\"]\n[SetUp \"1\"]\n[FEN \"8/8/8/4k3/8/8/4K3/8 w - - 0 1\"]\n[Result \"*\"]\n\n1. Ke2 Ke4\n"
chess.loadPgn(pgn2, { strict: true }) // Works - proper setup
// Custom line breaks
const pgnWithCustomNewlines = "\
[Event \"Test\"]|\n[Site \"?\"]|\n|\n1. e4 c5\n".replace(/\|/g, '\n')
chess.loadPgn(pgnWithCustomNewlines, { newlineChar: '\n' })
```
--------------------------------
### Chess Constructor
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/configuration.md
The Chess class accepts an optional FEN string and an options object.
```typescript
constructor(fen?: string, options?: { skipValidation?: boolean })
```
--------------------------------
### isEnPassant() Example
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Move.md
Checks if the move is an en passant capture.
```typescript
const chess = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1')
chess.move('d5')
const move = chess.move('exd5')
move.isEnPassant() // true
```
--------------------------------
### reset()
Source: https://github.com/jhlywa/chess.js/blob/master/_autodocs/Chess.md
Resets the board to the starting position and clears all game metadata.
```typescript
const chess = new Chess()
chess.move('e2e4')
chess.reset() // Back to starting position
```