chess4js 1.0.0-beta.6 → 1.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,10 +19,10 @@ hundred milliseconds on modern machines.
19
19
 
20
20
  `Square` is a non-instantiable class representing a square on the board. It contains two main properties:
21
21
 
22
- | Property | Type | Description |
23
- |----------|--------|--------------------------------------------------------|
24
- | ordinal | number | Internal numerical representation used by the library. |
25
- | name | string | The algebraic name of the square (e.g., "A1"). |
22
+ | Property | Type | Description |
23
+ |-----------|----------|--------------------------------------------------------|
24
+ | `ordinal` | `number` | Internal numerical representation used by the library. |
25
+ | `name` | `string` | The algebraic name of the square (e.g., "A1"). |
26
26
 
27
27
  The library provides predefined instances for every square (A1, B1, ..., H8). You can import them directly:
28
28
 
@@ -34,10 +34,10 @@ import { A1, G4, D6 } from "chess4js";
34
34
 
35
35
  `Piece` is a non-instantiable class representing a chess piece.
36
36
 
37
- | Property | Type | Description |
38
- |----------|--------|--------------------------------------------------------|
39
- | ordinal | number | Internal numerical representation used by the library. |
40
- | name | string | The name of the piece. |
37
+ | Property | Type | Description |
38
+ |-----------|----------|--------------------------------------------------------|
39
+ | `ordinal` | `number` | Internal numerical representation used by the library. |
40
+ | `name` | `string` | The name of the piece. |
41
41
 
42
42
  Predefined instances are available for all pieces:
43
43
 
@@ -65,46 +65,55 @@ A non-directly instantiable class representing a 64-bit bitboard. Instances are
65
65
 
66
66
  ### Methods
67
67
 
68
- | Method | Arguments | Return Type | Description |
69
- |---------------|-----------------|-------------------------|---------------------------------------------------------------------------------------------|
70
- | peekLastBit | None | Bitboard | Returns a bitboard containing only the Least Significant Bit (LSB). |
71
- | peekFirstBit | None | Bitboard | Returns a bitboard containing only the Most Significant Bit (MSB). |
72
- | trailingZeros | None | number | Returns the number of zero bits following the LSB. |
73
- | leadingZeros | None | number | Returns the number of zero bits preceding the MSB. |
74
- | and | other: Bitboard | Bitboard | Performs a bitwise AND operation. |
75
- | or | other: Bitboard | Bitboard | Performs a bitwise OR operation. |
76
- | xor | other: Bitboard | Bitboard | Performs a bitwise XOR operation. |
77
- | inv | None | Bitboard | Performs a bitwise NOT operation (inverts all bits). |
78
- | shl | i: number | Bitboard | Returns a bitboard with bits shifted left by i positions. |
79
- | ushr | i: number | Bitboard | Returns a bitboard with bits shifted right (unsigned) by `i` positions. |
80
- | toString | none | string | Returns a formatted string representation. |
81
- | toArray | none | ReadonlyArray\<number\> | Returns an array containing the indices of all set bits (bits equal to 1) in this bitboard. |
68
+ | Method | Arguments | Return Type | Description |
69
+ |-----------------|---------------------|-------------------------|---------------------------------------------------------------------------------------------|
70
+ | `peekLastBit` | None | `Bitboard` | Returns a bitboard containing only the Least Significant Bit (LSB). |
71
+ | `peekFirstBit` | None | `Bitboard` | Returns a bitboard containing only the Most Significant Bit (MSB). |
72
+ | `trailingZeros` | None | `number` | Returns the number of zero bits following the LSB. |
73
+ | `leadingZeros` | None | `number` | Returns the number of zero bits preceding the MSB. |
74
+ | `and` | `other`: `Bitboard` | `Bitboard` | Performs a bitwise AND operation. |
75
+ | `or` | `other`: `Bitboard` | `Bitboard` | Performs a bitwise OR operation. |
76
+ | `xor` | `other`: `Bitboard` | `Bitboard` | Performs a bitwise XOR operation. |
77
+ | `inv` | None | `Bitboard` | Performs a bitwise NOT operation (inverts all bits). |
78
+ | `shl` | `i`: `number` | `Bitboard` | Returns a bitboard with bits shifted left by i positions. |
79
+ | `ushr` | `i`: `number` | `Bitboard` | Returns a bitboard with bits shifted right (unsigned) by `i` positions. |
80
+ | `toString` | none | `string` | Returns a formatted string representation. |
81
+ | `toArray` | none | `ReadonlyArray<number>` | Returns an array containing the indices of all set bits (bits equal to 1) in this bitboard. |
82
82
 
83
83
  Instances of this class can be obtained from `Position` instances.
84
84
 
85
+ ### Visible squares
86
+
87
+ The visibleSquares function accepts a piece type, a source square, and the current board position to compute the
88
+ visibility bitmask, returning the result as a Bitboard.
89
+
90
+ | Function | Arguments | Return Type | Description |
91
+ |------------------|---------------------------------------------------------------|-------------|------------------------------------------------------------------------------------------------------|
92
+ | `visibleSquares` | `piece`: `string`, `square`: `string`, `position`: `Position` | `Bitboard` | Calculates a bitboard of all squares "visible" or attacked by an specific piece from a given square. |
93
+
85
94
  ## Move
86
95
 
87
96
  A non directly instantiable class that represents a move made on the board.
88
97
 
89
98
  ### Properties
90
99
 
91
- | Property | Type | Description |
92
- |----------------|--------|-------------------------------------------------------------------------|
93
- | origin | number | The zero-based index (0-63) of the move's origin square. |
94
- | target | number | The zero-based index (0-63) of the move's target square. |
95
- | promotionPiece | number | The ordinal value of the promotion piece, or -1 if no promotion occurs. |
100
+ | Property | Type | Description |
101
+ |------------------|----------|-------------------------------------------------------------------------|
102
+ | `origin` | `number` | The zero-based index (0-63) of the move's origin square. |
103
+ | `target` | `number` | The zero-based index (0-63) of the move's target square. |
104
+ | `promotionPiece` | `number` | The ordinal value of the promotion piece, or -1 if no promotion occurs. |
96
105
 
