chess-rule-engine 0.0.0-stage → 0.1.0

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.
Files changed (58) hide show
  1. package/README.md +170 -2
  2. package/dist/board.d.ts +22 -0
  3. package/dist/board.js +107 -0
  4. package/dist/chessRuleSet.d.ts +22 -0
  5. package/dist/chessRuleSet.js +154 -0
  6. package/dist/constants/board.d.ts +2 -0
  7. package/dist/constants/board.js +2 -0
  8. package/dist/constants/castleType.d.ts +7 -0
  9. package/dist/constants/castleType.js +8 -0
  10. package/dist/constants/game.d.ts +24 -0
  11. package/dist/constants/game.js +34 -0
  12. package/dist/constants/index.d.ts +3 -0
  13. package/dist/constants/index.js +3 -0
  14. package/dist/constants/piece.d.ts +34 -0
  15. package/dist/constants/piece.js +6 -0
  16. package/dist/game.d.ts +57 -0
  17. package/dist/game.js +314 -0
  18. package/dist/hashing/zobrist.d.ts +23 -0
  19. package/dist/hashing/zobrist.js +97 -0
  20. package/dist/hashing/zobristUpdater.d.ts +20 -0
  21. package/dist/hashing/zobristUpdater.js +105 -0
  22. package/dist/index.d.ts +6 -0
  23. package/dist/index.js +6 -0
  24. package/dist/pieces/bishop.d.ts +9 -0
  25. package/dist/pieces/bishop.js +17 -0
  26. package/dist/pieces/index.d.ts +8 -0
  27. package/dist/pieces/index.js +7 -0
  28. package/dist/pieces/king.d.ts +12 -0
  29. package/dist/pieces/king.js +90 -0
  30. package/dist/pieces/knight.d.ts +9 -0
  31. package/dist/pieces/knight.js +21 -0
  32. package/dist/pieces/pawn.d.ts +11 -0
  33. package/dist/pieces/pawn.js +90 -0
  34. package/dist/pieces/piece.d.ts +12 -0
  35. package/dist/pieces/piece.js +14 -0
  36. package/dist/pieces/queen.d.ts +9 -0
  37. package/dist/pieces/queen.js +21 -0
  38. package/dist/pieces/rook.d.ts +9 -0
  39. package/dist/pieces/rook.js +17 -0
  40. package/dist/types/board.d.ts +5 -0
  41. package/dist/types/board.js +1 -0
  42. package/dist/types/game.d.ts +38 -0
  43. package/dist/types/game.js +1 -0
  44. package/dist/types/index.d.ts +5 -0
  45. package/dist/types/index.js +5 -0
  46. package/dist/types/move.d.ts +96 -0
  47. package/dist/types/move.js +1 -0
  48. package/dist/types/piece.d.ts +23 -0
  49. package/dist/types/piece.js +1 -0
  50. package/dist/types/util.d.ts +10 -0
  51. package/dist/types/util.js +1 -0
  52. package/dist/utils/color.d.ts +4 -0
  53. package/dist/utils/color.js +7 -0
  54. package/dist/utils/piece.d.ts +6 -0
  55. package/dist/utils/piece.js +7 -0
  56. package/dist/utils/splitMix64.d.ts +6 -0
  57. package/dist/utils/splitMix64.js +15 -0
  58. package/package.json +30 -4
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # Chess Rule Engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `chess-rule-engine` is a TypeScript-first chess rules engine for applications that need reliable board state, legal move validation, special moves, game history, and game-ending condition detection.
4
+
5
+ It is designed to be the rules layer underneath a chess UI, game server, analysis tool, or AI project. The package has no UI dependencies and can be used in Node.js or other modern JavaScript environments that support ES modules.
6
+
7
+ ## Features
8
+
9
+ - Legal move validation for all standard chess pieces
10
+ - Check and checkmate detection
11
+ - Stalemate detection
12
+ - Castling and castling-right tracking
13
+ - En passant
14
+ - Pawn promotion
15
+ - Threefold-repetition tracking using Zobrist hashing
16
+ - Fifty-move-rule detection
17
+ - Insufficient-material detection
18
+ - Move history with undo, replay, and position navigation
19
+ - Strong TypeScript types included in the package
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install chess-rule-engine
25
+ ```
26
+
27
+ The package is published as an ES module and includes generated TypeScript declarations.
28
+
29
+ ## Quick start
30
+
31
+ ```ts
32
+ import { Game, GameResult, GameStatus } from "chess-rule-engine";
33
+
34
+ const game = new Game();
35
+
36
+ // Load the standard starting position.
37
+ game.setBoardLayout();
38
+
39
+ // Coordinates use x for the file and y for the rank, both from 0 to 7.
40
+ // The default board is represented from Black's back rank to White's back rank.
41
+ const result = game.playMoveWithValidation({
42
+ from: { x: 4, y: 6 }, // e2
43
+ to: { x: 4, y: 4 }, // e4
44
+ });
45
+
46
+ console.log(result);
47
+ // { result: "Legal Move", executed: true }
48
+
49
+ console.log(game.currentTurnColor); // "black"
50
+ console.log(game.currentStatus);
51
+ console.log(game.currentResult); // GameResult.PENDING
52
+ ```
53
+
54
+ Moves are only applied when they are valid, legal for the current position, and made by the side whose turn it is. The returned `MoveRemark` distinguishes invalid, illegal, and out-of-turn moves.
55
+
56
+ ## Board layouts
57
+
58
+ The engine uses an 8×8 `BoardStringLayout`. Each occupied square is represented by a two-character code:
59
+
60
+ | Code | Meaning |
61
+ | --- | --- |
62
+ | `wP`, `wN`, `wB`, `wR`, `wQ`, `wK` | White pawn, knight, bishop, rook, queen, king |
63
+ | `bP`, `bN`, `bB`, `bR`, `bQ`, `bK` | Black pawn, knight, bishop, rook, queen, king |
64
+ | `null` | Empty square |
65
+
66
+ Rows are indexed by `y` and columns by `x`. The built-in `DefaultBoard` starts with Black's back rank at row `0` and White's back rank at row `7`.
67
+
68
+ ```ts
69
+ import { Game, type BoardStringLayout } from "chess-rule-engine";
70
+
71
+ const layout: BoardStringLayout = [
72
+ ["bK", null, null, null, null, null, null, null],
73
+ [null, null, null, null, null, null, null, null],
74
+ [null, null, null, null, null, null, null, null],
75
+ [null, null, null, null, null, null, null, null],
76
+ [null, null, null, null, null, null, null, null],
77
+ [null, null, null, null, null, null, null, null],
78
+ [null, null, null, null, null, null, null, null],
79
+ ["wK", null, null, null, null, null, null, null],
80
+ ];
81
+
82
+ const game = new Game();
83
+ const loaded = game.setBoardLayout(layout);
84
+
85
+ if (!loaded) {
86
+ throw new Error("Invalid board layout");
87
+ }
88
+ ```
89
+
90
+ `setBoardLayout()` validates the dimensions and piece codes, applies the position, updates special rights, and recalculates the game state.
91
+
92
+ ## Inspecting legal moves
93
+
94
+ `ChessRuleSet` exposes position-level rule helpers. For example, use `getLegalMoves()` to list legal destinations for a piece:
95
+
96
+ ```ts
97
+ import { ChessRuleSet, Game } from "chess-rule-engine";
98
+
99
+ const game = new Game();
100
+ game.setBoardLayout();
101
+
102
+ const moves = ChessRuleSet.getLegalMoves(game, { x: 1, y: 7 }); // White knight on b1
103
+ console.log(moves);
104
+ ```
105
+
106
+ Other useful checks include:
107
+
108
+ ```ts
109
+ ChessRuleSet.isKingInCheck(game, "white");
110
+ ChessRuleSet.isCheckmated(game);
111
+ ChessRuleSet.isDrawByStalemate(game);
112
+ ChessRuleSet.isDrawByThreeFoldRepetition(game);
113
+ ChessRuleSet.isDrawByFiftyMoveRule(game);
114
+ ChessRuleSet.isDrawByInsufficientMaterial(game);
115
+ ```
116
+
117
+ ## History and replay
118
+
119
+ The `Game` class keeps move records and supports undoing or navigating through the current history:
120
+
121
+ ```ts
122
+ game.undoMove();
123
+ game.reverseOneMove();
124
+ game.forwardOneMove();
125
+ game.jumpToStartingMove();
126
+ game.jumpToLatestMove();
127
+ game.jumpToMove(2);
128
+
129
+ console.log(game.moveHistory);
130
+ console.log(game.board.getStrLayout());
131
+ ```
132
+
133
+ `moveHistory` contains structured move, capture, and promotion changes rather than chess notation. The package currently operates on coordinates and board layouts; it does not parse or generate FEN, PGN, or SAN notation.
134
+
135
+ ## Public API
136
+
137
+ The package entry point exports:
138
+
139
+ - `Game` — mutable game state, move execution, history, and status
140
+ - `Board` — board storage and layout utilities
141
+ - `ChessRuleSet` — legal-move and rule evaluation helpers
142
+ - Piece classes — `Piece`, `Pawn`, `Knight`, `Bishop`, `Rook`, `Queen`, and `King`
143
+ - Constants — `GameStatus`, `GameResult`, `CastleType`, `PieceCode`, `PieceType`, and `DefaultBoard`
144
+ - TypeScript types — positions, move queries, board layouts, move records, pieces, and game contexts
145
+
146
+ ## Development
147
+
148
+ Install dependencies and build the distributable files:
149
+
150
+ ```bash
151
+ pnpm install
152
+ pnpm run build
153
+ ```
154
+
155
+ The compiled JavaScript and declaration files are written to `dist/`. Only `dist/` is included in the published package.
156
+
157
+ ## Publishing a release
158
+
159
+ Update the version, build the package, and publish it from the project root:
160
+
161
+ ```bash
162
+ npm version patch
163
+ pnpm run build
164
+ npm publish
165
+ ```
166
+
167
+ Use `npm version minor` or `npm version major` when the release contains larger additions or breaking API changes.
168
+
169
+ ## License
170
+
171
+ ISC
@@ -0,0 +1,22 @@
1
+ import type { Position } from "./types/move.js";
2
+ import type { PiecePositionMap, BoardStringLayout } from "./types/board.js";
3
+ import { Piece, type PieceColor, type PieceName } from "./pieces/index.js";
4
+ declare class Board {
5
+ readonly boardSize: number;
6
+ readonly positionMap: PiecePositionMap;
7
+ constructor(boardSize: number);
8
+ static isSame(b1: Board, b2: Board): boolean;
9
+ copyBoard(): Board;
10
+ isValidLayout(layout: (string | null)[][]): boolean;
11
+ applyLayout(layout: BoardStringLayout): void;
12
+ clearBoard(): void;
13
+ getStrLayout(): BoardStringLayout;
14
+ setAtPos(pos: Position, piece: Piece | null): void;
15
+ getAtPos(pos: Position): Piece | null;
16
+ findPiece(color: PieceColor, name: PieceName): Position | null;
17
+ isInBounds(pos: Position): boolean;
18
+ getAllPieces(): Piece[];
19
+ }
20
+ export { Board };
21
+ export type { PiecePositionMap, BoardStringLayout } from './types/board.js';
22
+ export type { MoveChange, PromotionChange, CaptureChange, BoardChange } from './types/move.js';
package/dist/board.js ADDED
@@ -0,0 +1,107 @@
1
+ import { Bishop, King, Knight, Pawn, Queen, Rook } from "./pieces/index.js";
2
+ import { PieceCode } from "./constants/piece.js";
3
+ const pieceClassMap = { "P": Pawn, "N": Knight, "B": Bishop, "R": Rook, "Q": Queen, "K": King };
4
+ class Board {
5
+ boardSize;
6
+ positionMap;
7
+ constructor(boardSize) {
8
+ this.boardSize = boardSize;
9
+ this.positionMap = Array.from({ length: this.boardSize }, () => Array(this.boardSize).fill(null));
10
+ }
11
+ static isSame(b1, b2) {
12
+ if (b1.boardSize != b2.boardSize)
13
+ return false;
14
+ const { positionMap: map1, boardSize } = b1;
15
+ const { positionMap: map2 } = b2;
16
+ for (let y = 0; y < boardSize; ++y)
17
+ for (let x = 0; x < boardSize; ++x) {
18
+ const p1 = map1[y][x];
19
+ const p2 = map2[y][x];
20
+ if ((p1 === null && p2 !== null) || (p1 !== null && p2 === null))
21
+ return false;
22
+ if (p1 !== null && p2 !== null && (p1.color !== p2.color || p1.name !== p2.name))
23
+ return false;
24
+ }
25
+ return true;
26
+ }
27
+ copyBoard() {
28
+ const board = new Board(this.boardSize);
29
+ for (let y = 0; y < this.boardSize; ++y)
30
+ for (let x = 0; x < this.boardSize; ++x)
31
+ board.positionMap[y][x] = this.positionMap[y][x];
32
+ return board;
33
+ }
34
+ isValidLayout(layout) {
35
+ // Checking size of board
36
+ if (layout.length !== this.boardSize)
37
+ return false;
38
+ for (let row of layout) {
39
+ if (row.length !== this.boardSize)
40
+ return false;
41
+ }
42
+ // Checking if representation is correct
43
+ for (let row = 0; row < this.boardSize; ++row) {
44
+ for (let col = 0; col < this.boardSize; ++col) {
45
+ const val = layout[row][col];
46
+ if (val !== null &&
47
+ (val.length !== 2 ||
48
+ !["w", "b"].includes(val[0]) ||
49
+ !["P", "N", "B", "R", "Q", "K"].includes(val[1])))
50
+ return false;
51
+ }
52
+ }
53
+ return true;
54
+ }
55
+ applyLayout(layout) {
56
+ for (let row = 0; row < this.boardSize; ++row) {
57
+ for (let col = 0; col < this.boardSize; ++col) {
58
+ const val = layout[row][col];
59
+ this.positionMap[row][col] =
60
+ val ? new pieceClassMap[val[1]](val[0] === "w" ? "white" : "black") : null;
61
+ }
62
+ }
63
+ }
64
+ clearBoard() {
65
+ for (let row = 0; row < this.boardSize; ++row)
66
+ for (let col = 0; col < this.boardSize; ++col)
67
+ this.positionMap[row][col] = null;
68
+ }
69
+ getStrLayout() {
70
+ const boardStrLayout = Array.from({ length: this.boardSize }, () => Array(this.boardSize).fill(null));
71
+ for (let row = 0; row < this.boardSize; ++row) {
72
+ for (let col = 0; col < this.boardSize; ++col) {
73
+ const piece = this.positionMap[row][col];
74
+ if (piece)
75
+ boardStrLayout[row][col] = `${piece.color[0]}${PieceCode[piece.name]}`;
76
+ }
77
+ }
78
+ return boardStrLayout;
79
+ }
80
+ setAtPos(pos, piece) {
81
+ this.positionMap[pos.y][pos.x] = piece;
82
+ }
83
+ getAtPos(pos) {
84
+ return this.positionMap[pos.y][pos.x];
85
+ }
86
+ findPiece(color, name) {
87
+ for (let y = 0; y < this.boardSize; ++y)
88
+ for (let x = 0; x < this.boardSize; ++x)
89
+ if (this.positionMap[y][x]?.color === color && this.positionMap[y][x]?.name === name)
90
+ return { x, y };
91
+ return null;
92
+ }
93
+ isInBounds(pos) {
94
+ return (pos.x >= 0 && pos.y >= 0 && pos.x < this.boardSize && pos.y < this.boardSize);
95
+ }
96
+ getAllPieces() {
97
+ const pieces = [];
98
+ for (let y = 0; y < this.boardSize; ++y)
99
+ for (let x = 0; x < this.boardSize; ++x) {
100
+ const piece = this.positionMap[y][x];
101
+ if (piece)
102
+ pieces.push(piece);
103
+ }
104
+ return pieces;
105
+ }
106
+ }
107
+ export { Board };
@@ -0,0 +1,22 @@
1
+ import type { GameContext } from "./types/game.js";
2
+ import type { PieceColor } from "./types/piece.js";
3
+ import type { IsValidMove, LegalPosition, Position } from "./types/move.js";
4
+ declare class ChessRuleSet {
5
+ private constructor();
6
+ private static getPiecePos;
7
+ private static markAttackedSquares;
8
+ private static getAttackedSquaresByColor;
9
+ private static getPseudoLegalMoves;
10
+ static isKingInCheck(game: Pick<GameContext, "board">, color: PieceColor): boolean;
11
+ static isCheckmated(game: GameContext): boolean;
12
+ static isDrawByStalemate(game: GameContext): boolean;
13
+ static isDrawByThreeFoldRepetition(game: GameContext): boolean;
14
+ static isDrawByFiftyMoveRule(game: GameContext): boolean;
15
+ static isDrawByInsufficientMaterial(game: GameContext): boolean;
16
+ static getLegalMoves(game: GameContext, piecePos: Position): LegalPosition[];
17
+ static hasPlayerAnyLegalMove(game: GameContext): boolean;
18
+ static validateAsLegalMove(game: GameContext, from: Position, to: Position): IsValidMove;
19
+ static canSeeEachOther(game: Pick<GameContext, "board">, a: Position, b: Position): boolean;
20
+ static isPathClear(game: Pick<GameContext, "board">, start: Position, end: Position): boolean;
21
+ }
22
+ export { ChessRuleSet };
@@ -0,0 +1,154 @@
1
+ import { switchColor } from "./utils/color.js";
2
+ class ChessRuleSet {
3
+ constructor() { }
4
+ static getPiecePos(game, pieceColor, pieceName) {
5
+ const piecePos = game.board.findPiece(pieceColor, pieceName);
6
+ if (!piecePos) {
7
+ throw Error(`[Not Found] ${pieceColor} ${pieceName} is missing from board!`);
8
+ }
9
+ return piecePos;
10
+ }
11
+ static markAttackedSquares(game, piecePos, attackedSquares) {
12
+ const { board } = game;
13
+ const { boardSize, positionMap } = board;
14
+ const piece = board.getAtPos(piecePos);
15
+ if (!piece)
16
+ return;
17
+ for (const move of piece.getMoves()) {
18
+ if (!move.canAttack)
19
+ continue;
20
+ const dx = move.vec.dx;
21
+ const dy = move.vec.dy * (piece.color === "white" ? -1 : 1);
22
+ let { x: currX, y: currY } = piecePos;
23
+ do {
24
+ currX += dx;
25
+ currY += dy;
26
+ if (currX < 0 || currY < 0 || currX >= boardSize || currY >= boardSize ||
27
+ (!move.canAttack && positionMap[currY][currX]) ||
28
+ positionMap[currY][currX]?.color === piece.color) {
29
+ break;
30
+ }
31
+ attackedSquares[currY][currX] = true;
32
+ } while (move.isSliding && !positionMap[currY][currX]);
33
+ }
34
+ }
35
+ static getAttackedSquaresByColor(game, color) {
36
+ const { board } = game;
37
+ const { boardSize, positionMap } = board;
38
+ const attackedSquares = Array.from({ length: boardSize }, () => Array(boardSize).fill(false));
39
+ for (let y = 0; y < boardSize; ++y)
40
+ for (let x = 0; x < boardSize; ++x)
41
+ if (positionMap[y][x]?.color === color)
42
+ ChessRuleSet.markAttackedSquares(game, { x, y }, attackedSquares);
43
+ return attackedSquares;
44
+ }
45
+ static getPseudoLegalMoves(game, pos) {
46
+ const { board } = game;
47
+ const piece = board.getAtPos(pos);
48
+ if (!piece)
49
+ throw Error(`Invalid try to get legal moves, no piece at position (${pos.x}, ${pos.y})!`);
50
+ const pseudoLegalMoves = [];
51
+ const { boardSize, positionMap: piecePositionMap } = board;
52
+ for (const move of piece.getMoves()) {
53
+ if (move.condition && !move.condition(game, pos))
54
+ continue;
55
+ const dx = move.vec.dx;
56
+ const dy = move.vec.dy * (piece.color === "white" ? -1 : 1);
57
+ let { x: currX, y: currY } = pos;
58
+ do {
59
+ currX += dx;
60
+ currY += dy;
61
+ if (currX < 0 || currY < 0 || currX >= boardSize || currY >= boardSize ||
62
+ (!move.canAttack && piecePositionMap[currY][currX]) ||
63
+ piecePositionMap[currY][currX]?.color === piece.color) {
64
+ break;
65
+ }
66
+ pseudoLegalMoves.push({ x: currX, y: currY, onMove: move.onMove ?? undefined });
67
+ } while (move.isSliding && !piecePositionMap[currY][currX]);
68
+ }
69
+ return pseudoLegalMoves;
70
+ }
71
+ static isKingInCheck(game, color) {
72
+ const kingPos = ChessRuleSet.getPiecePos(game, color, "king");
73
+ const enemyAttackedSquares = ChessRuleSet.getAttackedSquaresByColor(game, switchColor(color));
74
+ return enemyAttackedSquares[kingPos.y][kingPos.x];
75
+ }
76
+ static isCheckmated(game) {
77
+ return ChessRuleSet.isKingInCheck(game, game.currentTurnColor) && !ChessRuleSet.hasPlayerAnyLegalMove(game);
78
+ }
79
+ static isDrawByStalemate(game) {
80
+ return !ChessRuleSet.isKingInCheck(game, game.currentTurnColor) && !ChessRuleSet.hasPlayerAnyLegalMove(game);
81
+ }
82
+ static isDrawByThreeFoldRepetition(game) {
83
+ return game.zobristUpdater.checkThreeFoldRepetition(game);
84
+ }
85
+ static isDrawByFiftyMoveRule(game) {
86
+ return game.moveHistory.length - game.lastPawnMoveOrCaptureIndex >= 100;
87
+ }
88
+ static isDrawByInsufficientMaterial(game) {
89
+ const pieces = game.board.getAllPieces();
90
+ if (pieces.length === 3) {
91
+ if (pieces.some(piece => piece.name === "bishop") || pieces.some(piece => piece.name === "knight"))
92
+ return true;
93
+ }
94
+ return pieces.length === 2;
95
+ }
96
+ static getLegalMoves(game, piecePos) {
97
+ const pseudoLegalMoves = ChessRuleSet.getPseudoLegalMoves(game, piecePos);
98
+ const { currentTurnColor } = game;
99
+ return pseudoLegalMoves.filter(move => game.evaluateAndBacktrack({ from: piecePos, to: move }, (game) => !ChessRuleSet.isKingInCheck(game, currentTurnColor)));
100
+ }
101
+ static hasPlayerAnyLegalMove(game) {
102
+ const { board, currentTurnColor: color } = game;
103
+ const { boardSize } = board;
104
+ for (let y = 0; y < boardSize; ++y)
105
+ for (let x = 0; x < boardSize; ++x)
106
+ if (board.positionMap[y][x]?.color === color && ChessRuleSet.getLegalMoves(game, { x, y }).length > 0)
107
+ return true;
108
+ return false;
109
+ }
110
+ static validateAsLegalMove(game, from, to) {
111
+ const legalMoves = ChessRuleSet.getLegalMoves(game, from);
112
+ const foundMove = legalMoves.find(move => move.x === to.x && move.y === to.y);
113
+ if (!foundMove)
114
+ return { valid: false };
115
+ return { valid: true, move: foundMove };
116
+ }
117
+ static canSeeEachOther(game, a, b) {
118
+ if (!game.board.isInBounds(a) || !game.board.isInBounds(b))
119
+ return false;
120
+ const dx = Math.abs(a.x - b.x);
121
+ const dy = Math.abs(a.y - b.y);
122
+ if (a.x != b.x && a.y != b.y && dx != dy)
123
+ return false;
124
+ const stepX = Math.sign(b.x - a.x);
125
+ const stepY = Math.sign(b.y - a.y);
126
+ let x = a.x + stepX, y = a.y + stepY;
127
+ while (x !== b.x || y !== b.y) {
128
+ if (game.board.positionMap[y][x] !== null)
129
+ return false;
130
+ x += stepX;
131
+ y += stepY;
132
+ }
133
+ return true;
134
+ }
135
+ static isPathClear(game, start, end) {
136
+ if (!game.board.isInBounds(start) || !game.board.isInBounds(end))
137
+ return false;
138
+ const dx = Math.abs(start.x - end.x);
139
+ const dy = Math.abs(start.y - end.y);
140
+ if (start.x != end.x && start.y != end.y && dx != dy)
141
+ return false;
142
+ const stepX = Math.sign(end.x - start.x);
143
+ const stepY = Math.sign(end.y - start.y);
144
+ let x = start.x, y = start.y;
145
+ while (x !== end.x || y !== end.y) {
146
+ x += stepX;
147
+ y += stepY;
148
+ if (game.board.positionMap[y][x] !== null)
149
+ return false;
150
+ }
151
+ return true;
152
+ }
153
+ }
154
+ export { ChessRuleSet };
@@ -0,0 +1,2 @@
1
+ declare const BOARD_SIZE = 8;
2
+ export { BOARD_SIZE };
@@ -0,0 +1,2 @@
1
+ const BOARD_SIZE = 8;
2
+ export { BOARD_SIZE };
@@ -0,0 +1,7 @@
1
+ declare enum CastleType {
2
+ WHITE_SHORT_CASTLE = 0,
3
+ WHITE_LONG_CASTLE = 1,
4
+ BLACK_SHORT_CASTLE = 2,
5
+ BLACK_LONG_CASTLE = 3
6
+ }
7
+ export { CastleType };
@@ -0,0 +1,8 @@
1
+ var CastleType;
2
+ (function (CastleType) {
3
+ CastleType[CastleType["WHITE_SHORT_CASTLE"] = 0] = "WHITE_SHORT_CASTLE";
4
+ CastleType[CastleType["WHITE_LONG_CASTLE"] = 1] = "WHITE_LONG_CASTLE";
5
+ CastleType[CastleType["BLACK_SHORT_CASTLE"] = 2] = "BLACK_SHORT_CASTLE";
6
+ CastleType[CastleType["BLACK_LONG_CASTLE"] = 3] = "BLACK_LONG_CASTLE";
7
+ })(CastleType || (CastleType = {}));
8
+ export { CastleType };
@@ -0,0 +1,24 @@
1
+ import type { BoardStringLayout } from "../types/board.js";
2
+ declare enum GameStatus {
3
+ NOT_STARTED = 0,
4
+ ACTIVE = 1,
5
+ WHITE_WON = 2,
6
+ BLACK_WON = 3,
7
+ DRAW = 4
8
+ }
9
+ declare enum GameResult {
10
+ PENDING = -1,
11
+ ABORT = 0,
12
+ RESIGN = 1,
13
+ CHECKMATE = 2,
14
+ TIMEOUT = 3,
15
+ ABANDONED = 4,
16
+ STALEMATE = 5,
17
+ THREE_FOLD_REPETITION = 6,
18
+ FIFTY_MOVE_RULE = 7,
19
+ DRAW_BY_AGREEMENT = 8,
20
+ DRAW_BY_INSUFFICIENT_MATERIAL = 9
21
+ }
22
+ declare const BOARD_SIZE = 8;
23
+ declare const DefaultBoard: BoardStringLayout;
24
+ export { GameStatus, GameResult, BOARD_SIZE, DefaultBoard };
@@ -0,0 +1,34 @@
1
+ var GameStatus;
2
+ (function (GameStatus) {
3
+ GameStatus[GameStatus["NOT_STARTED"] = 0] = "NOT_STARTED";
4
+ GameStatus[GameStatus["ACTIVE"] = 1] = "ACTIVE";
5
+ GameStatus[GameStatus["WHITE_WON"] = 2] = "WHITE_WON";
6
+ GameStatus[GameStatus["BLACK_WON"] = 3] = "BLACK_WON";
7
+ GameStatus[GameStatus["DRAW"] = 4] = "DRAW";
8
+ })(GameStatus || (GameStatus = {}));
9
+ var GameResult;
10
+ (function (GameResult) {
11
+ GameResult[GameResult["PENDING"] = -1] = "PENDING";
12
+ GameResult[GameResult["ABORT"] = 0] = "ABORT";
13
+ GameResult[GameResult["RESIGN"] = 1] = "RESIGN";
14
+ GameResult[GameResult["CHECKMATE"] = 2] = "CHECKMATE";
15
+ GameResult[GameResult["TIMEOUT"] = 3] = "TIMEOUT";
16
+ GameResult[GameResult["ABANDONED"] = 4] = "ABANDONED";
17
+ GameResult[GameResult["STALEMATE"] = 5] = "STALEMATE";
18
+ GameResult[GameResult["THREE_FOLD_REPETITION"] = 6] = "THREE_FOLD_REPETITION";
19
+ GameResult[GameResult["FIFTY_MOVE_RULE"] = 7] = "FIFTY_MOVE_RULE";
20
+ GameResult[GameResult["DRAW_BY_AGREEMENT"] = 8] = "DRAW_BY_AGREEMENT";
21
+ GameResult[GameResult["DRAW_BY_INSUFFICIENT_MATERIAL"] = 9] = "DRAW_BY_INSUFFICIENT_MATERIAL";
22
+ })(GameResult || (GameResult = {}));
23
+ const BOARD_SIZE = 8;
24
+ const DefaultBoard = [
25
+ ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
26
+ ["bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP"],
27
+ [null, null, null, null, null, null, null, null],
28
+ [null, null, null, null, null, null, null, null],
29
+ [null, null, null, null, null, null, null, null],
30
+ [null, null, null, null, null, null, null, null],
31
+ ["wP", "wP", "wP", "wP", "wP", "wP", "wP", "wP"],
32
+ ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"],
33
+ ];
34
+ export { GameStatus, GameResult, BOARD_SIZE, DefaultBoard };
@@ -0,0 +1,3 @@
1
+ export * from './game.js';
2
+ export * from './piece.js';
3
+ export * from './castleType.js';
@@ -0,0 +1,3 @@
1
+ export * from './game.js';
2
+ export * from './piece.js';
3
+ export * from './castleType.js';
@@ -0,0 +1,34 @@
1
+ import { Bishop, King, Knight, Pawn, Queen, Rook } from "../pieces/index.js";
2
+ declare const PieceType: {
3
+ readonly pawn: 0;
4
+ readonly knight: 1;
5
+ readonly bishop: 2;
6
+ readonly rook: 3;
7
+ readonly queen: 4;
8
+ readonly king: 5;
9
+ };
10
+ declare const PieceMaterialValue: {
11
+ readonly king: 0;
12
+ readonly pawn: 1;
13
+ readonly knight: 3;
14
+ readonly bishop: 3;
15
+ readonly rook: 5;
16
+ readonly queen: 9;
17
+ };
18
+ declare const PieceCode: {
19
+ readonly pawn: "P";
20
+ readonly knight: "N";
21
+ readonly bishop: "B";
22
+ readonly rook: "R";
23
+ readonly queen: "Q";
24
+ readonly king: "K";
25
+ };
26
+ declare const PieceClassMap: {
27
+ readonly P: typeof Pawn;
28
+ readonly B: typeof Bishop;
29
+ readonly N: typeof Knight;
30
+ readonly R: typeof Rook;
31
+ readonly Q: typeof Queen;
32
+ readonly K: typeof King;
33
+ };
34
+ export { PieceType, PieceMaterialValue, PieceCode, PieceClassMap };
@@ -0,0 +1,6 @@
1
+ import { Bishop, King, Knight, Pawn, Queen, Rook } from "../pieces/index.js";
2
+ const PieceType = { pawn: 0, knight: 1, bishop: 2, rook: 3, queen: 4, king: 5 };
3
+ const PieceMaterialValue = { king: 0, pawn: 1, knight: 3, bishop: 3, rook: 5, queen: 9 };
4
+ const PieceCode = { pawn: "P", knight: "N", bishop: "B", rook: "R", queen: "Q", king: "K" };
5
+ const PieceClassMap = { P: Pawn, B: Bishop, N: Knight, R: Rook, Q: Queen, K: King };
6
+ export { PieceType, PieceMaterialValue, PieceCode, PieceClassMap };
package/dist/game.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { Board } from "./board.js";
2
+ import { GameStatus, GameResult } from "./constants/game.js";
3
+ import { ZobristUpdater } from "./hashing/zobristUpdater.js";
4
+ import type { BoardStringLayout } from "./types/board.js";
5
+ import type { Position, MoveRecord, MoveQuery, MoveRemark, LegalPosition } from "./types/move.js";
6
+ import type { PieceColor, PieceNameCode } from "./types/piece.js";
7
+ import type { GameSpecialRights } from "./types/game.js";
8
+ type BoardChangeOptions = {
9
+ updateGameHash?: boolean;
10
+ };
11
+ type PlayMoveOptions = {
12
+ updateGameStatus?: boolean;
13
+ updateGameHash?: boolean;
14
+ };
15
+ declare class Game {
16
+ private _moveHistory;
17
+ private _currentMoveIndex;
18
+ private _currentTurnColor;
19
+ private _currentStatus;
20
+ private _currentResult;
21
+ private _zobristUpdater;
22
+ private _specialRights;
23
+ private _lastPawnMoveOrCaptureIndex;
24
+ readonly board: Board;
25
+ get lastMoveRecord(): Readonly<MoveRecord | null>;
26
+ get currentTurnColor(): PieceColor;
27
+ get currentStatus(): GameStatus;
28
+ get currentResult(): GameResult;
29
+ get lastPawnMoveOrCaptureIndex(): number;
30
+ get moveHistory(): Readonly<MoveRecord[]>;
31
+ get specialRights(): Readonly<GameSpecialRights>;
32
+ get zobristUpdater(): Readonly<ZobristUpdater>;
33
+ setBoardLayout(layout?: BoardStringLayout): boolean;
34
+ applyChanges(moveRecord: MoveRecord, { updateGameHash }?: BoardChangeOptions): void;
35
+ removeChanges(moveRecord: MoveRecord, { updateGameHash }?: BoardChangeOptions): void;
36
+ isSamePosition(board: Board, turnColor: PieceColor, specialRights: GameSpecialRights): boolean;
37
+ private evaluateStatus;
38
+ evaluateAndBacktrack<T>(moveQuery: MoveQuery<LegalPosition>, fn: (game: Game) => T): T | null;
39
+ evaluateAt<T>(moveHistoryIndexes: number[], evaluate: (game: Game) => T): T[];
40
+ updateStatus(): void;
41
+ updateSpecialRights(): void;
42
+ private changeCurrentTurn;
43
+ addMove(moveRecord: MoveRecord, moveQuery: MoveQuery<Position>): void;
44
+ addCapture(moveRecord: MoveRecord, from: Position): void;
45
+ addPromotion(moveRecord: MoveRecord, to: Position, promotionColor: PieceColor, promotionName: PieceNameCode | null): void;
46
+ private playMove;
47
+ playMoveWithValidation(moveQuery: MoveQuery<Position>): MoveRemark;
48
+ undoMove({ updateGameStatus, updateGameHash }?: PlayMoveOptions): void;
49
+ recordHashForLatestMove(): void;
50
+ removeHashForLatestMove(): void;
51
+ jumpToStartingMove(): void;
52
+ jumpToLatestMove(): void;
53
+ forwardOneMove(): void;
54
+ reverseOneMove(): void;
55
+ jumpToMove(moveHistoryIndex: number): void;
56
+ }
57
+ export { Game };