97
106
  ### Methods
98
107
 
99
- | Method | Arguments | Return Type | Description |
100
- |----------|-----------|-------------|-----------------------------------------|
101
- | toString | None | string | Returns the UCI notation for this move. |
108
+ | Method | Arguments | Return Type | Description |
109
+ |------------|-----------|-------------|-----------------------------------------|
110
+ | `toString` | None | `string` | Returns the UCI notation for this move. |
102
111
 
103
112
  ### Factories
104
113
 
105
- | Function | Arguments | Return Type | Description |
106
- |----------|--------------|-------------|-----------------------------------------------------------------------|
107
- | moveOf | move: String | Move | Creates a `Move` object from its UCI notation string (e.g., "e7e8q"). |
114
+ | Function | Arguments | Return Type | Description |
115
+ |----------|------------------|-------------|-----------------------------------------------------------------------|
116
+ | `moveOf` | `move`: `string` | `Move` | Creates a `Move` object from its UCI notation string (e.g., "e7e8q"). |
108
117
 
109
118
  ### Example
110
119
 
@@ -129,49 +138,52 @@ const somePosition = positionOf("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w K
129
138
 
130
139
  ### Properties
131
140
 
132
- | Property | Type | Description |
133
- |----------------------|------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
134
- | bitboards | ReadonlyArray\<Bitboard\> | The index in the array is equal to the ordinal value minus one of the corresponding piece (e.g., Black Knight distribution is at index `BN.ordinal - 1`). Each Bitboard has 64 bits, where each bit represents a square in the board, following the Square ordinal order (A1 is bit 0, B1 is bit 1, up to H8 which is bit 63). A bit set to 1 indicates the presence of the piece corresponding to the array index, and 0 indicates absence. |
135
- | whiteMove | boolean | True if it is White's turn to move. False if it is Black's turn. |
136
- | enPassant | number | The square index (0-63) where a pawn can be captured en passant. Returns -1 if no en passant capture is possible. |
137
- | whiteCastleKingside | boolean | True if White can castle kingside (short castling). False otherwise. |
138
- | whiteCastleQueenside | boolean | True if White can castle queenside (long castling). False otherwise. |
139
- | blackCastleKingside | boolean | True if Black can castle kingside (short castling). False otherwise. |
140
- | blackCastleQueenside | boolean | True if Black can castle queenside (long castling). False otherwise. |
141
- | movesCounter | number | The full move number in the game (starts at 1 and is incremented after Black's move). |
142
- | halfMovesCounter | number | The number of half-moves since the last pawn move or capture. This is used for the 50-move rule. |
143
- | check | boolean | True if the current side to move is in check. False otherwise. |
144
- | checkmate | boolean | True if the position is a checkmate (the current side is in check and has no legal moves). False otherwise. |
145
- | stalemate | boolean | True if the position is a stalemate (the current side is not in check but has no legal moves). False otherwise. |
146
- | lackOfMaterial | boolean | True if the position is a draw due to insufficient mating material (e.g., King vs. King). False otherwise. |
147
- | fiftyMoves | boolean | True if the position has reached or exceeded 50 half-moves without a pawn move or capture. |
148
- | zobrist | Bitboard | The Zobrist hash key of the position. This is used for efficient position lookup and repetition detection. |
149
- | squares | Int32Array | A 64-element array where the index corresponds to the square order defined in Square (A1=0, H8=63). The value of each element is the ordinal of the Piece occupying that square (0 for EMPTY, 1 for WP, and so on). |
150
- | fen | string | The FEN (Forsyth-Edwards Notation) string representation of the position. |
151
- | children | ReadonlyArray\<Tuple\<Position, Move\>\> | A list of tuples, where each tuple represents a legal move from this position and the resulting new position (Tuple<Position, Move>). This list effectively defines the legal branches of the game tree from the current position. |
152
- | draw | boolean | True if the position is a forced draw. This is true if the position results in a stalemate or lackOfMaterial. False otherwise. |
153
- | enPassantSquare | Nullable\<Square\> | The square exposed to an en passant capture, if one exists. Returns null if no en passant capture is possible in the current position. |
154
- | gameOver | boolean | True if the game state is concluded (terminal position), either due to a forced draw or checkmate. False otherwise. |
155
- | sideToMove | Side | The side (WHITE or BLACK) whose turn it is to move. |
141
+ | Property | Type | Description |
142
+ |------------------------|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
143
+ | `bitboards` | `ReadonlyArray<Bitboard>` | The index in the array is equal to the ordinal value minus one of the corresponding piece (e.g., Black Knight distribution is at index `BN.ordinal - 1`). Each Bitboard has 64 bits, where each bit represents a square in the board, following the Square ordinal order (A1 is bit 0, B1 is bit 1, up to H8 which is bit 63). A bit set to 1 indicates the presence of the piece corresponding to the array index, and 0 indicates absence. |
144
+ | `whiteMove` | `boolean` | True if it is White's turn to move. False if it is Black's turn. |
145
+ | `enPassant` | `number` | The square index (0-63) where a pawn can be captured en passant. Returns -1 if no en passant capture is possible. |
146
+ | `whiteCastleKingside` | `boolean` | True if White can castle kingside (short castling). False otherwise. |
147
+ | `whiteCastleQueenside` | `boolean` | True if White can castle queenside (long castling). False otherwise. |
148
+ | `blackCastleKingside` | `boolean` | True if Black can castle kingside (short castling). False otherwise. |
149
+ | `blackCastleQueenside` | `boolean` | True if Black can castle queenside (long castling). False otherwise. |
150
+ | `movesCounter` | `number` | The full move number in the game (starts at 1 and is incremented after Black's move). |
151
+ | `halfMovesCounter` | `number` | The number of half-moves since the last pawn move or capture. This is used for the 50-move rule. |
152
+ | `check` | `boolean` | True if the current side to move is in check. False otherwise. |
153
+ | `checkmate` | `boolean` | True if the position is a checkmate (the current side is in check and has no legal moves). False otherwise. |
154
+ | `stalemate` | `boolean` | True if the position is a stalemate (the current side is not in check but has no legal moves). False otherwise. |
155
+ | `lackOfMaterial` | `boolean` | True if the position is a draw due to insufficient mating material (e.g., King vs. King). False otherwise. |
156
+ | `fiftyMoves` | `boolean` | True if the position has reached or exceeded 50 half-moves without a pawn move or capture. |
157
+ | `zobrist` | `Bitboard` | The Zobrist hash key of the position. This is used for efficient position lookup and repetition detection. |
158
+ | `squares` | `Int32Array` | A 64-element array where the index corresponds to the square order defined in Square (A1=0, H8=63). The value of each element is the ordinal of the Piece occupying that square (0 for EMPTY, 1 for WP, and so on). |
159
+ | `fen` | `string` | The FEN (Forsyth-Edwards Notation) string representation of the position. |
160
+ | `children` | `ReadonlyArray<Tuple<Position, Move>>` | A list of tuples, where each tuple represents a legal move from this position and the resulting new position (Tuple<Position, Move>). This list effectively defines the legal branches of the game tree from the current position. |
161
+ | `draw` | `boolean` | True if the position is a forced draw. This is true if the position results in a stalemate or lackOfMaterial. False otherwise. |
162
+ | `enPassantSquare` | `Nullable<Square>` | The square exposed to an en passant capture, if one exists. Returns null if no en passant capture is possible in the current position. |
163
+ | `gameOver` | `boolean` | True if the game state is concluded (terminal position), either due to a forced draw or checkmate. False otherwise. |
164
+ | `sideToMove` | `Side` | The side (WHITE or BLACK) whose turn it is to move. |
165
+ | `friends` | `Bitboard` | Returns a bitboard representing the occupancy of all friendly pieces. |
166
+ | `enemies` | `Bitboard` | Returns a bitboard representing the occupancy of all enemy pieces. |
156
167
 
157
168
  ### Methods
158
169
 
159
- | Method | Arguments | Return Type | Description |
160
- |----------------------|----------------------------------------|-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
161
- | whiteLacksOfMaterial | None | boolean | Determines if White has insufficient material to win the game. Returns true if the current pieces for White cannot potentially lead to a checkmate. |
162
- | blackLacksOfMaterial | None | boolean | Determines if Black has insufficient material to win the game. Returns true if the current pieces for Black cannot potentially lead to a checkmate. |
163
- | pieceAt | square: Square | Piece | Retrieves the piece object that occupies the given square. |
164
- | isLegal | move: Move | boolean | Returns true if the evaluated Move is legal in the current position, and false otherwise. |
165
- | move | move: Move | Position | Retrieves the new Position that results from executing the provided legal Move. Throws a MoveException if the provided move is not legal in the current position. |
166
- | moveFromString | move: String, notation: Notation = UCI | Position | Retrieves the new Position that results from executing the move specified in the given notation. Throws a MoveException if the move is not legal. If no notation is provided, UCI notation is assumed. |
167
- | toString | None | string | retrieves a nice string representation |
170
+ | Method | Arguments | Return Type | Description |
171
+ |------------------------|--------------------------------------------------------|-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
172
+ | `whiteLacksOfMaterial` | None | `boolean` | Determines if White has insufficient material to win the game. Returns true if the current pieces for White cannot potentially lead to a checkmate. |
173
+ | `blackLacksOfMaterial` | None | `boolean` | Determines if Black has insufficient material to win the game. Returns true if the current pieces for Black cannot potentially lead to a checkmate. |
174
+ | `pieceAt` | `square`: `Square` | `Piece` | Retrieves the piece object that occupies the given square. |
175
+ | `isLegal` | `move`: `Move` | `boolean` | Returns true if the evaluated Move is legal in the current position, and false otherwise. |
176
+ | `move` | `move`: `Move` | `Position` | Retrieves the new Position that results from executing the provided legal Move. Throws a MoveException if the provided move is not legal in the current position. |
177
+ | `moveFromString` | `move`: `String`, `notation`: `Notation` default `UCI` | `Position` | Retrieves the new Position that results from executing the move specified in the given notation. Throws a MoveException if the move is not legal. If no notation is provided, UCI notation is assumed. |
178
+ | `toString` | None | `string` | retrieves a nice string representation |
179
+ | `flipSide` | None | `Position` | Creates a new Position identical to the current one, but with the active side toggled. |
168
180
 
169
181
  ### Factories
170
182
 
171
- | Function | Arguments | Return Type | Description |
172
- |------------|-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
173
- | startpos | None | Position | Returns the standard starting `Position` (the startpos FEN). |
174
- | positionOf | fen: String | Position | Factory function to create a `Position` object from a FEN string. Throws an exception if the FEN string is invalid or leads to an illegal position. |
183
+ | Function | Arguments | Return Type | Description |
184
+ |--------------|-----------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
185
+ | `startpos` | None | `Position` | Returns the standard starting `Position` (the startpos FEN). |
186
+ | `positionOf` | `fen`: `string` | `Position` | Factory function to create a `Position` object from a FEN string. Throws an exception if the FEN string is invalid or leads to an illegal position. |
175
187
 
176
188
  ## Tuple
177
189
 
@@ -179,10 +191,10 @@ A utility class designed to group a `Position` and a `Move` together.
179
191
 
180
192
  ### Properties
181
193
 
182
- | Property | Type | Description |
183
- |----------|----------|--------------|
184
- | position | Position | The position |
185
- | move | Move | The move |
194
+ | Property | Type | Description |
195
+ |------------|------------|--------------|
196
+ | `position` | `Position` | The position |
197
+ | `move` | `Move` | The move |
186
198
 
187
199
  ## Notation
188
200
 
@@ -193,9 +205,9 @@ algebraic notation).
193
205
 
194
206
  ### Properties
195
207
 
196
- | Property | Type | Description |
197
- |----------|--------|-------------------|
198
- | name | String | The notation name |
208
+ | Property | Type | Description |
209
+ |----------|----------|-------------------|
210
+ | `name` | `string` | The notation name |
199
211
 
200
212
  ## Game and Node
201
213
 
@@ -207,71 +219,71 @@ If an instance is used to represent a documented match then its structure become
207
219
 
208
220
  For the `Game` class:
209
221
 
210
- | Property | Type | Description |
211
- |-------------------------|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
212
- | root | Node | The root node of the game tree. The setter is protected if the game is immutable. |
213
- | ecoInfo | Nullable\<EcoInfo\> | Stores the current ECO (Encyclopedia of Chess Openings) information for the main line. Setting this property will be ignored if the game is immutable (i.e., MATCH and result is set). |
214
- | id | Nullable\<any\> | A developer-provided unique identifier for serialization or tracking purposes (e.g., UUID or String). |
215
- | result | Nullable\<string\> | The final result of the game. Setting this property will update the "Result" tag in tags and set the game as immutable if MATCH is used. The values can only be set to WHITE_WIN, BLACK_WIN or DRAW. |
216
- | fiftyMoves | boolean | Indicates whether the 50-move half-move limit has been reached (non-terminal). |
217
- | finalComment | Nullable\<string\> | An optional comment placed immediately after the game's result tag in PGN. |
218
- | fiftyMovesRuleMode | string | Determines how the fifty-move rule is enforced for this game instance. The values can only be set to IGNORE, STRICT or AWARE. |
219
- | finalEndLineComment | Nullable\<string\> | An optional end-of-line comment placed immediately after the game's result tag in PGN. |
220
- | fiveRepetitions | boolean | Indicates whether a position has been repeated five times, leading to an automatic draw according to FIDE rules (terminal). |
221
- | seventyFiveMoves | boolean | Indicates whether the 75-move half-move limit has been reached, leading to an automatic draw (terminal). |
222
- | threeRepetitionsMode | string | Determines how the three-fold repetition rule is enforced for this game instance. The values can only be set to IGNORE, STRICT or AWARE. |
223
- | threeRepetitionsWarning | boolean | Indicates that a three-fold repetition draw can be claimed, as the repetition is impending (e.g., the current move will complete the third repetition). |
224
- | tags | any | A read-only object with keys as PGN tags names in lowercase (e.g., Event, Site, Date, Round, White, Black, Result). and values as PGN tags values |
222
+ | Property | Type | Description |
223
+ |---------------------------|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
224
+ | `root` | `Node` | The root node of the game tree. The setter is protected if the game is immutable. |
225
+ | `ecoInfo` | `Nullable<EcoInfo>` | Stores the current ECO (Encyclopedia of Chess Openings) information for the main line. Setting this property will be ignored if the game is immutable (i.e., MATCH and result is set). |
226
+ | `id` | `Nullable<any>` | A developer-provided unique identifier for serialization or tracking purposes (e.g., UUID or String). |
227
+ | `result` | `Nullable<string>` | The final result of the game. Setting this property will update the "Result" tag in tags and set the game as immutable if MATCH is used. The values can only be set to WHITE_WIN, BLACK_WIN or DRAW. |
228
+ | `fiftyMoves` | `boolean` | Indicates whether the 50-move half-move limit has been reached (non-terminal). |
229
+ | `finalComment` | `Nullable<string>` | An optional comment placed immediately after the game's result tag in PGN. |
230
+ | `fiftyMovesRuleMode` | `string` | Determines how the fifty-move rule is enforced for this game instance. The values can only be set to IGNORE, STRICT or AWARE. |
231
+ | `finalEndLineComment` | `Nullable<string>` | An optional end-of-line comment placed immediately after the game's result tag in PGN. |
232
+ | `fiveRepetitions` | `boolean` | Indicates whether a position has been repeated five times, leading to an automatic draw according to FIDE rules (terminal). |
233
+ | `seventyFiveMoves` | `boolean` | Indicates whether the 75-move half-move limit has been reached, leading to an automatic draw (terminal). |
234
+ | `threeRepetitionsMode` | `string` | Determines how the three-fold repetition rule is enforced for this game instance. The values can only be set to IGNORE, STRICT or AWARE. |
235
+ | `threeRepetitionsWarning` | `boolean` | Indicates that a three-fold repetition draw can be claimed, as the repetition is impending (e.g., the current move will complete the third repetition). |
236
+ | `tags` | `any` | A read-only object with keys as PGN tags names in lowercase (e.g., Event, Site, Date, Round, White, Black, Result). and values as PGN tags values |
225
237
 
226
238
  For the `Node` class:
227
239
 
228
- | Property | Type | Description |
229
- |-------------------|-------------------------------------|--------------------------------------------------------------------------------------------------------------|
230
- | position | Position | The position of the node, which is the result after executing the move. |
231
- | move | Nullable\<Move\> | The move of the node. It is null when it is the root node, which only has the starting position of the game. |
232
- | children | ReadonlyArray\<Node\> | The children of the node. The first child corresponds to the main line. The rest are variations (RAVs). |
233
- | initialComment | Nullable\<string\> | The comment that precedes the move number in PGN (e.g., "{Comment} 1. e4"). |
234
- | comment | Nullable\<string\> | The regular comment that follows the move and any suffix annotations (e.g., 1. e4 {Comment}). |
235
- | endLineComment | Nullable\<string\> | The end-of-line comment for the node, which follows a semicolon ; and goes until the end of the line. |
236
- | suffixAnnotations | Nullable\<ReadonlyArray\<number\>\> | The list of suffix annotations (NAGs) for the node. |
237
- | parent | Nullable\<Node\> | The parent node. It can only be null when it is the root node, which evidently cannot have a parent. |
240
+ | Property | Type | Description |
241
+ |---------------------|-----------------------------------|--------------------------------------------------------------------------------------------------------------|
242
+ | `position` | `Position` | The position of the node, which is the result after executing the move. |
243
+ | `move` | `Nullable<Move>` | The move of the node. It is null when it is the root node, which only has the starting position of the game. |
244
+ | `children` | `ReadonlyArray<Node>` | The children of the node. The first child corresponds to the main line. The rest are variations (RAVs). |
245
+ | `initialComment` | `Nullable<string>` | The comment that precedes the move number in PGN (e.g., "{Comment} 1. e4"). |
246
+ | `comment` | `Nullable<string>` | The regular comment that follows the move and any suffix annotations (e.g., 1. e4 {Comment}). |
247
+ | `endLineComment` | `Nullable<string>` | The end-of-line comment for the node, which follows a semicolon ; and goes until the end of the line. |
248
+ | `suffixAnnotations` | `Nullable<ReadonlyArray<number>>` | The list of suffix annotations (NAGs) for the node. |
249
+ | `parent` | `Nullable<Node>` | The parent node. It can only be null when it is the root node, which evidently cannot have a parent. |
238
250
 
239
251
  ### Methods
240
252
 
241
253
  For the `Game` class
242
254
 
243
- | Method | Arguments | Return type | Description |
244
- |---------------------|------------------------------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
245
- | setTag | name: String, value: String | undefined | Sets a tag pair (name and value). |
246
- | getTag | name: String | Nullable<String> | Retrieves the tag's value. |
247
- | toString | None | String | Returns the game in pgn format. |
248
- | toAnalysis | idSupplier?: () => Nullable\<any\> | Game | Creates a deep copy of this game, converting its mode to ANALYSIS and setting both repetition rules to AWARE. This makes the new instance fully mutable for analysis. |
249
- | deleteFromExclusive | node: Node | Node | Deletes all moves (the main line continuation and any variations) that follow the provided node. The node provided remains in the game. |
250
- | deleteFromInclusive | node: Node | Node | Deletes all moves (the main line continuation and any variations) that follow the provided node. The move represented by the node is effectively removed from the game. |
251
- | deleteBefore | node: Node | Node | Deletes all moves that preceded the provided node in the main line. The node (and its position) becomes the new effective start of the game, creating a new root Node. |
252
- | updateEco | None | undefined | Updates the instance's ECO ranking based on the last move of the main line. In match mode this is automatic, but in analysis this function must be called, otherwise the game will not be ranked. |
255
+ | Method | Arguments | Return type | Description |
256
+ |-----------------------|-----------------------------------------------|--------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
257
+ | `setTag` | `name`: `string`, `value`: `string` | `undefined` | Sets a tag pair (name and value). |
258
+ | `getTag` | `name`: `string` | `Nullable<String>` | Retrieves the tag's value. |
259
+ | `toString` | None | `string` | Returns the game in pgn format. |
260
+ | `toAnalysis` | `idSupplier`: `Nullable<() => Nullable<any>>` | `Game` | Creates a deep copy of this game, converting its mode to ANALYSIS and setting both repetition rules to AWARE. This makes the new instance fully mutable for analysis. |
261
+ | `deleteFromExclusive` | `node`: `Node` | `Node` | Deletes all moves (the main line continuation and any variations) that follow the provided node. The node provided remains in the game. |
262
+ | `deleteFromInclusive` | `node`: `Node` | `Node` | Deletes all moves (the main line continuation and any variations) that follow the provided node. The move represented by the node is effectively removed from the game. |
263
+ | `deleteBefore` | `node`: `Node` | `Node` | Deletes all moves that preceded the provided node in the main line. The node (and its position) becomes the new effective start of the game, creating a new root Node. |
264
+ | `updateEco` | None | `undefined` | Updates the instance's ECO ranking based on the last move of the main line. In match mode this is automatic, but in analysis this function must be called, otherwise the game will not be ranked. |
253
265
 
254
266
  For the `Node` class
255
267
 
256
- | Method | Arguments | Return type | Description |
257
- |-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
258
- | appendMove | move: string, initialComment?: Nullable\<string\>, comment?: Nullable\<string\>, endLineComment?: Nullable\<string\>, suffixAnnotations?: Nullable\<ReadonlyArray\<number\>\>, notation?: Notation | Node | Appends a move and returns the added node. If the node already has a child, the added move will be a variation (RAV). Returns the new node if the move is legal, or the current node if the move is illegal. |
259
- | promoteChild | index: number | boolean | Promotes the child at the given index to the primary variation (children[0]). |
260
- | promoteNode | None | boolean | Promotes this node to the main line. |
261
- | removeChild | node: Node | boolean | Removes the specified child node (variation) from the current node's list of children. |
262
- | hasChildren | None | boolean | Checks if the node has children. |
263
- | belongsToMainLine | None | boolean | Indicates whether this node belongs to the main line (i.e., it is the first child of all its ancestors). |
264
- | copy | parent: Nullable\<Node\> | Node | Creates a deep copy of this node and its entire subtree, assigning the specified parent to the new copy. This process is recursive; copying the root node copies the entire game tree. |
265
- | toSan | language: string (deafult "english"), pieces: Nullable\<Array\<String\>\> (default null) | string | Converts a move to Standard Algebraic Notation (SAN). This function acts as a convenience wrapper to generate notation adapted to different languages. If the move is null, it returns an empty string. If the specified language is not predefined, a custom array of piece initials must be provided. Supported internal languages: "english", "spanish", "dutch", "french", "german", and "italian". |
268
+ | Method | Arguments | Return type | Description |
269
+ |---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
270
+ | `appendMove` | `move`: `string`, `initialComment`: `Nullable<string>`, `comment`: `Nullable<string>`, `endLineComment`: `Nullable<string>`, `suffixAnnotations`: `Nullable<ReadonlyArray<number>>`, `notation`: `Nullable<Notation>` | `Node` | Appends a move and returns the added node. If the node already has a child, the added move will be a variation (RAV). Returns the new node if the move is legal, or the current node if the move is illegal. |
271
+ | `promoteChild` | `index`: `number` | `boolean` | Promotes the child at the given index to the primary variation (children[0]). |
272
+ | `promoteNode` | None | `boolean` | Promotes this node to the main line. |
273
+ | `removeChild` | `node`: `Node` | `boolean` | Removes the specified child node (variation) from the current node's list of children. |
274
+ | `hasChildren` | None | `boolean` | Checks if the node has children. |
275
+ | `belongsToMainLine` | None | `boolean` | Indicates whether this node belongs to the main line (i.e., it is the first child of all its ancestors). |
276
+ | `copy` | `parent`: `Nullable<Node>` | `Node` | Creates a deep copy of this node and its entire subtree, assigning the specified parent to the new copy. This process is recursive; copying the root node copies the entire game tree. |
277
+ | `toSan` | `language`: `string` default `"english"`, `pieces`: `Nullable<Array<String>>` default `null` | `string` | Converts a move to Standard Algebraic Notation (SAN). This function acts as a convenience wrapper to generate notation adapted to different languages. If the move is null, it returns an empty string. If the specified language is not predefined, a custom array of piece initials must be provided. Supported internal languages: "english", "spanish", "dutch", "french", "german", and "italian". |
266
278
 
267
279
  ### Factories and PGN parsing
268
280
 
269
- | Function | Arguments | Return type | Description |
270
- |--------------|-------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
271
- | strictMatch | idSupplier?: () => Nullable\<any\> | Game | Creates a new Game instance configured for strict competitive match play. Uses MATCH with strict enforcement for the three-fold repetition and 50-move rules. |
272
- | analysisGame | idSupplier?: () => Nullable\<any\> | Game | Creates a new Game instance configured for analysis. Uses ANALYSIS with AWARE, making the game fully mutable. |
273
- | customGame | gameMode: string, threeRepetitionsMode: string, fiftyMovesRuleMode: string, initialFen?: Nullable\<string\>, idSupplier?: () => Nullable\<any\> | Game | Creates a new Game instance with fully customizable parameters. Allows setting the game mode, rule enforcement, initial FEN, and PGN tags. |
274
- | parseGames | pgnInput: string, idSupplier?: () => Nullable\<any\> | ReadonlyArray\<Game\> | Parses a string containing one or more games in Portable Game Notation (PGN) format. Games are returned in ANALYSIS mode, making them mutable for subsequent use. |
281
+ | Function | Arguments | Return type | Description |
282
+ |----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
283
+ | `strictMatch` | `idSupplier`: `Nullable<() => Nullable<any>>` | Game | Creates a new Game instance configured for strict competitive match play. Uses MATCH with strict enforcement for the three-fold repetition and 50-move rules. |
284
+ | `analysisGame` | `idSupplier`: `Nullable<() => Nullable<any>>` | Game | Creates a new Game instance configured for analysis. Uses ANALYSIS with AWARE, making the game fully mutable. |
285
+ | `customGame` | `gameMode`: `string`, `threeRepetitionsMode`: `string`, `fiftyMovesRuleMode`: `string`, `initialFen`: `Nullable<string>`, `idSupplier`: `Nullable<() => Nullable<any>>` | Game | Creates a new Game instance with fully customizable parameters. Allows setting the game mode, rule enforcement, initial FEN, and PGN tags. |
286
+ | `parseGames` | `pgnInput`: `string`, `idSupplier`: `Nullable<() => Nullable<any>>` | ReadonlyArray\<Game\> | Parses a string containing one or more games in Portable Game Notation (PGN) format. Games are returned in ANALYSIS mode, making them mutable for subsequent use. |
275
287
 
276
288
  ### Example
277
289
 
@@ -301,8 +313,331 @@ A non-instantiable class that provides basic information about ECO classificatio
301
313
 
302
314
  ### Properties
303
315
 
304
- | Property | Type | Description |
305
- |----------|--------|------------------------------------------------------------------------------------------|
306
- | name | string | The name of the opening or variation (e.g., "Nimzo-Indian, 4.e3 O-O 5.Bd3 d5 6.Nf3 c5"). |
307
- | eco | string | The ECO code (e.g., "E57", "B40"). |
316
+ | Property | Type | Description |
317
+ |----------|----------|------------------------------------------------------------------------------------------|
318
+ | `name` | `string` | The name of the opening or variation (e.g., "Nimzo-Indian, 4.e3 O-O 5.Bd3 d5 6.Nf3 c5"). |
319
+ | `eco` | `string` | The ECO code (e.g., "E57", "B40"). |
320
+
321
+ ### Example
322
+
323
+ ```javascript
324
+ import { strictMatch } from "chess4js";
325
+
326
+ const myGame = strictMatch(() => "someId");
327
+ myGame.setTag("white", "foo")
328
+ myGame.setTag("black", "bar")
329
+ myGame.setTag("event", "foobared event")
330
+ myGame.setTag("site", "foobared place")
331
+ myGame.setTag("date", "1999.06.10")
332
+
333
+ myGame.root.appendMove("e4")
334
+ .appendMove("c5")
335
+ .appendMove("Nf3")
336
+ .appendMove("e6")
337
+ .appendMove("d4")
338
+ .appendMove("cxd4")
339
+ .appendMove("Nxd4")
340
+ .appendMove("Qb6")
341
+
342
+ const ecoInfo = myGame.ecoInfo.eco // "B40"
343
+ ```
344
+
345
+ ## Tournament Management
346
+
347
+ The library provides a suite of utilities with the purpose to handle all logic related to tournaments.
348
+
349
+ ### Score
350
+
351
+ Represents a score in a tournament. It can't be directly instantiated, you need to use a factory.
352
+
353
+ #### Methods
354
+
355
+ | Method | Arguments | Return type | Description |
356
+ |-------------|------------------|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
357
+ | `toNumber` | None | `number` | Converts the internal representation to a `number` |
358
+ | `toString` | None | `string` | Returns the human-readable string representation of the `Score`. |
359
+ | `addScore` | `other`: `Score` | `Score` | Combines this score with another and returns a new `Score` |
360
+ | `compareTo` | `other`: `Score` | `number` | Method for internal use. Compares this `Score` with the specified `Score` for order. Returns zero if this object is equal to the specified other object, a negative number if it's less than other, or a positive number if it's greater than other. |
361
+
362
+ #### Factories
363
+
364
+ | Function | Arguments | Return type | Description |
365
+ |-----------|-------------------|-------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
366
+ | `scoreOf` | `score`: `string` | `Score` | Parses a string representation of a score into a [Score]. The input must be a string ending in either ".0" (for whole points) or ".5" (for half points). |
367
+
368
+ #### Example
369
+
370
+ ```javascript
371
+ import { scoreOf } from "chess4js";
372
+
373
+ const hightScore = scoreOf("2.5");
374
+ const lowScore = scoreOf("0.0");
375
+
376
+ hightScore.compareTo(lowScore) // 1
377
+ ```
378
+
379
+ ### Player
380
+
381
+ The `Player` class represents a participant in a tournament. It can't be directly instantiated, you need to use a
382
+ factory.
383
+
384
+ #### Properties
385
+
386
+ | Property | Type | Description |
387
+ |---------------|----------------|----------------------------------------------------|
388
+ | `name` | `string` | The player's name. It's has to be unique. |
389
+ | `initialElo` | `number` | The Elo rating at the start of the tournament. |
390
+ | `currentElo` | `number` | The current elo. |
391
+ | `score` | `Score` | The score for the tournament. |
392
+ | `blackScore` | `number` | The games with black pieces counter. |
393
+ | `against` | `Set<Player>` | Set of players already faced. |
394
+ | `active` | `boolean` | Whether the player still active in the tournament. |
395
+ | `roundScores` | `Array<Score>` | Historical record of scores per round. |
396
+ | `matches` | `Array<Match>` | List of matches played by this participant. |
397
+
398
+ #### Factories
399
+
400
+ | Function | Arguments | Return type | Description |
401
+ |------------|-----------------------------------|-------------|------------------------------------------------------------------|
402
+ | `playerOf` | `name`: `string`, `elo`: `number` | `Player` | Creates a new Player instance from a given name and initial elo. |
403
+
404
+ #### Example
405
+
406
+ ```javascript
407
+ import { playerOf } from "chess4js";
408
+
409
+ const foo = playerOf("foo", 1600);
410
+ const bar = playerOf("bar", 1600);
411
+ ```
412
+
413
+ ### Match
414
+
415
+ The `Match` class represents a match between two players. It can't be directly instantiated, you need to use a
416
+ factory.
417
+
418
+ #### Properties
419
+
420
+ | Property | Type | Description |
421
+ |-----------|--------------------|------------------------------------------------------------------------------------|
422
+ | `white` | `Nullable<Player>` | The white player. |
423
+ | `black` | `Nullable<Player>` | The black player. |
424
+ | `outcome` | `string` | The outcome of the match, can be "1-0", "0-1", "1/2-1/2", "in game" or "suspended" |
425
+
426
+ #### Factories
427
+
428
+ | Function | Arguments | Return type | Description |
429
+ |-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|-------------|-------------------------------------------------------------------------------------------------------|
430
+ | `matchOf` | `white`: `Player`, `black`: `Player`, `impactFactor`: `number` default `32`, `rangeFactor`: `number` default `400`, `logisticBase`: `number` default `10` | `Match` | Creates a match between two players with the given elo calculation parameters or with default values. |
431
+
432
+ #### Example
433
+
434
+ ```javascript
435
+ import { matchOf, playerOf } from "chess4js";
436
+
437
+ const white = playerOf("foo", 1600);
438
+ const black = playerOf("bar", 1600);
439
+
440
+ const match = matchOf(white, black);
441
+ ```
442
+
443
+ ### Tournament
444
+
445
+ The `Tournament` class is the most important one in this set, as it allows us to manage and automate the tournament
446
+ management logic. It cannot be instantiated directly; instead, it must be obtained through a factory. So far, there
447
+ are two types: arena and swiss instances. Both are further detailed in the examples below.
448
+
449
+ #### Properties
450
+
451
+ | Property | Type | Description |
452
+ |-------------------|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------|
453
+ | `impactFactor` | `number` | The K-factor that determines how much a single match affects the rating. A higher value leads to faster rating changes. Default is 32.0. |
454
+ | `rangeFactor` | `number` | The scale factor used to determine win probability. Default is 400.0. |
455
+ | `logisticBase` | `number` | The base of the exponent in the logistic function. Default is 10. |
456
+ | `tiebreakers` | `Array<string>` | The strategy for breaking ties in the leaderboard. |
457
+ | `leaderboard` | `ReadonlyArray<Player>` | Current player standings, ordered by score and tie-breakers. |
458
+ | `completed` | `boolean` | Whether the tournament has reached its conclusion. |
459
+ | `activeMatches` | `ReadonlyArray<Match>` | Current matches being played. |
460
+ | `finishedMatches` | `ReadonlyArray<Match>` | All concluded matches in the tournament history. |
461
+
462
+ #### Methods
463
+
464
+ | Method | Arguments | Return Type | Description |
465
+ |----------------|--------------------|------------------------|----------------------------------------------------------------|
466
+ | `addPlayer` | `player`: `Player` | None | Adds a player to the tournament. Player's name most be unique. |
467
+ | `removePlayer` | `player`: `Player` | None | Removes a player from the tournament |
468
+ | `nextRound` | None | `ReadonlyArray<Match>` | Generates a list of new pairings. |
469
+
470
+ #### Factories
471
+
472
+ | Function | Arguments | Return Type | Description |
473
+ |--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|-------------------------------------------------------------------------------|
474
+ | `tournament` | `type`: `string`, `tiebreakers`: `Array<String>` default `["fidePerformance", "buchholz", "progressive", "sonnebornBerger"]`, `impactFactor`: `number` default `32`, `rangeFactor`: `number` default `400`, `logisticBase`: `number` default `10` | `Tournament` | Factory function to create a Tournament instance based on the specified type. |
475
+
476
+ #### Examples
477
+
478
+ *Creating a swiss tournament*
479
+
480
+ These tournaments are obtained by setting the type argument to 'swiss'. This way, the resulting instance follows the
481
+ behavior of a Swiss tournament, having a fixed number of rounds, for example. Additionally, each round must be completed
482
+ before the next one can be generated.
483
+
484
+ ```javascript
485
+ import { tournament, playerOf } from "./chess4js.mjs";
486
+
487
+ const myTournament = tournament("swiss");
488
+
489
+ function randomInt(min, max) {
490
+ return Math.floor(Math.random() * (max - min) + min);
491
+ }
492
+
493
+ function runMatch(match) {
494
+ const ratio = (match.white.currentElo - match.black.currentElo) / 100;
495
+ const random = Math.random();
496
+ if (match.white.currentElo >= match.black.currentElo) {
497
+ if (random < ratio) {
498
+ match.outcome = "1-0";
499
+ } else if (random == ratio) {
500
+ match.outcome = "1/2-1/2";
501
+ } else {
502
+ match.outcome = "0-1";
503
+ }
504
+ } else {
505
+ if (random < ratio) {
506
+ match.outcome = "0-1";
507
+ } else if (random == ratio) {
508
+ match.outcome = "1/2-1/2";
509
+ } else {
510
+ match.outcome = "1-0";
511
+ }
512
+ }
513
+ }
514
+
515
+ const minElo = 1800;
516
+ const maxElo = 2200;
517
+
518
+ const players = [
519
+ "William Smith",
520
+ "Jack Jones",
521
+ "Oliver Williams",
522
+ "Joshua Brown",
523
+ "Thomas Wilson",
524
+ "Lachlan Taylor",
525
+ "Cooper Johnson",
526
+ "Noah White",
527
+ "Ethan Martin",
528
+ "Lucas Anderson",
529
+ "James Thompson",
530
+ "Samuel Nguyen",
531
+ "Jacob Thomas",
532
+ "Liam Walker",
533
+ "Alexander Harris",
534
+ "Benjamin Lee",
535
+ ].map((name) => {
536
+ return playerOf(name, randomInt(minElo, maxElo));
537
+ });
538
+
539
+ players.forEach((player) => {
540
+ console.log(`adding player ${player.toString()}`);
541
+ myTournament.addPlayer(player);
542
+ });
543
+
544
+ while (!myTournament.completed) {
545
+ console.log("next round");
546
+ myTournament.nextRound().forEach((match) => {
547
+ runMatch(match);
548
+ console.log(`${match.toString()}`);
549
+ });
550
+ }
551
+
552
+ console.log(myTournament.leaderboard.map( e => e.toString() + ` - ${e.score.toString()}`));
553
+ ```
308
554
 
555
+ *Creating an arena tournament*
556
+
557
+ Arena-type tournaments do not actually have rounds; instead, games are generated at specific time intervals.
558
+ Regardless, new games are obtained via `nextRound()`. This type of tournament are managed using external variables,
559
+ such as elapsed time, and they do not end until the developer decides they should. The following example
560
+ is only intended to show the class's behavior when used in arena mode; it is not meant to illustrate the actual
561
+ management of an arena tournament, which is typically more complex.
562
+
563
+ ```javascript
564
+ import { tournament, playerOf } from "./chess4js.mjs";
565
+
566
+ const myTournament = tournament("arena");
567
+
568
+ function randomInt(min, max) {
569
+ return Math.floor(Math.random() * (max - min) + min);
570
+ }
571
+
572
+ function runMatch(match) {
573
+ const ratio = (match.white.currentElo - match.black.currentElo) / 100;
574
+ const random = Math.random();
575
+ if (match.white.currentElo >= match.black.currentElo) {
576
+ if (random < ratio) {
577
+ match.outcome = "1-0";
578
+ } else if (random == ratio) {
579
+ match.outcome = "1/2-1/2";
580
+ } else {
581
+ match.outcome = "0-1";
582
+ }
583
+ } else {
584
+ if (random < ratio) {
585
+ match.outcome = "0-1";
586
+ } else if (random == ratio) {
587
+ match.outcome = "1/2-1/2";
588
+ } else {
589
+ match.outcome = "1-0";
590
+ }
591
+ }
592
+ }
593
+
594
+ const minElo = 1800;
595
+ const maxElo = 2200;
596
+
597
+ const players = [
598
+ "William Smith",
599
+ "Jack Jones",
600
+ "Oliver Williams",
601
+ "Joshua Brown",
602
+ "Thomas Wilson",
603
+ "Lachlan Taylor",
604
+ "Cooper Johnson",
605
+ "Noah White",
606
+ "Ethan Martin",
607
+ "Lucas Anderson",
608
+ "James Thompson",
609
+ "Samuel Nguyen",
610
+ "Jacob Thomas",
611
+ "Liam Walker",
612
+ "Alexander Harris",
613
+ "Benjamin Lee",
614
+ ].map((name) => {
615
+ return playerOf(name, randomInt(minElo, maxElo));
616
+ });
617
+
618
+ players.forEach((player) => {
619
+ console.log(`adding player ${player.toString()}`);
620
+ myTournament.addPlayer(player);
621
+ });
622
+
623
+ const gamesLimit = 100;
624
+
625
+ let gamesQueue = [];
626
+
627
+ while((myTournament.finishedMatches.length + myTournament.activeMatches.length) < gamesLimit) {
628
+ myTournament.nextRound();
629
+ myTournament.activeMatches.forEach( (match) => gamesQueue.push(match) )
630
+ if (gamesQueue.length > 0) {
631
+ for(let i = 0; i < (gamesQueue.length / 4 * 3); i++) {
632
+ runMatch(gamesQueue.pop());
633
+ }
634
+ }
635
+ gamesQueue = [];
636
+ }
637
+
638
+ myTournament.activeMatches.forEach( (match) => runMatch(match) );
639
+
640
+ myTournament.completed = true;
641
+
642
+ console.log(myTournament.leaderboard.map( e => e.toString() + ` - ${e.score.toString()}`));
643
+ ```