@alepot55/chessboardjs 2.0.4 → 2.1.5
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/chessboard.bundle.js +3305 -0
- package/chessboard.config.js +1 -1
- package/dist/website/home/bundle.js +3303 -0
- package/package.json +4 -2
- package/rollup.config.js +11 -0
|
@@ -0,0 +1,3305 @@
|
|
|
1
|
+
var Chessboard = (function () {
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright (c) 2025, Jeff Hlywa (jhlywa@gmail.com)
|
|
7
|
+
* All rights reserved.
|
|
8
|
+
*
|
|
9
|
+
* Redistribution and use in source and binary forms, with or without
|
|
10
|
+
* modification, are permitted provided that the following conditions are met:
|
|
11
|
+
*
|
|
12
|
+
* 1. Redistributions of source code must retain the above copyright notice,
|
|
13
|
+
* this list of conditions and the following disclaimer.
|
|
14
|
+
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
15
|
+
* this list of conditions and the following disclaimer in the documentation
|
|
16
|
+
* and/or other materials provided with the distribution.
|
|
17
|
+
*
|
|
18
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
19
|
+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
20
|
+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
21
|
+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
22
|
+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
23
|
+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
24
|
+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
25
|
+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
26
|
+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
27
|
+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
28
|
+
* POSSIBILITY OF SUCH DAMAGE.
|
|
29
|
+
*/
|
|
30
|
+
const WHITE = 'w';
|
|
31
|
+
const BLACK = 'b';
|
|
32
|
+
const PAWN = 'p';
|
|
33
|
+
const KNIGHT = 'n';
|
|
34
|
+
const BISHOP = 'b';
|
|
35
|
+
const ROOK = 'r';
|
|
36
|
+
const QUEEN = 'q';
|
|
37
|
+
const KING = 'k';
|
|
38
|
+
const DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
|
|
39
|
+
let Move$1 = class Move {
|
|
40
|
+
color;
|
|
41
|
+
from;
|
|
42
|
+
to;
|
|
43
|
+
piece;
|
|
44
|
+
captured;
|
|
45
|
+
promotion;
|
|
46
|
+
/**
|
|
47
|
+
* @deprecated This field is deprecated and will be removed in version 2.0.0.
|
|
48
|
+
* Please use move descriptor functions instead: `isCapture`, `isPromotion`,
|
|
49
|
+
* `isEnPassant`, `isKingsideCastle`, `isQueensideCastle`, `isCastle`, and
|
|
50
|
+
* `isBigPawn`
|
|
51
|
+
*/
|
|
52
|
+
flags;
|
|
53
|
+
san;
|
|
54
|
+
lan;
|
|
55
|
+
before;
|
|
56
|
+
after;
|
|
57
|
+
constructor(chess, internal) {
|
|
58
|
+
const { color, piece, from, to, flags, captured, promotion } = internal;
|
|
59
|
+
const fromAlgebraic = algebraic(from);
|
|
60
|
+
const toAlgebraic = algebraic(to);
|
|
61
|
+
this.color = color;
|
|
62
|
+
this.piece = piece;
|
|
63
|
+
this.from = fromAlgebraic;
|
|
64
|
+
this.to = toAlgebraic;
|
|
65
|
+
/*
|
|
66
|
+
* HACK: The chess['_method']() calls below invoke private methods in the
|
|
67
|
+
* Chess class to generate SAN and FEN. It's a bit of a hack, but makes the
|
|
68
|
+
* code cleaner elsewhere.
|
|
69
|
+
*/
|
|
70
|
+
this.san = chess['_moveToSan'](internal, chess['_moves']({ legal: true }));
|
|
71
|
+
this.lan = fromAlgebraic + toAlgebraic;
|
|
72
|
+
this.before = chess.fen();
|
|
73
|
+
// Generate the FEN for the 'after' key
|
|
74
|
+
chess['_makeMove'](internal);
|
|
75
|
+
this.after = chess.fen();
|
|
76
|
+
chess['_undoMove']();
|
|
77
|
+
// Build the text representation of the move flags
|
|
78
|
+
this.flags = '';
|
|
79
|
+
for (const flag in BITS) {
|
|
80
|
+
if (BITS[flag] & flags) {
|
|
81
|
+
this.flags += FLAGS[flag];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (captured) {
|
|
85
|
+
this.captured = captured;
|
|
86
|
+
}
|
|
87
|
+
if (promotion) {
|
|
88
|
+
this.promotion = promotion;
|
|
89
|
+
this.lan += promotion;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
isCapture() {
|
|
93
|
+
return this.flags.indexOf(FLAGS['CAPTURE']) > -1;
|
|
94
|
+
}
|
|
95
|
+
isPromotion() {
|
|
96
|
+
return this.flags.indexOf(FLAGS['PROMOTION']) > -1;
|
|
97
|
+
}
|
|
98
|
+
isEnPassant() {
|
|
99
|
+
return this.flags.indexOf(FLAGS['EP_CAPTURE']) > -1;
|
|
100
|
+
}
|
|
101
|
+
isKingsideCastle() {
|
|
102
|
+
return this.flags.indexOf(FLAGS['KSIDE_CASTLE']) > -1;
|
|
103
|
+
}
|
|
104
|
+
isQueensideCastle() {
|
|
105
|
+
return this.flags.indexOf(FLAGS['QSIDE_CASTLE']) > -1;
|
|
106
|
+
}
|
|
107
|
+
isBigPawn() {
|
|
108
|
+
return this.flags.indexOf(FLAGS['BIG_PAWN']) > -1;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
const EMPTY = -1;
|
|
112
|
+
const FLAGS = {
|
|
113
|
+
NORMAL: 'n',
|
|
114
|
+
CAPTURE: 'c',
|
|
115
|
+
BIG_PAWN: 'b',
|
|
116
|
+
EP_CAPTURE: 'e',
|
|
117
|
+
PROMOTION: 'p',
|
|
118
|
+
KSIDE_CASTLE: 'k',
|
|
119
|
+
QSIDE_CASTLE: 'q',
|
|
120
|
+
};
|
|
121
|
+
const BITS = {
|
|
122
|
+
NORMAL: 1,
|
|
123
|
+
CAPTURE: 2,
|
|
124
|
+
BIG_PAWN: 4,
|
|
125
|
+
EP_CAPTURE: 8,
|
|
126
|
+
PROMOTION: 16,
|
|
127
|
+
KSIDE_CASTLE: 32,
|
|
128
|
+
QSIDE_CASTLE: 64,
|
|
129
|
+
};
|
|
130
|
+
/*
|
|
131
|
+
* NOTES ABOUT 0x88 MOVE GENERATION ALGORITHM
|
|
132
|
+
* ----------------------------------------------------------------------------
|
|
133
|
+
* From https://github.com/jhlywa/chess.js/issues/230
|
|
134
|
+
*
|
|
135
|
+
* A lot of people are confused when they first see the internal representation
|
|
136
|
+
* of chess.js. It uses the 0x88 Move Generation Algorithm which internally
|
|
137
|
+
* stores the board as an 8x16 array. This is purely for efficiency but has a
|
|
138
|
+
* couple of interesting benefits:
|
|
139
|
+
*
|
|
140
|
+
* 1. 0x88 offers a very inexpensive "off the board" check. Bitwise AND (&) any
|
|
141
|
+
* square with 0x88, if the result is non-zero then the square is off the
|
|
142
|
+
* board. For example, assuming a knight square A8 (0 in 0x88 notation),
|
|
143
|
+
* there are 8 possible directions in which the knight can move. These
|
|
144
|
+
* directions are relative to the 8x16 board and are stored in the
|
|
145
|
+
* PIECE_OFFSETS map. One possible move is A8 - 18 (up one square, and two
|
|
146
|
+
* squares to the left - which is off the board). 0 - 18 = -18 & 0x88 = 0x88
|
|
147
|
+
* (because of two-complement representation of -18). The non-zero result
|
|
148
|
+
* means the square is off the board and the move is illegal. Take the
|
|
149
|
+
* opposite move (from A8 to C7), 0 + 18 = 18 & 0x88 = 0. A result of zero
|
|
150
|
+
* means the square is on the board.
|
|
151
|
+
*
|
|
152
|
+
* 2. The relative distance (or difference) between two squares on a 8x16 board
|
|
153
|
+
* is unique and can be used to inexpensively determine if a piece on a
|
|
154
|
+
* square can attack any other arbitrary square. For example, let's see if a
|
|
155
|
+
* pawn on E7 can attack E2. The difference between E7 (20) - E2 (100) is
|
|
156
|
+
* -80. We add 119 to make the ATTACKS array index non-negative (because the
|
|
157
|
+
* worst case difference is A8 - H1 = -119). The ATTACKS array contains a
|
|
158
|
+
* bitmask of pieces that can attack from that distance and direction.
|
|
159
|
+
* ATTACKS[-80 + 119=39] gives us 24 or 0b11000 in binary. Look at the
|
|
160
|
+
* PIECE_MASKS map to determine the mask for a given piece type. In our pawn
|
|
161
|
+
* example, we would check to see if 24 & 0x1 is non-zero, which it is
|
|
162
|
+
* not. So, naturally, a pawn on E7 can't attack a piece on E2. However, a
|
|
163
|
+
* rook can since 24 & 0x8 is non-zero. The only thing left to check is that
|
|
164
|
+
* there are no blocking pieces between E7 and E2. That's where the RAYS
|
|
165
|
+
* array comes in. It provides an offset (in this case 16) to add to E7 (20)
|
|
166
|
+
* to check for blocking pieces. E7 (20) + 16 = E6 (36) + 16 = E5 (52) etc.
|
|
167
|
+
*/
|
|
168
|
+
// prettier-ignore
|
|
169
|
+
// eslint-disable-next-line
|
|
170
|
+
const Ox88 = {
|
|
171
|
+
a8: 0, b8: 1, c8: 2, d8: 3, e8: 4, f8: 5, g8: 6, h8: 7,
|
|
172
|
+
a7: 16, b7: 17, c7: 18, d7: 19, e7: 20, f7: 21, g7: 22, h7: 23,
|
|
173
|
+
a6: 32, b6: 33, c6: 34, d6: 35, e6: 36, f6: 37, g6: 38, h6: 39,
|
|
174
|
+
a5: 48, b5: 49, c5: 50, d5: 51, e5: 52, f5: 53, g5: 54, h5: 55,
|
|
175
|
+
a4: 64, b4: 65, c4: 66, d4: 67, e4: 68, f4: 69, g4: 70, h4: 71,
|
|
176
|
+
a3: 80, b3: 81, c3: 82, d3: 83, e3: 84, f3: 85, g3: 86, h3: 87,
|
|
177
|
+
a2: 96, b2: 97, c2: 98, d2: 99, e2: 100, f2: 101, g2: 102, h2: 103,
|
|
178
|
+
a1: 112, b1: 113, c1: 114, d1: 115, e1: 116, f1: 117, g1: 118, h1: 119
|
|
179
|
+
};
|
|
180
|
+
const PAWN_OFFSETS = {
|
|
181
|
+
b: [16, 32, 17, 15],
|
|
182
|
+
w: [-16, -32, -17, -15],
|
|
183
|
+
};
|
|
184
|
+
const PIECE_OFFSETS = {
|
|
185
|
+
n: [-18, -33, -31, -14, 18, 33, 31, 14],
|
|
186
|
+
b: [-17, -15, 17, 15],
|
|
187
|
+
r: [-16, 1, 16, -1],
|
|
188
|
+
q: [-17, -16, -15, 1, 17, 16, 15, -1],
|
|
189
|
+
k: [-17, -16, -15, 1, 17, 16, 15, -1],
|
|
190
|
+
};
|
|
191
|
+
// prettier-ignore
|
|
192
|
+
const ATTACKS = [
|
|
193
|
+
20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 20, 0,
|
|
194
|
+
0, 20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 20, 0, 0,
|
|
195
|
+
0, 0, 20, 0, 0, 0, 0, 24, 0, 0, 0, 0, 20, 0, 0, 0,
|
|
196
|
+
0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 20, 0, 0, 0, 0,
|
|
197
|
+
0, 0, 0, 0, 20, 0, 0, 24, 0, 0, 20, 0, 0, 0, 0, 0,
|
|
198
|
+
0, 0, 0, 0, 0, 20, 2, 24, 2, 20, 0, 0, 0, 0, 0, 0,
|
|
199
|
+
0, 0, 0, 0, 0, 2, 53, 56, 53, 2, 0, 0, 0, 0, 0, 0,
|
|
200
|
+
24, 24, 24, 24, 24, 24, 56, 0, 56, 24, 24, 24, 24, 24, 24, 0,
|
|
201
|
+
0, 0, 0, 0, 0, 2, 53, 56, 53, 2, 0, 0, 0, 0, 0, 0,
|
|
202
|
+
0, 0, 0, 0, 0, 20, 2, 24, 2, 20, 0, 0, 0, 0, 0, 0,
|
|
203
|
+
0, 0, 0, 0, 20, 0, 0, 24, 0, 0, 20, 0, 0, 0, 0, 0,
|
|
204
|
+
0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 20, 0, 0, 0, 0,
|
|
205
|
+
0, 0, 20, 0, 0, 0, 0, 24, 0, 0, 0, 0, 20, 0, 0, 0,
|
|
206
|
+
0, 20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 20, 0, 0,
|
|
207
|
+
20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 20
|
|
208
|
+
];
|
|
209
|
+
// prettier-ignore
|
|
210
|
+
const RAYS = [
|
|
211
|
+
17, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 15, 0,
|
|
212
|
+
0, 17, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 0,
|
|
213
|
+
0, 0, 17, 0, 0, 0, 0, 16, 0, 0, 0, 0, 15, 0, 0, 0,
|
|
214
|
+
0, 0, 0, 17, 0, 0, 0, 16, 0, 0, 0, 15, 0, 0, 0, 0,
|
|
215
|
+
0, 0, 0, 0, 17, 0, 0, 16, 0, 0, 15, 0, 0, 0, 0, 0,
|
|
216
|
+
0, 0, 0, 0, 0, 17, 0, 16, 0, 15, 0, 0, 0, 0, 0, 0,
|
|
217
|
+
0, 0, 0, 0, 0, 0, 17, 16, 15, 0, 0, 0, 0, 0, 0, 0,
|
|
218
|
+
1, 1, 1, 1, 1, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, 0,
|
|
219
|
+
0, 0, 0, 0, 0, 0, -15, -16, -17, 0, 0, 0, 0, 0, 0, 0,
|
|
220
|
+
0, 0, 0, 0, 0, -15, 0, -16, 0, -17, 0, 0, 0, 0, 0, 0,
|
|
221
|
+
0, 0, 0, 0, -15, 0, 0, -16, 0, 0, -17, 0, 0, 0, 0, 0,
|
|
222
|
+
0, 0, 0, -15, 0, 0, 0, -16, 0, 0, 0, -17, 0, 0, 0, 0,
|
|
223
|
+
0, 0, -15, 0, 0, 0, 0, -16, 0, 0, 0, 0, -17, 0, 0, 0,
|
|
224
|
+
0, -15, 0, 0, 0, 0, 0, -16, 0, 0, 0, 0, 0, -17, 0, 0,
|
|
225
|
+
-15, 0, 0, 0, 0, 0, 0, -16, 0, 0, 0, 0, 0, 0, -17
|
|
226
|
+
];
|
|
227
|
+
const PIECE_MASKS = { p: 0x1, n: 0x2, b: 0x4, r: 0x8, q: 0x10, k: 0x20 };
|
|
228
|
+
const SYMBOLS = 'pnbrqkPNBRQK';
|
|
229
|
+
const PROMOTIONS = [KNIGHT, BISHOP, ROOK, QUEEN];
|
|
230
|
+
const RANK_1 = 7;
|
|
231
|
+
const RANK_2 = 6;
|
|
232
|
+
/*
|
|
233
|
+
* const RANK_3 = 5
|
|
234
|
+
* const RANK_4 = 4
|
|
235
|
+
* const RANK_5 = 3
|
|
236
|
+
* const RANK_6 = 2
|
|
237
|
+
*/
|
|
238
|
+
const RANK_7 = 1;
|
|
239
|
+
const RANK_8 = 0;
|
|
240
|
+
const SIDES = {
|
|
241
|
+
[KING]: BITS.KSIDE_CASTLE,
|
|
242
|
+
[QUEEN]: BITS.QSIDE_CASTLE,
|
|
243
|
+
};
|
|
244
|
+
const ROOKS = {
|
|
245
|
+
w: [
|
|
246
|
+
{ square: Ox88.a1, flag: BITS.QSIDE_CASTLE },
|
|
247
|
+
{ square: Ox88.h1, flag: BITS.KSIDE_CASTLE },
|
|
248
|
+
],
|
|
249
|
+
b: [
|
|
250
|
+
{ square: Ox88.a8, flag: BITS.QSIDE_CASTLE },
|
|
251
|
+
{ square: Ox88.h8, flag: BITS.KSIDE_CASTLE },
|
|
252
|
+
],
|
|
253
|
+
};
|
|
254
|
+
const SECOND_RANK = { b: RANK_7, w: RANK_2 };
|
|
255
|
+
const TERMINATION_MARKERS = ['1-0', '0-1', '1/2-1/2', '*'];
|
|
256
|
+
// Extracts the zero-based rank of an 0x88 square.
|
|
257
|
+
function rank(square) {
|
|
258
|
+
return square >> 4;
|
|
259
|
+
}
|
|
260
|
+
// Extracts the zero-based file of an 0x88 square.
|
|
261
|
+
function file(square) {
|
|
262
|
+
return square & 0xf;
|
|
263
|
+
}
|
|
264
|
+
function isDigit(c) {
|
|
265
|
+
return '0123456789'.indexOf(c) !== -1;
|
|
266
|
+
}
|
|
267
|
+
// Converts a 0x88 square to algebraic notation.
|
|
268
|
+
function algebraic(square) {
|
|
269
|
+
const f = file(square);
|
|
270
|
+
const r = rank(square);
|
|
271
|
+
return ('abcdefgh'.substring(f, f + 1) +
|
|
272
|
+
'87654321'.substring(r, r + 1));
|
|
273
|
+
}
|
|
274
|
+
function swapColor(color) {
|
|
275
|
+
return color === WHITE ? BLACK : WHITE;
|
|
276
|
+
}
|
|
277
|
+
function validateFen(fen) {
|
|
278
|
+
// 1st criterion: 6 space-seperated fields?
|
|
279
|
+
const tokens = fen.split(/\s+/);
|
|
280
|
+
if (tokens.length !== 6) {
|
|
281
|
+
return {
|
|
282
|
+
ok: false,
|
|
283
|
+
error: 'Invalid FEN: must contain six space-delimited fields',
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
// 2nd criterion: move number field is a integer value > 0?
|
|
287
|
+
const moveNumber = parseInt(tokens[5], 10);
|
|
288
|
+
if (isNaN(moveNumber) || moveNumber <= 0) {
|
|
289
|
+
return {
|
|
290
|
+
ok: false,
|
|
291
|
+
error: 'Invalid FEN: move number must be a positive integer',
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
// 3rd criterion: half move counter is an integer >= 0?
|
|
295
|
+
const halfMoves = parseInt(tokens[4], 10);
|
|
296
|
+
if (isNaN(halfMoves) || halfMoves < 0) {
|
|
297
|
+
return {
|
|
298
|
+
ok: false,
|
|
299
|
+
error: 'Invalid FEN: half move counter number must be a non-negative integer',
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
// 4th criterion: 4th field is a valid e.p.-string?
|
|
303
|
+
if (!/^(-|[abcdefgh][36])$/.test(tokens[3])) {
|
|
304
|
+
return { ok: false, error: 'Invalid FEN: en-passant square is invalid' };
|
|
305
|
+
}
|
|
306
|
+
// 5th criterion: 3th field is a valid castle-string?
|
|
307
|
+
if (/[^kKqQ-]/.test(tokens[2])) {
|
|
308
|
+
return { ok: false, error: 'Invalid FEN: castling availability is invalid' };
|
|
309
|
+
}
|
|
310
|
+
// 6th criterion: 2nd field is "w" (white) or "b" (black)?
|
|
311
|
+
if (!/^(w|b)$/.test(tokens[1])) {
|
|
312
|
+
return { ok: false, error: 'Invalid FEN: side-to-move is invalid' };
|
|
313
|
+
}
|
|
314
|
+
// 7th criterion: 1st field contains 8 rows?
|
|
315
|
+
const rows = tokens[0].split('/');
|
|
316
|
+
if (rows.length !== 8) {
|
|
317
|
+
return {
|
|
318
|
+
ok: false,
|
|
319
|
+
error: "Invalid FEN: piece data does not contain 8 '/'-delimited rows",
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
// 8th criterion: every row is valid?
|
|
323
|
+
for (let i = 0; i < rows.length; i++) {
|
|
324
|
+
// check for right sum of fields AND not two numbers in succession
|
|
325
|
+
let sumFields = 0;
|
|
326
|
+
let previousWasNumber = false;
|
|
327
|
+
for (let k = 0; k < rows[i].length; k++) {
|
|
328
|
+
if (isDigit(rows[i][k])) {
|
|
329
|
+
if (previousWasNumber) {
|
|
330
|
+
return {
|
|
331
|
+
ok: false,
|
|
332
|
+
error: 'Invalid FEN: piece data is invalid (consecutive number)',
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
sumFields += parseInt(rows[i][k], 10);
|
|
336
|
+
previousWasNumber = true;
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) {
|
|
340
|
+
return {
|
|
341
|
+
ok: false,
|
|
342
|
+
error: 'Invalid FEN: piece data is invalid (invalid piece)',
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
sumFields += 1;
|
|
346
|
+
previousWasNumber = false;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (sumFields !== 8) {
|
|
350
|
+
return {
|
|
351
|
+
ok: false,
|
|
352
|
+
error: 'Invalid FEN: piece data is invalid (too many squares in rank)',
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
// 9th criterion: is en-passant square legal?
|
|
357
|
+
if ((tokens[3][1] == '3' && tokens[1] == 'w') ||
|
|
358
|
+
(tokens[3][1] == '6' && tokens[1] == 'b')) {
|
|
359
|
+
return { ok: false, error: 'Invalid FEN: illegal en-passant square' };
|
|
360
|
+
}
|
|
361
|
+
// 10th criterion: does chess position contain exact two kings?
|
|
362
|
+
const kings = [
|
|
363
|
+
{ color: 'white', regex: /K/g },
|
|
364
|
+
{ color: 'black', regex: /k/g },
|
|
365
|
+
];
|
|
366
|
+
for (const { color, regex } of kings) {
|
|
367
|
+
if (!regex.test(tokens[0])) {
|
|
368
|
+
return { ok: false, error: `Invalid FEN: missing ${color} king` };
|
|
369
|
+
}
|
|
370
|
+
if ((tokens[0].match(regex) || []).length > 1) {
|
|
371
|
+
return { ok: false, error: `Invalid FEN: too many ${color} kings` };
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// 11th criterion: are any pawns on the first or eighth rows?
|
|
375
|
+
if (Array.from(rows[0] + rows[7]).some((char) => char.toUpperCase() === 'P')) {
|
|
376
|
+
return {
|
|
377
|
+
ok: false,
|
|
378
|
+
error: 'Invalid FEN: some pawns are on the edge rows',
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
return { ok: true };
|
|
382
|
+
}
|
|
383
|
+
// this function is used to uniquely identify ambiguous moves
|
|
384
|
+
function getDisambiguator(move, moves) {
|
|
385
|
+
const from = move.from;
|
|
386
|
+
const to = move.to;
|
|
387
|
+
const piece = move.piece;
|
|
388
|
+
let ambiguities = 0;
|
|
389
|
+
let sameRank = 0;
|
|
390
|
+
let sameFile = 0;
|
|
391
|
+
for (let i = 0, len = moves.length; i < len; i++) {
|
|
392
|
+
const ambigFrom = moves[i].from;
|
|
393
|
+
const ambigTo = moves[i].to;
|
|
394
|
+
const ambigPiece = moves[i].piece;
|
|
395
|
+
/*
|
|
396
|
+
* if a move of the same piece type ends on the same to square, we'll need
|
|
397
|
+
* to add a disambiguator to the algebraic notation
|
|
398
|
+
*/
|
|
399
|
+
if (piece === ambigPiece && from !== ambigFrom && to === ambigTo) {
|
|
400
|
+
ambiguities++;
|
|
401
|
+
if (rank(from) === rank(ambigFrom)) {
|
|
402
|
+
sameRank++;
|
|
403
|
+
}
|
|
404
|
+
if (file(from) === file(ambigFrom)) {
|
|
405
|
+
sameFile++;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (ambiguities > 0) {
|
|
410
|
+
if (sameRank > 0 && sameFile > 0) {
|
|
411
|
+
/*
|
|
412
|
+
* if there exists a similar moving piece on the same rank and file as
|
|
413
|
+
* the move in question, use the square as the disambiguator
|
|
414
|
+
*/
|
|
415
|
+
return algebraic(from);
|
|
416
|
+
}
|
|
417
|
+
else if (sameFile > 0) {
|
|
418
|
+
/*
|
|
419
|
+
* if the moving piece rests on the same file, use the rank symbol as the
|
|
420
|
+
* disambiguator
|
|
421
|
+
*/
|
|
422
|
+
return algebraic(from).charAt(1);
|
|
423
|
+
}
|
|
424
|
+
else {
|
|
425
|
+
// else use the file symbol
|
|
426
|
+
return algebraic(from).charAt(0);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return '';
|
|
430
|
+
}
|
|
431
|
+
function addMove(moves, color, from, to, piece, captured = undefined, flags = BITS.NORMAL) {
|
|
432
|
+
const r = rank(to);
|
|
433
|
+
if (piece === PAWN && (r === RANK_1 || r === RANK_8)) {
|
|
434
|
+
for (let i = 0; i < PROMOTIONS.length; i++) {
|
|
435
|
+
const promotion = PROMOTIONS[i];
|
|
436
|
+
moves.push({
|
|
437
|
+
color,
|
|
438
|
+
from,
|
|
439
|
+
to,
|
|
440
|
+
piece,
|
|
441
|
+
captured,
|
|
442
|
+
promotion,
|
|
443
|
+
flags: flags | BITS.PROMOTION,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
moves.push({
|
|
449
|
+
color,
|
|
450
|
+
from,
|
|
451
|
+
to,
|
|
452
|
+
piece,
|
|
453
|
+
captured,
|
|
454
|
+
flags,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function inferPieceType(san) {
|
|
459
|
+
let pieceType = san.charAt(0);
|
|
460
|
+
if (pieceType >= 'a' && pieceType <= 'h') {
|
|
461
|
+
const matches = san.match(/[a-h]\d.*[a-h]\d/);
|
|
462
|
+
if (matches) {
|
|
463
|
+
return undefined;
|
|
464
|
+
}
|
|
465
|
+
return PAWN;
|
|
466
|
+
}
|
|
467
|
+
pieceType = pieceType.toLowerCase();
|
|
468
|
+
if (pieceType === 'o') {
|
|
469
|
+
return KING;
|
|
470
|
+
}
|
|
471
|
+
return pieceType;
|
|
472
|
+
}
|
|
473
|
+
// parses all of the decorators out of a SAN string
|
|
474
|
+
function strippedSan(move) {
|
|
475
|
+
return move.replace(/=/, '').replace(/[+#]?[?!]*$/, '');
|
|
476
|
+
}
|
|
477
|
+
function trimFen(fen) {
|
|
478
|
+
/*
|
|
479
|
+
* remove last two fields in FEN string as they're not needed when checking
|
|
480
|
+
* for repetition
|
|
481
|
+
*/
|
|
482
|
+
return fen.split(' ').slice(0, 4).join(' ');
|
|
483
|
+
}
|
|
484
|
+
class Chess {
|
|
485
|
+
_board = new Array(128);
|
|
486
|
+
_turn = WHITE;
|
|
487
|
+
_header = {};
|
|
488
|
+
_kings = { w: EMPTY, b: EMPTY };
|
|
489
|
+
_epSquare = -1;
|
|
490
|
+
_halfMoves = 0;
|
|
491
|
+
_moveNumber = 0;
|
|
492
|
+
_history = [];
|
|
493
|
+
_comments = {};
|
|
494
|
+
_castling = { w: 0, b: 0 };
|
|
495
|
+
// tracks number of times a position has been seen for repetition checking
|
|
496
|
+
_positionCount = {};
|
|
497
|
+
constructor(fen = DEFAULT_POSITION) {
|
|
498
|
+
this.load(fen);
|
|
499
|
+
}
|
|
500
|
+
clear({ preserveHeaders = false } = {}) {
|
|
501
|
+
this._board = new Array(128);
|
|
502
|
+
this._kings = { w: EMPTY, b: EMPTY };
|
|
503
|
+
this._turn = WHITE;
|
|
504
|
+
this._castling = { w: 0, b: 0 };
|
|
505
|
+
this._epSquare = EMPTY;
|
|
506
|
+
this._halfMoves = 0;
|
|
507
|
+
this._moveNumber = 1;
|
|
508
|
+
this._history = [];
|
|
509
|
+
this._comments = {};
|
|
510
|
+
this._header = preserveHeaders ? this._header : {};
|
|
511
|
+
this._positionCount = {};
|
|
512
|
+
/*
|
|
513
|
+
* Delete the SetUp and FEN headers (if preserved), the board is empty and
|
|
514
|
+
* these headers don't make sense in this state. They'll get added later
|
|
515
|
+
* via .load() or .put()
|
|
516
|
+
*/
|
|
517
|
+
delete this._header['SetUp'];
|
|
518
|
+
delete this._header['FEN'];
|
|
519
|
+
}
|
|
520
|
+
load(fen, { skipValidation = false, preserveHeaders = false } = {}) {
|
|
521
|
+
let tokens = fen.split(/\s+/);
|
|
522
|
+
// append commonly omitted fen tokens
|
|
523
|
+
if (tokens.length >= 2 && tokens.length < 6) {
|
|
524
|
+
const adjustments = ['-', '-', '0', '1'];
|
|
525
|
+
fen = tokens.concat(adjustments.slice(-(6 - tokens.length))).join(' ');
|
|
526
|
+
}
|
|
527
|
+
tokens = fen.split(/\s+/);
|
|
528
|
+
if (!skipValidation) {
|
|
529
|
+
const { ok, error } = validateFen(fen);
|
|
530
|
+
if (!ok) {
|
|
531
|
+
throw new Error(error);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const position = tokens[0];
|
|
535
|
+
let square = 0;
|
|
536
|
+
this.clear({ preserveHeaders });
|
|
537
|
+
for (let i = 0; i < position.length; i++) {
|
|
538
|
+
const piece = position.charAt(i);
|
|
539
|
+
if (piece === '/') {
|
|
540
|
+
square += 8;
|
|
541
|
+
}
|
|
542
|
+
else if (isDigit(piece)) {
|
|
543
|
+
square += parseInt(piece, 10);
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
const color = piece < 'a' ? WHITE : BLACK;
|
|
547
|
+
this._put({ type: piece.toLowerCase(), color }, algebraic(square));
|
|
548
|
+
square++;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
this._turn = tokens[1];
|
|
552
|
+
if (tokens[2].indexOf('K') > -1) {
|
|
553
|
+
this._castling.w |= BITS.KSIDE_CASTLE;
|
|
554
|
+
}
|
|
555
|
+
if (tokens[2].indexOf('Q') > -1) {
|
|
556
|
+
this._castling.w |= BITS.QSIDE_CASTLE;
|
|
557
|
+
}
|
|
558
|
+
if (tokens[2].indexOf('k') > -1) {
|
|
559
|
+
this._castling.b |= BITS.KSIDE_CASTLE;
|
|
560
|
+
}
|
|
561
|
+
if (tokens[2].indexOf('q') > -1) {
|
|
562
|
+
this._castling.b |= BITS.QSIDE_CASTLE;
|
|
563
|
+
}
|
|
564
|
+
this._epSquare = tokens[3] === '-' ? EMPTY : Ox88[tokens[3]];
|
|
565
|
+
this._halfMoves = parseInt(tokens[4], 10);
|
|
566
|
+
this._moveNumber = parseInt(tokens[5], 10);
|
|
567
|
+
this._updateSetup(fen);
|
|
568
|
+
this._incPositionCount(fen);
|
|
569
|
+
}
|
|
570
|
+
fen() {
|
|
571
|
+
let empty = 0;
|
|
572
|
+
let fen = '';
|
|
573
|
+
for (let i = Ox88.a8; i <= Ox88.h1; i++) {
|
|
574
|
+
if (this._board[i]) {
|
|
575
|
+
if (empty > 0) {
|
|
576
|
+
fen += empty;
|
|
577
|
+
empty = 0;
|
|
578
|
+
}
|
|
579
|
+
const { color, type: piece } = this._board[i];
|
|
580
|
+
fen += color === WHITE ? piece.toUpperCase() : piece.toLowerCase();
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
empty++;
|
|
584
|
+
}
|
|
585
|
+
if ((i + 1) & 0x88) {
|
|
586
|
+
if (empty > 0) {
|
|
587
|
+
fen += empty;
|
|
588
|
+
}
|
|
589
|
+
if (i !== Ox88.h1) {
|
|
590
|
+
fen += '/';
|
|
591
|
+
}
|
|
592
|
+
empty = 0;
|
|
593
|
+
i += 8;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
let castling = '';
|
|
597
|
+
if (this._castling[WHITE] & BITS.KSIDE_CASTLE) {
|
|
598
|
+
castling += 'K';
|
|
599
|
+
}
|
|
600
|
+
if (this._castling[WHITE] & BITS.QSIDE_CASTLE) {
|
|
601
|
+
castling += 'Q';
|
|
602
|
+
}
|
|
603
|
+
if (this._castling[BLACK] & BITS.KSIDE_CASTLE) {
|
|
604
|
+
castling += 'k';
|
|
605
|
+
}
|
|
606
|
+
if (this._castling[BLACK] & BITS.QSIDE_CASTLE) {
|
|
607
|
+
castling += 'q';
|
|
608
|
+
}
|
|
609
|
+
// do we have an empty castling flag?
|
|
610
|
+
castling = castling || '-';
|
|
611
|
+
let epSquare = '-';
|
|
612
|
+
/*
|
|
613
|
+
* only print the ep square if en passant is a valid move (pawn is present
|
|
614
|
+
* and ep capture is not pinned)
|
|
615
|
+
*/
|
|
616
|
+
if (this._epSquare !== EMPTY) {
|
|
617
|
+
const bigPawnSquare = this._epSquare + (this._turn === WHITE ? 16 : -16);
|
|
618
|
+
const squares = [bigPawnSquare + 1, bigPawnSquare - 1];
|
|
619
|
+
for (const square of squares) {
|
|
620
|
+
// is the square off the board?
|
|
621
|
+
if (square & 0x88) {
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
const color = this._turn;
|
|
625
|
+
// is there a pawn that can capture the epSquare?
|
|
626
|
+
if (this._board[square]?.color === color &&
|
|
627
|
+
this._board[square]?.type === PAWN) {
|
|
628
|
+
// if the pawn makes an ep capture, does it leave it's king in check?
|
|
629
|
+
this._makeMove({
|
|
630
|
+
color,
|
|
631
|
+
from: square,
|
|
632
|
+
to: this._epSquare,
|
|
633
|
+
piece: PAWN,
|
|
634
|
+
captured: PAWN,
|
|
635
|
+
flags: BITS.EP_CAPTURE,
|
|
636
|
+
});
|
|
637
|
+
const isLegal = !this._isKingAttacked(color);
|
|
638
|
+
this._undoMove();
|
|
639
|
+
// if ep is legal, break and set the ep square in the FEN output
|
|
640
|
+
if (isLegal) {
|
|
641
|
+
epSquare = algebraic(this._epSquare);
|
|
642
|
+
break;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return [
|
|
648
|
+
fen,
|
|
649
|
+
this._turn,
|
|
650
|
+
castling,
|
|
651
|
+
epSquare,
|
|
652
|
+
this._halfMoves,
|
|
653
|
+
this._moveNumber,
|
|
654
|
+
].join(' ');
|
|
655
|
+
}
|
|
656
|
+
/*
|
|
657
|
+
* Called when the initial board setup is changed with put() or remove().
|
|
658
|
+
* modifies the SetUp and FEN properties of the header object. If the FEN
|
|
659
|
+
* is equal to the default position, the SetUp and FEN are deleted the setup
|
|
660
|
+
* is only updated if history.length is zero, ie moves haven't been made.
|
|
661
|
+
*/
|
|
662
|
+
_updateSetup(fen) {
|
|
663
|
+
if (this._history.length > 0)
|
|
664
|
+
return;
|
|
665
|
+
if (fen !== DEFAULT_POSITION) {
|
|
666
|
+
this._header['SetUp'] = '1';
|
|
667
|
+
this._header['FEN'] = fen;
|
|
668
|
+
}
|
|
669
|
+
else {
|
|
670
|
+
delete this._header['SetUp'];
|
|
671
|
+
delete this._header['FEN'];
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
reset() {
|
|
675
|
+
this.load(DEFAULT_POSITION);
|
|
676
|
+
}
|
|
677
|
+
get(square) {
|
|
678
|
+
return this._board[Ox88[square]];
|
|
679
|
+
}
|
|
680
|
+
put({ type, color }, square) {
|
|
681
|
+
if (this._put({ type, color }, square)) {
|
|
682
|
+
this._updateCastlingRights();
|
|
683
|
+
this._updateEnPassantSquare();
|
|
684
|
+
this._updateSetup(this.fen());
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
_put({ type, color }, square) {
|
|
690
|
+
// check for piece
|
|
691
|
+
if (SYMBOLS.indexOf(type.toLowerCase()) === -1) {
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
// check for valid square
|
|
695
|
+
if (!(square in Ox88)) {
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
const sq = Ox88[square];
|
|
699
|
+
// don't let the user place more than one king
|
|
700
|
+
if (type == KING &&
|
|
701
|
+
!(this._kings[color] == EMPTY || this._kings[color] == sq)) {
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
const currentPieceOnSquare = this._board[sq];
|
|
705
|
+
// if one of the kings will be replaced by the piece from args, set the `_kings` respective entry to `EMPTY`
|
|
706
|
+
if (currentPieceOnSquare && currentPieceOnSquare.type === KING) {
|
|
707
|
+
this._kings[currentPieceOnSquare.color] = EMPTY;
|
|
708
|
+
}
|
|
709
|
+
this._board[sq] = { type: type, color: color };
|
|
710
|
+
if (type === KING) {
|
|
711
|
+
this._kings[color] = sq;
|
|
712
|
+
}
|
|
713
|
+
return true;
|
|
714
|
+
}
|
|
715
|
+
remove(square) {
|
|
716
|
+
const piece = this.get(square);
|
|
717
|
+
delete this._board[Ox88[square]];
|
|
718
|
+
if (piece && piece.type === KING) {
|
|
719
|
+
this._kings[piece.color] = EMPTY;
|
|
720
|
+
}
|
|
721
|
+
this._updateCastlingRights();
|
|
722
|
+
this._updateEnPassantSquare();
|
|
723
|
+
this._updateSetup(this.fen());
|
|
724
|
+
return piece;
|
|
725
|
+
}
|
|
726
|
+
_updateCastlingRights() {
|
|
727
|
+
const whiteKingInPlace = this._board[Ox88.e1]?.type === KING &&
|
|
728
|
+
this._board[Ox88.e1]?.color === WHITE;
|
|
729
|
+
const blackKingInPlace = this._board[Ox88.e8]?.type === KING &&
|
|
730
|
+
this._board[Ox88.e8]?.color === BLACK;
|
|
731
|
+
if (!whiteKingInPlace ||
|
|
732
|
+
this._board[Ox88.a1]?.type !== ROOK ||
|
|
733
|
+
this._board[Ox88.a1]?.color !== WHITE) {
|
|
734
|
+
this._castling.w &= -65;
|
|
735
|
+
}
|
|
736
|
+
if (!whiteKingInPlace ||
|
|
737
|
+
this._board[Ox88.h1]?.type !== ROOK ||
|
|
738
|
+
this._board[Ox88.h1]?.color !== WHITE) {
|
|
739
|
+
this._castling.w &= -33;
|
|
740
|
+
}
|
|
741
|
+
if (!blackKingInPlace ||
|
|
742
|
+
this._board[Ox88.a8]?.type !== ROOK ||
|
|
743
|
+
this._board[Ox88.a8]?.color !== BLACK) {
|
|
744
|
+
this._castling.b &= -65;
|
|
745
|
+
}
|
|
746
|
+
if (!blackKingInPlace ||
|
|
747
|
+
this._board[Ox88.h8]?.type !== ROOK ||
|
|
748
|
+
this._board[Ox88.h8]?.color !== BLACK) {
|
|
749
|
+
this._castling.b &= -33;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
_updateEnPassantSquare() {
|
|
753
|
+
if (this._epSquare === EMPTY) {
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const startSquare = this._epSquare + (this._turn === WHITE ? -16 : 16);
|
|
757
|
+
const currentSquare = this._epSquare + (this._turn === WHITE ? 16 : -16);
|
|
758
|
+
const attackers = [currentSquare + 1, currentSquare - 1];
|
|
759
|
+
if (this._board[startSquare] !== null ||
|
|
760
|
+
this._board[this._epSquare] !== null ||
|
|
761
|
+
this._board[currentSquare]?.color !== swapColor(this._turn) ||
|
|
762
|
+
this._board[currentSquare]?.type !== PAWN) {
|
|
763
|
+
this._epSquare = EMPTY;
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
const canCapture = (square) => !(square & 0x88) &&
|
|
767
|
+
this._board[square]?.color === this._turn &&
|
|
768
|
+
this._board[square]?.type === PAWN;
|
|
769
|
+
if (!attackers.some(canCapture)) {
|
|
770
|
+
this._epSquare = EMPTY;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
_attacked(color, square, verbose) {
|
|
774
|
+
const attackers = [];
|
|
775
|
+
for (let i = Ox88.a8; i <= Ox88.h1; i++) {
|
|
776
|
+
// did we run off the end of the board
|
|
777
|
+
if (i & 0x88) {
|
|
778
|
+
i += 7;
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
// if empty square or wrong color
|
|
782
|
+
if (this._board[i] === undefined || this._board[i].color !== color) {
|
|
783
|
+
continue;
|
|
784
|
+
}
|
|
785
|
+
const piece = this._board[i];
|
|
786
|
+
const difference = i - square;
|
|
787
|
+
// skip - to/from square are the same
|
|
788
|
+
if (difference === 0) {
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
const index = difference + 119;
|
|
792
|
+
if (ATTACKS[index] & PIECE_MASKS[piece.type]) {
|
|
793
|
+
if (piece.type === PAWN) {
|
|
794
|
+
if ((difference > 0 && piece.color === WHITE) ||
|
|
795
|
+
(difference <= 0 && piece.color === BLACK)) {
|
|
796
|
+
if (!verbose) {
|
|
797
|
+
return true;
|
|
798
|
+
}
|
|
799
|
+
else {
|
|
800
|
+
attackers.push(algebraic(i));
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
// if the piece is a knight or a king
|
|
806
|
+
if (piece.type === 'n' || piece.type === 'k') {
|
|
807
|
+
if (!verbose) {
|
|
808
|
+
return true;
|
|
809
|
+
}
|
|
810
|
+
else {
|
|
811
|
+
attackers.push(algebraic(i));
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
const offset = RAYS[index];
|
|
816
|
+
let j = i + offset;
|
|
817
|
+
let blocked = false;
|
|
818
|
+
while (j !== square) {
|
|
819
|
+
if (this._board[j] != null) {
|
|
820
|
+
blocked = true;
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
j += offset;
|
|
824
|
+
}
|
|
825
|
+
if (!blocked) {
|
|
826
|
+
if (!verbose) {
|
|
827
|
+
return true;
|
|
828
|
+
}
|
|
829
|
+
else {
|
|
830
|
+
attackers.push(algebraic(i));
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (verbose) {
|
|
837
|
+
return attackers;
|
|
838
|
+
}
|
|
839
|
+
else {
|
|
840
|
+
return false;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
attackers(square, attackedBy) {
|
|
844
|
+
if (!attackedBy) {
|
|
845
|
+
return this._attacked(this._turn, Ox88[square], true);
|
|
846
|
+
}
|
|
847
|
+
else {
|
|
848
|
+
return this._attacked(attackedBy, Ox88[square], true);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
_isKingAttacked(color) {
|
|
852
|
+
const square = this._kings[color];
|
|
853
|
+
return square === -1 ? false : this._attacked(swapColor(color), square);
|
|
854
|
+
}
|
|
855
|
+
isAttacked(square, attackedBy) {
|
|
856
|
+
return this._attacked(attackedBy, Ox88[square]);
|
|
857
|
+
}
|
|
858
|
+
isCheck() {
|
|
859
|
+
return this._isKingAttacked(this._turn);
|
|
860
|
+
}
|
|
861
|
+
inCheck() {
|
|
862
|
+
return this.isCheck();
|
|
863
|
+
}
|
|
864
|
+
isCheckmate() {
|
|
865
|
+
return this.isCheck() && this._moves().length === 0;
|
|
866
|
+
}
|
|
867
|
+
isStalemate() {
|
|
868
|
+
return !this.isCheck() && this._moves().length === 0;
|
|
869
|
+
}
|
|
870
|
+
isInsufficientMaterial() {
|
|
871
|
+
/*
|
|
872
|
+
* k.b. vs k.b. (of opposite colors) with mate in 1:
|
|
873
|
+
* 8/8/8/8/1b6/8/B1k5/K7 b - - 0 1
|
|
874
|
+
*
|
|
875
|
+
* k.b. vs k.n. with mate in 1:
|
|
876
|
+
* 8/8/8/8/1n6/8/B7/K1k5 b - - 2 1
|
|
877
|
+
*/
|
|
878
|
+
const pieces = {
|
|
879
|
+
b: 0,
|
|
880
|
+
n: 0,
|
|
881
|
+
r: 0,
|
|
882
|
+
q: 0,
|
|
883
|
+
k: 0,
|
|
884
|
+
p: 0,
|
|
885
|
+
};
|
|
886
|
+
const bishops = [];
|
|
887
|
+
let numPieces = 0;
|
|
888
|
+
let squareColor = 0;
|
|
889
|
+
for (let i = Ox88.a8; i <= Ox88.h1; i++) {
|
|
890
|
+
squareColor = (squareColor + 1) % 2;
|
|
891
|
+
if (i & 0x88) {
|
|
892
|
+
i += 7;
|
|
893
|
+
continue;
|
|
894
|
+
}
|
|
895
|
+
const piece = this._board[i];
|
|
896
|
+
if (piece) {
|
|
897
|
+
pieces[piece.type] = piece.type in pieces ? pieces[piece.type] + 1 : 1;
|
|
898
|
+
if (piece.type === BISHOP) {
|
|
899
|
+
bishops.push(squareColor);
|
|
900
|
+
}
|
|
901
|
+
numPieces++;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
// k vs. k
|
|
905
|
+
if (numPieces === 2) {
|
|
906
|
+
return true;
|
|
907
|
+
}
|
|
908
|
+
else if (
|
|
909
|
+
// k vs. kn .... or .... k vs. kb
|
|
910
|
+
numPieces === 3 &&
|
|
911
|
+
(pieces[BISHOP] === 1 || pieces[KNIGHT] === 1)) {
|
|
912
|
+
return true;
|
|
913
|
+
}
|
|
914
|
+
else if (numPieces === pieces[BISHOP] + 2) {
|
|
915
|
+
// kb vs. kb where any number of bishops are all on the same color
|
|
916
|
+
let sum = 0;
|
|
917
|
+
const len = bishops.length;
|
|
918
|
+
for (let i = 0; i < len; i++) {
|
|
919
|
+
sum += bishops[i];
|
|
920
|
+
}
|
|
921
|
+
if (sum === 0 || sum === len) {
|
|
922
|
+
return true;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
return false;
|
|
926
|
+
}
|
|
927
|
+
isThreefoldRepetition() {
|
|
928
|
+
return this._getPositionCount(this.fen()) >= 3;
|
|
929
|
+
}
|
|
930
|
+
isDrawByFiftyMoves() {
|
|
931
|
+
return this._halfMoves >= 100; // 50 moves per side = 100 half moves
|
|
932
|
+
}
|
|
933
|
+
isDraw() {
|
|
934
|
+
return (this.isDrawByFiftyMoves() ||
|
|
935
|
+
this.isStalemate() ||
|
|
936
|
+
this.isInsufficientMaterial() ||
|
|
937
|
+
this.isThreefoldRepetition());
|
|
938
|
+
}
|
|
939
|
+
isGameOver() {
|
|
940
|
+
return this.isCheckmate() || this.isStalemate() || this.isDraw();
|
|
941
|
+
}
|
|
942
|
+
moves({ verbose = false, square = undefined, piece = undefined, } = {}) {
|
|
943
|
+
const moves = this._moves({ square, piece });
|
|
944
|
+
if (verbose) {
|
|
945
|
+
return moves.map((move) => new Move$1(this, move));
|
|
946
|
+
}
|
|
947
|
+
else {
|
|
948
|
+
return moves.map((move) => this._moveToSan(move, moves));
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
_moves({ legal = true, piece = undefined, square = undefined, } = {}) {
|
|
952
|
+
const forSquare = square ? square.toLowerCase() : undefined;
|
|
953
|
+
const forPiece = piece?.toLowerCase();
|
|
954
|
+
const moves = [];
|
|
955
|
+
const us = this._turn;
|
|
956
|
+
const them = swapColor(us);
|
|
957
|
+
let firstSquare = Ox88.a8;
|
|
958
|
+
let lastSquare = Ox88.h1;
|
|
959
|
+
let singleSquare = false;
|
|
960
|
+
// are we generating moves for a single square?
|
|
961
|
+
if (forSquare) {
|
|
962
|
+
// illegal square, return empty moves
|
|
963
|
+
if (!(forSquare in Ox88)) {
|
|
964
|
+
return [];
|
|
965
|
+
}
|
|
966
|
+
else {
|
|
967
|
+
firstSquare = lastSquare = Ox88[forSquare];
|
|
968
|
+
singleSquare = true;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
for (let from = firstSquare; from <= lastSquare; from++) {
|
|
972
|
+
// did we run off the end of the board
|
|
973
|
+
if (from & 0x88) {
|
|
974
|
+
from += 7;
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
// empty square or opponent, skip
|
|
978
|
+
if (!this._board[from] || this._board[from].color === them) {
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
const { type } = this._board[from];
|
|
982
|
+
let to;
|
|
983
|
+
if (type === PAWN) {
|
|
984
|
+
if (forPiece && forPiece !== type)
|
|
985
|
+
continue;
|
|
986
|
+
// single square, non-capturing
|
|
987
|
+
to = from + PAWN_OFFSETS[us][0];
|
|
988
|
+
if (!this._board[to]) {
|
|
989
|
+
addMove(moves, us, from, to, PAWN);
|
|
990
|
+
// double square
|
|
991
|
+
to = from + PAWN_OFFSETS[us][1];
|
|
992
|
+
if (SECOND_RANK[us] === rank(from) && !this._board[to]) {
|
|
993
|
+
addMove(moves, us, from, to, PAWN, undefined, BITS.BIG_PAWN);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
// pawn captures
|
|
997
|
+
for (let j = 2; j < 4; j++) {
|
|
998
|
+
to = from + PAWN_OFFSETS[us][j];
|
|
999
|
+
if (to & 0x88)
|
|
1000
|
+
continue;
|
|
1001
|
+
if (this._board[to]?.color === them) {
|
|
1002
|
+
addMove(moves, us, from, to, PAWN, this._board[to].type, BITS.CAPTURE);
|
|
1003
|
+
}
|
|
1004
|
+
else if (to === this._epSquare) {
|
|
1005
|
+
addMove(moves, us, from, to, PAWN, PAWN, BITS.EP_CAPTURE);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
else {
|
|
1010
|
+
if (forPiece && forPiece !== type)
|
|
1011
|
+
continue;
|
|
1012
|
+
for (let j = 0, len = PIECE_OFFSETS[type].length; j < len; j++) {
|
|
1013
|
+
const offset = PIECE_OFFSETS[type][j];
|
|
1014
|
+
to = from;
|
|
1015
|
+
while (true) {
|
|
1016
|
+
to += offset;
|
|
1017
|
+
if (to & 0x88)
|
|
1018
|
+
break;
|
|
1019
|
+
if (!this._board[to]) {
|
|
1020
|
+
addMove(moves, us, from, to, type);
|
|
1021
|
+
}
|
|
1022
|
+
else {
|
|
1023
|
+
// own color, stop loop
|
|
1024
|
+
if (this._board[to].color === us)
|
|
1025
|
+
break;
|
|
1026
|
+
addMove(moves, us, from, to, type, this._board[to].type, BITS.CAPTURE);
|
|
1027
|
+
break;
|
|
1028
|
+
}
|
|
1029
|
+
/* break, if knight or king */
|
|
1030
|
+
if (type === KNIGHT || type === KING)
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
/*
|
|
1037
|
+
* check for castling if we're:
|
|
1038
|
+
* a) generating all moves, or
|
|
1039
|
+
* b) doing single square move generation on the king's square
|
|
1040
|
+
*/
|
|
1041
|
+
if (forPiece === undefined || forPiece === KING) {
|
|
1042
|
+
if (!singleSquare || lastSquare === this._kings[us]) {
|
|
1043
|
+
// king-side castling
|
|
1044
|
+
if (this._castling[us] & BITS.KSIDE_CASTLE) {
|
|
1045
|
+
const castlingFrom = this._kings[us];
|
|
1046
|
+
const castlingTo = castlingFrom + 2;
|
|
1047
|
+
if (!this._board[castlingFrom + 1] &&
|
|
1048
|
+
!this._board[castlingTo] &&
|
|
1049
|
+
!this._attacked(them, this._kings[us]) &&
|
|
1050
|
+
!this._attacked(them, castlingFrom + 1) &&
|
|
1051
|
+
!this._attacked(them, castlingTo)) {
|
|
1052
|
+
addMove(moves, us, this._kings[us], castlingTo, KING, undefined, BITS.KSIDE_CASTLE);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
// queen-side castling
|
|
1056
|
+
if (this._castling[us] & BITS.QSIDE_CASTLE) {
|
|
1057
|
+
const castlingFrom = this._kings[us];
|
|
1058
|
+
const castlingTo = castlingFrom - 2;
|
|
1059
|
+
if (!this._board[castlingFrom - 1] &&
|
|
1060
|
+
!this._board[castlingFrom - 2] &&
|
|
1061
|
+
!this._board[castlingFrom - 3] &&
|
|
1062
|
+
!this._attacked(them, this._kings[us]) &&
|
|
1063
|
+
!this._attacked(them, castlingFrom - 1) &&
|
|
1064
|
+
!this._attacked(them, castlingTo)) {
|
|
1065
|
+
addMove(moves, us, this._kings[us], castlingTo, KING, undefined, BITS.QSIDE_CASTLE);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
/*
|
|
1071
|
+
* return all pseudo-legal moves (this includes moves that allow the king
|
|
1072
|
+
* to be captured)
|
|
1073
|
+
*/
|
|
1074
|
+
if (!legal || this._kings[us] === -1) {
|
|
1075
|
+
return moves;
|
|
1076
|
+
}
|
|
1077
|
+
// filter out illegal moves
|
|
1078
|
+
const legalMoves = [];
|
|
1079
|
+
for (let i = 0, len = moves.length; i < len; i++) {
|
|
1080
|
+
this._makeMove(moves[i]);
|
|
1081
|
+
if (!this._isKingAttacked(us)) {
|
|
1082
|
+
legalMoves.push(moves[i]);
|
|
1083
|
+
}
|
|
1084
|
+
this._undoMove();
|
|
1085
|
+
}
|
|
1086
|
+
return legalMoves;
|
|
1087
|
+
}
|
|
1088
|
+
move(move, { strict = false } = {}) {
|
|
1089
|
+
/*
|
|
1090
|
+
* The move function can be called with in the following parameters:
|
|
1091
|
+
*
|
|
1092
|
+
* .move('Nxb7') <- argument is a case-sensitive SAN string
|
|
1093
|
+
*
|
|
1094
|
+
* .move({ from: 'h7', <- argument is a move object
|
|
1095
|
+
* to :'h8',
|
|
1096
|
+
* promotion: 'q' })
|
|
1097
|
+
*
|
|
1098
|
+
*
|
|
1099
|
+
* An optional strict argument may be supplied to tell chess.js to
|
|
1100
|
+
* strictly follow the SAN specification.
|
|
1101
|
+
*/
|
|
1102
|
+
let moveObj = null;
|
|
1103
|
+
if (typeof move === 'string') {
|
|
1104
|
+
moveObj = this._moveFromSan(move, strict);
|
|
1105
|
+
}
|
|
1106
|
+
else if (typeof move === 'object') {
|
|
1107
|
+
const moves = this._moves();
|
|
1108
|
+
// convert the pretty move object to an ugly move object
|
|
1109
|
+
for (let i = 0, len = moves.length; i < len; i++) {
|
|
1110
|
+
if (move.from === algebraic(moves[i].from) &&
|
|
1111
|
+
move.to === algebraic(moves[i].to) &&
|
|
1112
|
+
(!('promotion' in moves[i]) || move.promotion === moves[i].promotion)) {
|
|
1113
|
+
moveObj = moves[i];
|
|
1114
|
+
break;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
// failed to find move
|
|
1119
|
+
if (!moveObj) {
|
|
1120
|
+
if (typeof move === 'string') {
|
|
1121
|
+
throw new Error(`Invalid move: ${move}`);
|
|
1122
|
+
}
|
|
1123
|
+
else {
|
|
1124
|
+
throw new Error(`Invalid move: ${JSON.stringify(move)}`);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
/*
|
|
1128
|
+
* need to make a copy of move because we can't generate SAN after the move
|
|
1129
|
+
* is made
|
|
1130
|
+
*/
|
|
1131
|
+
const prettyMove = new Move$1(this, moveObj);
|
|
1132
|
+
this._makeMove(moveObj);
|
|
1133
|
+
this._incPositionCount(prettyMove.after);
|
|
1134
|
+
return prettyMove;
|
|
1135
|
+
}
|
|
1136
|
+
_push(move) {
|
|
1137
|
+
this._history.push({
|
|
1138
|
+
move,
|
|
1139
|
+
kings: { b: this._kings.b, w: this._kings.w },
|
|
1140
|
+
turn: this._turn,
|
|
1141
|
+
castling: { b: this._castling.b, w: this._castling.w },
|
|
1142
|
+
epSquare: this._epSquare,
|
|
1143
|
+
halfMoves: this._halfMoves,
|
|
1144
|
+
moveNumber: this._moveNumber,
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
_makeMove(move) {
|
|
1148
|
+
const us = this._turn;
|
|
1149
|
+
const them = swapColor(us);
|
|
1150
|
+
this._push(move);
|
|
1151
|
+
this._board[move.to] = this._board[move.from];
|
|
1152
|
+
delete this._board[move.from];
|
|
1153
|
+
// if ep capture, remove the captured pawn
|
|
1154
|
+
if (move.flags & BITS.EP_CAPTURE) {
|
|
1155
|
+
if (this._turn === BLACK) {
|
|
1156
|
+
delete this._board[move.to - 16];
|
|
1157
|
+
}
|
|
1158
|
+
else {
|
|
1159
|
+
delete this._board[move.to + 16];
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
// if pawn promotion, replace with new piece
|
|
1163
|
+
if (move.promotion) {
|
|
1164
|
+
this._board[move.to] = { type: move.promotion, color: us };
|
|
1165
|
+
}
|
|
1166
|
+
// if we moved the king
|
|
1167
|
+
if (this._board[move.to].type === KING) {
|
|
1168
|
+
this._kings[us] = move.to;
|
|
1169
|
+
// if we castled, move the rook next to the king
|
|
1170
|
+
if (move.flags & BITS.KSIDE_CASTLE) {
|
|
1171
|
+
const castlingTo = move.to - 1;
|
|
1172
|
+
const castlingFrom = move.to + 1;
|
|
1173
|
+
this._board[castlingTo] = this._board[castlingFrom];
|
|
1174
|
+
delete this._board[castlingFrom];
|
|
1175
|
+
}
|
|
1176
|
+
else if (move.flags & BITS.QSIDE_CASTLE) {
|
|
1177
|
+
const castlingTo = move.to + 1;
|
|
1178
|
+
const castlingFrom = move.to - 2;
|
|
1179
|
+
this._board[castlingTo] = this._board[castlingFrom];
|
|
1180
|
+
delete this._board[castlingFrom];
|
|
1181
|
+
}
|
|
1182
|
+
// turn off castling
|
|
1183
|
+
this._castling[us] = 0;
|
|
1184
|
+
}
|
|
1185
|
+
// turn off castling if we move a rook
|
|
1186
|
+
if (this._castling[us]) {
|
|
1187
|
+
for (let i = 0, len = ROOKS[us].length; i < len; i++) {
|
|
1188
|
+
if (move.from === ROOKS[us][i].square &&
|
|
1189
|
+
this._castling[us] & ROOKS[us][i].flag) {
|
|
1190
|
+
this._castling[us] ^= ROOKS[us][i].flag;
|
|
1191
|
+
break;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
// turn off castling if we capture a rook
|
|
1196
|
+
if (this._castling[them]) {
|
|
1197
|
+
for (let i = 0, len = ROOKS[them].length; i < len; i++) {
|
|
1198
|
+
if (move.to === ROOKS[them][i].square &&
|
|
1199
|
+
this._castling[them] & ROOKS[them][i].flag) {
|
|
1200
|
+
this._castling[them] ^= ROOKS[them][i].flag;
|
|
1201
|
+
break;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
// if big pawn move, update the en passant square
|
|
1206
|
+
if (move.flags & BITS.BIG_PAWN) {
|
|
1207
|
+
if (us === BLACK) {
|
|
1208
|
+
this._epSquare = move.to - 16;
|
|
1209
|
+
}
|
|
1210
|
+
else {
|
|
1211
|
+
this._epSquare = move.to + 16;
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
else {
|
|
1215
|
+
this._epSquare = EMPTY;
|
|
1216
|
+
}
|
|
1217
|
+
// reset the 50 move counter if a pawn is moved or a piece is captured
|
|
1218
|
+
if (move.piece === PAWN) {
|
|
1219
|
+
this._halfMoves = 0;
|
|
1220
|
+
}
|
|
1221
|
+
else if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) {
|
|
1222
|
+
this._halfMoves = 0;
|
|
1223
|
+
}
|
|
1224
|
+
else {
|
|
1225
|
+
this._halfMoves++;
|
|
1226
|
+
}
|
|
1227
|
+
if (us === BLACK) {
|
|
1228
|
+
this._moveNumber++;
|
|
1229
|
+
}
|
|
1230
|
+
this._turn = them;
|
|
1231
|
+
}
|
|
1232
|
+
undo() {
|
|
1233
|
+
const move = this._undoMove();
|
|
1234
|
+
if (move) {
|
|
1235
|
+
const prettyMove = new Move$1(this, move);
|
|
1236
|
+
this._decPositionCount(prettyMove.after);
|
|
1237
|
+
return prettyMove;
|
|
1238
|
+
}
|
|
1239
|
+
return null;
|
|
1240
|
+
}
|
|
1241
|
+
_undoMove() {
|
|
1242
|
+
const old = this._history.pop();
|
|
1243
|
+
if (old === undefined) {
|
|
1244
|
+
return null;
|
|
1245
|
+
}
|
|
1246
|
+
const move = old.move;
|
|
1247
|
+
this._kings = old.kings;
|
|
1248
|
+
this._turn = old.turn;
|
|
1249
|
+
this._castling = old.castling;
|
|
1250
|
+
this._epSquare = old.epSquare;
|
|
1251
|
+
this._halfMoves = old.halfMoves;
|
|
1252
|
+
this._moveNumber = old.moveNumber;
|
|
1253
|
+
const us = this._turn;
|
|
1254
|
+
const them = swapColor(us);
|
|
1255
|
+
this._board[move.from] = this._board[move.to];
|
|
1256
|
+
this._board[move.from].type = move.piece; // to undo any promotions
|
|
1257
|
+
delete this._board[move.to];
|
|
1258
|
+
if (move.captured) {
|
|
1259
|
+
if (move.flags & BITS.EP_CAPTURE) {
|
|
1260
|
+
// en passant capture
|
|
1261
|
+
let index;
|
|
1262
|
+
if (us === BLACK) {
|
|
1263
|
+
index = move.to - 16;
|
|
1264
|
+
}
|
|
1265
|
+
else {
|
|
1266
|
+
index = move.to + 16;
|
|
1267
|
+
}
|
|
1268
|
+
this._board[index] = { type: PAWN, color: them };
|
|
1269
|
+
}
|
|
1270
|
+
else {
|
|
1271
|
+
// regular capture
|
|
1272
|
+
this._board[move.to] = { type: move.captured, color: them };
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) {
|
|
1276
|
+
let castlingTo, castlingFrom;
|
|
1277
|
+
if (move.flags & BITS.KSIDE_CASTLE) {
|
|
1278
|
+
castlingTo = move.to + 1;
|
|
1279
|
+
castlingFrom = move.to - 1;
|
|
1280
|
+
}
|
|
1281
|
+
else {
|
|
1282
|
+
castlingTo = move.to - 2;
|
|
1283
|
+
castlingFrom = move.to + 1;
|
|
1284
|
+
}
|
|
1285
|
+
this._board[castlingTo] = this._board[castlingFrom];
|
|
1286
|
+
delete this._board[castlingFrom];
|
|
1287
|
+
}
|
|
1288
|
+
return move;
|
|
1289
|
+
}
|
|
1290
|
+
pgn({ newline = '\n', maxWidth = 0, } = {}) {
|
|
1291
|
+
/*
|
|
1292
|
+
* using the specification from http://www.chessclub.com/help/PGN-spec
|
|
1293
|
+
* example for html usage: .pgn({ max_width: 72, newline_char: "<br />" })
|
|
1294
|
+
*/
|
|
1295
|
+
const result = [];
|
|
1296
|
+
let headerExists = false;
|
|
1297
|
+
/* add the PGN header information */
|
|
1298
|
+
for (const i in this._header) {
|
|
1299
|
+
/*
|
|
1300
|
+
* TODO: order of enumerated properties in header object is not
|
|
1301
|
+
* guaranteed, see ECMA-262 spec (section 12.6.4)
|
|
1302
|
+
*/
|
|
1303
|
+
result.push('[' + i + ' "' + this._header[i] + '"]' + newline);
|
|
1304
|
+
headerExists = true;
|
|
1305
|
+
}
|
|
1306
|
+
if (headerExists && this._history.length) {
|
|
1307
|
+
result.push(newline);
|
|
1308
|
+
}
|
|
1309
|
+
const appendComment = (moveString) => {
|
|
1310
|
+
const comment = this._comments[this.fen()];
|
|
1311
|
+
if (typeof comment !== 'undefined') {
|
|
1312
|
+
const delimiter = moveString.length > 0 ? ' ' : '';
|
|
1313
|
+
moveString = `${moveString}${delimiter}{${comment}}`;
|
|
1314
|
+
}
|
|
1315
|
+
return moveString;
|
|
1316
|
+
};
|
|
1317
|
+
// pop all of history onto reversed_history
|
|
1318
|
+
const reversedHistory = [];
|
|
1319
|
+
while (this._history.length > 0) {
|
|
1320
|
+
reversedHistory.push(this._undoMove());
|
|
1321
|
+
}
|
|
1322
|
+
const moves = [];
|
|
1323
|
+
let moveString = '';
|
|
1324
|
+
// special case of a commented starting position with no moves
|
|
1325
|
+
if (reversedHistory.length === 0) {
|
|
1326
|
+
moves.push(appendComment(''));
|
|
1327
|
+
}
|
|
1328
|
+
// build the list of moves. a move_string looks like: "3. e3 e6"
|
|
1329
|
+
while (reversedHistory.length > 0) {
|
|
1330
|
+
moveString = appendComment(moveString);
|
|
1331
|
+
const move = reversedHistory.pop();
|
|
1332
|
+
// make TypeScript stop complaining about move being undefined
|
|
1333
|
+
if (!move) {
|
|
1334
|
+
break;
|
|
1335
|
+
}
|
|
1336
|
+
// if the position started with black to move, start PGN with #. ...
|
|
1337
|
+
if (!this._history.length && move.color === 'b') {
|
|
1338
|
+
const prefix = `${this._moveNumber}. ...`;
|
|
1339
|
+
// is there a comment preceding the first move?
|
|
1340
|
+
moveString = moveString ? `${moveString} ${prefix}` : prefix;
|
|
1341
|
+
}
|
|
1342
|
+
else if (move.color === 'w') {
|
|
1343
|
+
// store the previous generated move_string if we have one
|
|
1344
|
+
if (moveString.length) {
|
|
1345
|
+
moves.push(moveString);
|
|
1346
|
+
}
|
|
1347
|
+
moveString = this._moveNumber + '.';
|
|
1348
|
+
}
|
|
1349
|
+
moveString =
|
|
1350
|
+
moveString + ' ' + this._moveToSan(move, this._moves({ legal: true }));
|
|
1351
|
+
this._makeMove(move);
|
|
1352
|
+
}
|
|
1353
|
+
// are there any other leftover moves?
|
|
1354
|
+
if (moveString.length) {
|
|
1355
|
+
moves.push(appendComment(moveString));
|
|
1356
|
+
}
|
|
1357
|
+
// is there a result?
|
|
1358
|
+
if (typeof this._header.Result !== 'undefined') {
|
|
1359
|
+
moves.push(this._header.Result);
|
|
1360
|
+
}
|
|
1361
|
+
/*
|
|
1362
|
+
* history should be back to what it was before we started generating PGN,
|
|
1363
|
+
* so join together moves
|
|
1364
|
+
*/
|
|
1365
|
+
if (maxWidth === 0) {
|
|
1366
|
+
return result.join('') + moves.join(' ');
|
|
1367
|
+
}
|
|
1368
|
+
// TODO (jah): huh?
|
|
1369
|
+
const strip = function () {
|
|
1370
|
+
if (result.length > 0 && result[result.length - 1] === ' ') {
|
|
1371
|
+
result.pop();
|
|
1372
|
+
return true;
|
|
1373
|
+
}
|
|
1374
|
+
return false;
|
|
1375
|
+
};
|
|
1376
|
+
// NB: this does not preserve comment whitespace.
|
|
1377
|
+
const wrapComment = function (width, move) {
|
|
1378
|
+
for (const token of move.split(' ')) {
|
|
1379
|
+
if (!token) {
|
|
1380
|
+
continue;
|
|
1381
|
+
}
|
|
1382
|
+
if (width + token.length > maxWidth) {
|
|
1383
|
+
while (strip()) {
|
|
1384
|
+
width--;
|
|
1385
|
+
}
|
|
1386
|
+
result.push(newline);
|
|
1387
|
+
width = 0;
|
|
1388
|
+
}
|
|
1389
|
+
result.push(token);
|
|
1390
|
+
width += token.length;
|
|
1391
|
+
result.push(' ');
|
|
1392
|
+
width++;
|
|
1393
|
+
}
|
|
1394
|
+
if (strip()) {
|
|
1395
|
+
width--;
|
|
1396
|
+
}
|
|
1397
|
+
return width;
|
|
1398
|
+
};
|
|
1399
|
+
// wrap the PGN output at max_width
|
|
1400
|
+
let currentWidth = 0;
|
|
1401
|
+
for (let i = 0; i < moves.length; i++) {
|
|
1402
|
+
if (currentWidth + moves[i].length > maxWidth) {
|
|
1403
|
+
if (moves[i].includes('{')) {
|
|
1404
|
+
currentWidth = wrapComment(currentWidth, moves[i]);
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
// if the current move will push past max_width
|
|
1409
|
+
if (currentWidth + moves[i].length > maxWidth && i !== 0) {
|
|
1410
|
+
// don't end the line with whitespace
|
|
1411
|
+
if (result[result.length - 1] === ' ') {
|
|
1412
|
+
result.pop();
|
|
1413
|
+
}
|
|
1414
|
+
result.push(newline);
|
|
1415
|
+
currentWidth = 0;
|
|
1416
|
+
}
|
|
1417
|
+
else if (i !== 0) {
|
|
1418
|
+
result.push(' ');
|
|
1419
|
+
currentWidth++;
|
|
1420
|
+
}
|
|
1421
|
+
result.push(moves[i]);
|
|
1422
|
+
currentWidth += moves[i].length;
|
|
1423
|
+
}
|
|
1424
|
+
return result.join('');
|
|
1425
|
+
}
|
|
1426
|
+
/*
|
|
1427
|
+
* @deprecated Use `setHeader` and `getHeaders` instead.
|
|
1428
|
+
*/
|
|
1429
|
+
header(...args) {
|
|
1430
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
1431
|
+
if (typeof args[i] === 'string' && typeof args[i + 1] === 'string') {
|
|
1432
|
+
this._header[args[i]] = args[i + 1];
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
return this._header;
|
|
1436
|
+
}
|
|
1437
|
+
setHeader(key, value) {
|
|
1438
|
+
this._header[key] = value;
|
|
1439
|
+
return this._header;
|
|
1440
|
+
}
|
|
1441
|
+
removeHeader(key) {
|
|
1442
|
+
if (key in this._header) {
|
|
1443
|
+
delete this._header[key];
|
|
1444
|
+
return true;
|
|
1445
|
+
}
|
|
1446
|
+
return false;
|
|
1447
|
+
}
|
|
1448
|
+
getHeaders() {
|
|
1449
|
+
return this._header;
|
|
1450
|
+
}
|
|
1451
|
+
loadPgn(pgn, { strict = false, newlineChar = '\r?\n', } = {}) {
|
|
1452
|
+
function mask(str) {
|
|
1453
|
+
return str.replace(/\\/g, '\\');
|
|
1454
|
+
}
|
|
1455
|
+
function parsePgnHeader(header) {
|
|
1456
|
+
const headerObj = {};
|
|
1457
|
+
const headers = header.split(new RegExp(mask(newlineChar)));
|
|
1458
|
+
let key = '';
|
|
1459
|
+
let value = '';
|
|
1460
|
+
for (let i = 0; i < headers.length; i++) {
|
|
1461
|
+
const regex = /^\s*\[\s*([A-Za-z]+)\s*"(.*)"\s*\]\s*$/;
|
|
1462
|
+
key = headers[i].replace(regex, '$1');
|
|
1463
|
+
value = headers[i].replace(regex, '$2');
|
|
1464
|
+
if (key.trim().length > 0) {
|
|
1465
|
+
headerObj[key] = value;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
return headerObj;
|
|
1469
|
+
}
|
|
1470
|
+
// strip whitespace from head/tail of PGN block
|
|
1471
|
+
pgn = pgn.trim();
|
|
1472
|
+
/*
|
|
1473
|
+
* RegExp to split header. Takes advantage of the fact that header and movetext
|
|
1474
|
+
* will always have a blank line between them (ie, two newline_char's). Handles
|
|
1475
|
+
* case where movetext is empty by matching newlineChar until end of string is
|
|
1476
|
+
* matched - effectively trimming from the end extra newlineChar.
|
|
1477
|
+
*
|
|
1478
|
+
* With default newline_char, will equal:
|
|
1479
|
+
* /^(\[((?:\r?\n)|.)*\])((?:\s*\r?\n){2}|(?:\s*\r?\n)*$)/
|
|
1480
|
+
*/
|
|
1481
|
+
const headerRegex = new RegExp('^(\\[((?:' +
|
|
1482
|
+
mask(newlineChar) +
|
|
1483
|
+
')|.)*\\])' +
|
|
1484
|
+
'((?:\\s*' +
|
|
1485
|
+
mask(newlineChar) +
|
|
1486
|
+
'){2}|(?:\\s*' +
|
|
1487
|
+
mask(newlineChar) +
|
|
1488
|
+
')*$)');
|
|
1489
|
+
// If no header given, begin with moves.
|
|
1490
|
+
const headerRegexResults = headerRegex.exec(pgn);
|
|
1491
|
+
const headerString = headerRegexResults
|
|
1492
|
+
? headerRegexResults.length >= 2
|
|
1493
|
+
? headerRegexResults[1]
|
|
1494
|
+
: ''
|
|
1495
|
+
: '';
|
|
1496
|
+
// Put the board in the starting position
|
|
1497
|
+
this.reset();
|
|
1498
|
+
// parse PGN header
|
|
1499
|
+
const headers = parsePgnHeader(headerString);
|
|
1500
|
+
let fen = '';
|
|
1501
|
+
for (const key in headers) {
|
|
1502
|
+
// check to see user is including fen (possibly with wrong tag case)
|
|
1503
|
+
if (key.toLowerCase() === 'fen') {
|
|
1504
|
+
fen = headers[key];
|
|
1505
|
+
}
|
|
1506
|
+
this.header(key, headers[key]);
|
|
1507
|
+
}
|
|
1508
|
+
/*
|
|
1509
|
+
* the permissive parser should attempt to load a fen tag, even if it's the
|
|
1510
|
+
* wrong case and doesn't include a corresponding [SetUp "1"] tag
|
|
1511
|
+
*/
|
|
1512
|
+
if (!strict) {
|
|
1513
|
+
if (fen) {
|
|
1514
|
+
this.load(fen, { preserveHeaders: true });
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
else {
|
|
1518
|
+
/*
|
|
1519
|
+
* strict parser - load the starting position indicated by [Setup '1']
|
|
1520
|
+
* and [FEN position]
|
|
1521
|
+
*/
|
|
1522
|
+
if (headers['SetUp'] === '1') {
|
|
1523
|
+
if (!('FEN' in headers)) {
|
|
1524
|
+
throw new Error('Invalid PGN: FEN tag must be supplied with SetUp tag');
|
|
1525
|
+
}
|
|
1526
|
+
// don't clear the headers when loading
|
|
1527
|
+
this.load(headers['FEN'], { preserveHeaders: true });
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
/*
|
|
1531
|
+
* NB: the regexes below that delete move numbers, recursive annotations,
|
|
1532
|
+
* and numeric annotation glyphs may also match text in comments. To
|
|
1533
|
+
* prevent this, we transform comments by hex-encoding them in place and
|
|
1534
|
+
* decoding them again after the other tokens have been deleted.
|
|
1535
|
+
*
|
|
1536
|
+
* While the spec states that PGN files should be ASCII encoded, we use
|
|
1537
|
+
* {en,de}codeURIComponent here to support arbitrary UTF8 as a convenience
|
|
1538
|
+
* for modern users
|
|
1539
|
+
*/
|
|
1540
|
+
function toHex(s) {
|
|
1541
|
+
return Array.from(s)
|
|
1542
|
+
.map(function (c) {
|
|
1543
|
+
/*
|
|
1544
|
+
* encodeURI doesn't transform most ASCII characters, so we handle
|
|
1545
|
+
* these ourselves
|
|
1546
|
+
*/
|
|
1547
|
+
return c.charCodeAt(0) < 128
|
|
1548
|
+
? c.charCodeAt(0).toString(16)
|
|
1549
|
+
: encodeURIComponent(c).replace(/%/g, '').toLowerCase();
|
|
1550
|
+
})
|
|
1551
|
+
.join('');
|
|
1552
|
+
}
|
|
1553
|
+
function fromHex(s) {
|
|
1554
|
+
return s.length == 0
|
|
1555
|
+
? ''
|
|
1556
|
+
: decodeURIComponent('%' + (s.match(/.{1,2}/g) || []).join('%'));
|
|
1557
|
+
}
|
|
1558
|
+
const encodeComment = function (s) {
|
|
1559
|
+
s = s.replace(new RegExp(mask(newlineChar), 'g'), ' ');
|
|
1560
|
+
return `{${toHex(s.slice(1, s.length - 1))}}`;
|
|
1561
|
+
};
|
|
1562
|
+
const decodeComment = function (s) {
|
|
1563
|
+
if (s.startsWith('{') && s.endsWith('}')) {
|
|
1564
|
+
return fromHex(s.slice(1, s.length - 1));
|
|
1565
|
+
}
|
|
1566
|
+
};
|
|
1567
|
+
// delete header to get the moves
|
|
1568
|
+
let ms = pgn
|
|
1569
|
+
.replace(headerString, '')
|
|
1570
|
+
.replace(
|
|
1571
|
+
// encode comments so they don't get deleted below
|
|
1572
|
+
new RegExp(`({[^}]*})+?|;([^${mask(newlineChar)}]*)`, 'g'), function (_match, bracket, semicolon) {
|
|
1573
|
+
return bracket !== undefined
|
|
1574
|
+
? encodeComment(bracket)
|
|
1575
|
+
: ' ' + encodeComment(`{${semicolon.slice(1)}}`);
|
|
1576
|
+
})
|
|
1577
|
+
.replace(new RegExp(mask(newlineChar), 'g'), ' ');
|
|
1578
|
+
// delete recursive annotation variations
|
|
1579
|
+
const ravRegex = /(\([^()]+\))+?/g;
|
|
1580
|
+
while (ravRegex.test(ms)) {
|
|
1581
|
+
ms = ms.replace(ravRegex, '');
|
|
1582
|
+
}
|
|
1583
|
+
// delete move numbers
|
|
1584
|
+
ms = ms.replace(/\d+\.(\.\.)?/g, '');
|
|
1585
|
+
// delete ... indicating black to move
|
|
1586
|
+
ms = ms.replace(/\.\.\./g, '');
|
|
1587
|
+
/* delete numeric annotation glyphs */
|
|
1588
|
+
ms = ms.replace(/\$\d+/g, '');
|
|
1589
|
+
// trim and get array of moves
|
|
1590
|
+
let moves = ms.trim().split(new RegExp(/\s+/));
|
|
1591
|
+
// delete empty entries
|
|
1592
|
+
moves = moves.filter((move) => move !== '');
|
|
1593
|
+
let result = '';
|
|
1594
|
+
for (let halfMove = 0; halfMove < moves.length; halfMove++) {
|
|
1595
|
+
const comment = decodeComment(moves[halfMove]);
|
|
1596
|
+
if (comment !== undefined) {
|
|
1597
|
+
this._comments[this.fen()] = comment;
|
|
1598
|
+
continue;
|
|
1599
|
+
}
|
|
1600
|
+
const move = this._moveFromSan(moves[halfMove], strict);
|
|
1601
|
+
// invalid move
|
|
1602
|
+
if (move == null) {
|
|
1603
|
+
// was the move an end of game marker
|
|
1604
|
+
if (TERMINATION_MARKERS.indexOf(moves[halfMove]) > -1) {
|
|
1605
|
+
result = moves[halfMove];
|
|
1606
|
+
}
|
|
1607
|
+
else {
|
|
1608
|
+
throw new Error(`Invalid move in PGN: ${moves[halfMove]}`);
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
else {
|
|
1612
|
+
// reset the end of game marker if making a valid move
|
|
1613
|
+
result = '';
|
|
1614
|
+
this._makeMove(move);
|
|
1615
|
+
this._incPositionCount(this.fen());
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
/*
|
|
1619
|
+
* Per section 8.2.6 of the PGN spec, the Result tag pair must match match
|
|
1620
|
+
* the termination marker. Only do this when headers are present, but the
|
|
1621
|
+
* result tag is missing
|
|
1622
|
+
*/
|
|
1623
|
+
if (result && Object.keys(this._header).length && !this._header['Result']) {
|
|
1624
|
+
this.header('Result', result);
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
/*
|
|
1628
|
+
* Convert a move from 0x88 coordinates to Standard Algebraic Notation
|
|
1629
|
+
* (SAN)
|
|
1630
|
+
*
|
|
1631
|
+
* @param {boolean} strict Use the strict SAN parser. It will throw errors
|
|
1632
|
+
* on overly disambiguated moves (see below):
|
|
1633
|
+
*
|
|
1634
|
+
* r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4
|
|
1635
|
+
* 4. ... Nge7 is overly disambiguated because the knight on c6 is pinned
|
|
1636
|
+
* 4. ... Ne7 is technically the valid SAN
|
|
1637
|
+
*/
|
|
1638
|
+
_moveToSan(move, moves) {
|
|
1639
|
+
let output = '';
|
|
1640
|
+
if (move.flags & BITS.KSIDE_CASTLE) {
|
|
1641
|
+
output = 'O-O';
|
|
1642
|
+
}
|
|
1643
|
+
else if (move.flags & BITS.QSIDE_CASTLE) {
|
|
1644
|
+
output = 'O-O-O';
|
|
1645
|
+
}
|
|
1646
|
+
else {
|
|
1647
|
+
if (move.piece !== PAWN) {
|
|
1648
|
+
const disambiguator = getDisambiguator(move, moves);
|
|
1649
|
+
output += move.piece.toUpperCase() + disambiguator;
|
|
1650
|
+
}
|
|
1651
|
+
if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) {
|
|
1652
|
+
if (move.piece === PAWN) {
|
|
1653
|
+
output += algebraic(move.from)[0];
|
|
1654
|
+
}
|
|
1655
|
+
output += 'x';
|
|
1656
|
+
}
|
|
1657
|
+
output += algebraic(move.to);
|
|
1658
|
+
if (move.promotion) {
|
|
1659
|
+
output += '=' + move.promotion.toUpperCase();
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
this._makeMove(move);
|
|
1663
|
+
if (this.isCheck()) {
|
|
1664
|
+
if (this.isCheckmate()) {
|
|
1665
|
+
output += '#';
|
|
1666
|
+
}
|
|
1667
|
+
else {
|
|
1668
|
+
output += '+';
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
this._undoMove();
|
|
1672
|
+
return output;
|
|
1673
|
+
}
|
|
1674
|
+
// convert a move from Standard Algebraic Notation (SAN) to 0x88 coordinates
|
|
1675
|
+
_moveFromSan(move, strict = false) {
|
|
1676
|
+
// strip off any move decorations: e.g Nf3+?! becomes Nf3
|
|
1677
|
+
const cleanMove = strippedSan(move);
|
|
1678
|
+
let pieceType = inferPieceType(cleanMove);
|
|
1679
|
+
let moves = this._moves({ legal: true, piece: pieceType });
|
|
1680
|
+
// strict parser
|
|
1681
|
+
for (let i = 0, len = moves.length; i < len; i++) {
|
|
1682
|
+
if (cleanMove === strippedSan(this._moveToSan(moves[i], moves))) {
|
|
1683
|
+
return moves[i];
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
// the strict parser failed
|
|
1687
|
+
if (strict) {
|
|
1688
|
+
return null;
|
|
1689
|
+
}
|
|
1690
|
+
let piece = undefined;
|
|
1691
|
+
let matches = undefined;
|
|
1692
|
+
let from = undefined;
|
|
1693
|
+
let to = undefined;
|
|
1694
|
+
let promotion = undefined;
|
|
1695
|
+
/*
|
|
1696
|
+
* The default permissive (non-strict) parser allows the user to parse
|
|
1697
|
+
* non-standard chess notations. This parser is only run after the strict
|
|
1698
|
+
* Standard Algebraic Notation (SAN) parser has failed.
|
|
1699
|
+
*
|
|
1700
|
+
* When running the permissive parser, we'll run a regex to grab the piece, the
|
|
1701
|
+
* to/from square, and an optional promotion piece. This regex will
|
|
1702
|
+
* parse common non-standard notation like: Pe2-e4, Rc1c4, Qf3xf7,
|
|
1703
|
+
* f7f8q, b1c3
|
|
1704
|
+
*
|
|
1705
|
+
* NOTE: Some positions and moves may be ambiguous when using the permissive
|
|
1706
|
+
* parser. For example, in this position: 6k1/8/8/B7/8/8/8/BN4K1 w - - 0 1,
|
|
1707
|
+
* the move b1c3 may be interpreted as Nc3 or B1c3 (a disambiguated bishop
|
|
1708
|
+
* move). In these cases, the permissive parser will default to the most
|
|
1709
|
+
* basic interpretation (which is b1c3 parsing to Nc3).
|
|
1710
|
+
*/
|
|
1711
|
+
let overlyDisambiguated = false;
|
|
1712
|
+
matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/);
|
|
1713
|
+
if (matches) {
|
|
1714
|
+
piece = matches[1];
|
|
1715
|
+
from = matches[2];
|
|
1716
|
+
to = matches[3];
|
|
1717
|
+
promotion = matches[4];
|
|
1718
|
+
if (from.length == 1) {
|
|
1719
|
+
overlyDisambiguated = true;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
else {
|
|
1723
|
+
/*
|
|
1724
|
+
* The [a-h]?[1-8]? portion of the regex below handles moves that may be
|
|
1725
|
+
* overly disambiguated (e.g. Nge7 is unnecessary and non-standard when
|
|
1726
|
+
* there is one legal knight move to e7). In this case, the value of
|
|
1727
|
+
* 'from' variable will be a rank or file, not a square.
|
|
1728
|
+
*/
|
|
1729
|
+
matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/);
|
|
1730
|
+
if (matches) {
|
|
1731
|
+
piece = matches[1];
|
|
1732
|
+
from = matches[2];
|
|
1733
|
+
to = matches[3];
|
|
1734
|
+
promotion = matches[4];
|
|
1735
|
+
if (from.length == 1) {
|
|
1736
|
+
overlyDisambiguated = true;
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
pieceType = inferPieceType(cleanMove);
|
|
1741
|
+
moves = this._moves({
|
|
1742
|
+
legal: true,
|
|
1743
|
+
piece: piece ? piece : pieceType,
|
|
1744
|
+
});
|
|
1745
|
+
if (!to) {
|
|
1746
|
+
return null;
|
|
1747
|
+
}
|
|
1748
|
+
for (let i = 0, len = moves.length; i < len; i++) {
|
|
1749
|
+
if (!from) {
|
|
1750
|
+
// if there is no from square, it could be just 'x' missing from a capture
|
|
1751
|
+
if (cleanMove ===
|
|
1752
|
+
strippedSan(this._moveToSan(moves[i], moves)).replace('x', '')) {
|
|
1753
|
+
return moves[i];
|
|
1754
|
+
}
|
|
1755
|
+
// hand-compare move properties with the results from our permissive regex
|
|
1756
|
+
}
|
|
1757
|
+
else if ((!piece || piece.toLowerCase() == moves[i].piece) &&
|
|
1758
|
+
Ox88[from] == moves[i].from &&
|
|
1759
|
+
Ox88[to] == moves[i].to &&
|
|
1760
|
+
(!promotion || promotion.toLowerCase() == moves[i].promotion)) {
|
|
1761
|
+
return moves[i];
|
|
1762
|
+
}
|
|
1763
|
+
else if (overlyDisambiguated) {
|
|
1764
|
+
/*
|
|
1765
|
+
* SPECIAL CASE: we parsed a move string that may have an unneeded
|
|
1766
|
+
* rank/file disambiguator (e.g. Nge7). The 'from' variable will
|
|
1767
|
+
*/
|
|
1768
|
+
const square = algebraic(moves[i].from);
|
|
1769
|
+
if ((!piece || piece.toLowerCase() == moves[i].piece) &&
|
|
1770
|
+
Ox88[to] == moves[i].to &&
|
|
1771
|
+
(from == square[0] || from == square[1]) &&
|
|
1772
|
+
(!promotion || promotion.toLowerCase() == moves[i].promotion)) {
|
|
1773
|
+
return moves[i];
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
return null;
|
|
1778
|
+
}
|
|
1779
|
+
ascii() {
|
|
1780
|
+
let s = ' +------------------------+\n';
|
|
1781
|
+
for (let i = Ox88.a8; i <= Ox88.h1; i++) {
|
|
1782
|
+
// display the rank
|
|
1783
|
+
if (file(i) === 0) {
|
|
1784
|
+
s += ' ' + '87654321'[rank(i)] + ' |';
|
|
1785
|
+
}
|
|
1786
|
+
if (this._board[i]) {
|
|
1787
|
+
const piece = this._board[i].type;
|
|
1788
|
+
const color = this._board[i].color;
|
|
1789
|
+
const symbol = color === WHITE ? piece.toUpperCase() : piece.toLowerCase();
|
|
1790
|
+
s += ' ' + symbol + ' ';
|
|
1791
|
+
}
|
|
1792
|
+
else {
|
|
1793
|
+
s += ' . ';
|
|
1794
|
+
}
|
|
1795
|
+
if ((i + 1) & 0x88) {
|
|
1796
|
+
s += '|\n';
|
|
1797
|
+
i += 8;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
s += ' +------------------------+\n';
|
|
1801
|
+
s += ' a b c d e f g h';
|
|
1802
|
+
return s;
|
|
1803
|
+
}
|
|
1804
|
+
perft(depth) {
|
|
1805
|
+
const moves = this._moves({ legal: false });
|
|
1806
|
+
let nodes = 0;
|
|
1807
|
+
const color = this._turn;
|
|
1808
|
+
for (let i = 0, len = moves.length; i < len; i++) {
|
|
1809
|
+
this._makeMove(moves[i]);
|
|
1810
|
+
if (!this._isKingAttacked(color)) {
|
|
1811
|
+
if (depth - 1 > 0) {
|
|
1812
|
+
nodes += this.perft(depth - 1);
|
|
1813
|
+
}
|
|
1814
|
+
else {
|
|
1815
|
+
nodes++;
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
this._undoMove();
|
|
1819
|
+
}
|
|
1820
|
+
return nodes;
|
|
1821
|
+
}
|
|
1822
|
+
turn() {
|
|
1823
|
+
return this._turn;
|
|
1824
|
+
}
|
|
1825
|
+
board() {
|
|
1826
|
+
const output = [];
|
|
1827
|
+
let row = [];
|
|
1828
|
+
for (let i = Ox88.a8; i <= Ox88.h1; i++) {
|
|
1829
|
+
if (this._board[i] == null) {
|
|
1830
|
+
row.push(null);
|
|
1831
|
+
}
|
|
1832
|
+
else {
|
|
1833
|
+
row.push({
|
|
1834
|
+
square: algebraic(i),
|
|
1835
|
+
type: this._board[i].type,
|
|
1836
|
+
color: this._board[i].color,
|
|
1837
|
+
});
|
|
1838
|
+
}
|
|
1839
|
+
if ((i + 1) & 0x88) {
|
|
1840
|
+
output.push(row);
|
|
1841
|
+
row = [];
|
|
1842
|
+
i += 8;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
return output;
|
|
1846
|
+
}
|
|
1847
|
+
squareColor(square) {
|
|
1848
|
+
if (square in Ox88) {
|
|
1849
|
+
const sq = Ox88[square];
|
|
1850
|
+
return (rank(sq) + file(sq)) % 2 === 0 ? 'light' : 'dark';
|
|
1851
|
+
}
|
|
1852
|
+
return null;
|
|
1853
|
+
}
|
|
1854
|
+
history({ verbose = false } = {}) {
|
|
1855
|
+
const reversedHistory = [];
|
|
1856
|
+
const moveHistory = [];
|
|
1857
|
+
while (this._history.length > 0) {
|
|
1858
|
+
reversedHistory.push(this._undoMove());
|
|
1859
|
+
}
|
|
1860
|
+
while (true) {
|
|
1861
|
+
const move = reversedHistory.pop();
|
|
1862
|
+
if (!move) {
|
|
1863
|
+
break;
|
|
1864
|
+
}
|
|
1865
|
+
if (verbose) {
|
|
1866
|
+
moveHistory.push(new Move$1(this, move));
|
|
1867
|
+
}
|
|
1868
|
+
else {
|
|
1869
|
+
moveHistory.push(this._moveToSan(move, this._moves()));
|
|
1870
|
+
}
|
|
1871
|
+
this._makeMove(move);
|
|
1872
|
+
}
|
|
1873
|
+
return moveHistory;
|
|
1874
|
+
}
|
|
1875
|
+
/*
|
|
1876
|
+
* Keeps track of position occurrence counts for the purpose of repetition
|
|
1877
|
+
* checking. All three methods (`_inc`, `_dec`, and `_get`) trim the
|
|
1878
|
+
* irrelevent information from the fen, initialising new positions, and
|
|
1879
|
+
* removing old positions from the record if their counts are reduced to 0.
|
|
1880
|
+
*/
|
|
1881
|
+
_getPositionCount(fen) {
|
|
1882
|
+
const trimmedFen = trimFen(fen);
|
|
1883
|
+
return this._positionCount[trimmedFen] || 0;
|
|
1884
|
+
}
|
|
1885
|
+
_incPositionCount(fen) {
|
|
1886
|
+
const trimmedFen = trimFen(fen);
|
|
1887
|
+
if (this._positionCount[trimmedFen] === undefined) {
|
|
1888
|
+
this._positionCount[trimmedFen] = 0;
|
|
1889
|
+
}
|
|
1890
|
+
this._positionCount[trimmedFen] += 1;
|
|
1891
|
+
}
|
|
1892
|
+
_decPositionCount(fen) {
|
|
1893
|
+
const trimmedFen = trimFen(fen);
|
|
1894
|
+
if (this._positionCount[trimmedFen] === 1) {
|
|
1895
|
+
delete this._positionCount[trimmedFen];
|
|
1896
|
+
}
|
|
1897
|
+
else {
|
|
1898
|
+
this._positionCount[trimmedFen] -= 1;
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
_pruneComments() {
|
|
1902
|
+
const reversedHistory = [];
|
|
1903
|
+
const currentComments = {};
|
|
1904
|
+
const copyComment = (fen) => {
|
|
1905
|
+
if (fen in this._comments) {
|
|
1906
|
+
currentComments[fen] = this._comments[fen];
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
while (this._history.length > 0) {
|
|
1910
|
+
reversedHistory.push(this._undoMove());
|
|
1911
|
+
}
|
|
1912
|
+
copyComment(this.fen());
|
|
1913
|
+
while (true) {
|
|
1914
|
+
const move = reversedHistory.pop();
|
|
1915
|
+
if (!move) {
|
|
1916
|
+
break;
|
|
1917
|
+
}
|
|
1918
|
+
this._makeMove(move);
|
|
1919
|
+
copyComment(this.fen());
|
|
1920
|
+
}
|
|
1921
|
+
this._comments = currentComments;
|
|
1922
|
+
}
|
|
1923
|
+
getComment() {
|
|
1924
|
+
return this._comments[this.fen()];
|
|
1925
|
+
}
|
|
1926
|
+
setComment(comment) {
|
|
1927
|
+
this._comments[this.fen()] = comment.replace('{', '[').replace('}', ']');
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* @deprecated Renamed to `removeComment` for consistency
|
|
1931
|
+
*/
|
|
1932
|
+
deleteComment() {
|
|
1933
|
+
return this.removeComment();
|
|
1934
|
+
}
|
|
1935
|
+
removeComment() {
|
|
1936
|
+
const comment = this._comments[this.fen()];
|
|
1937
|
+
delete this._comments[this.fen()];
|
|
1938
|
+
return comment;
|
|
1939
|
+
}
|
|
1940
|
+
getComments() {
|
|
1941
|
+
this._pruneComments();
|
|
1942
|
+
return Object.keys(this._comments).map((fen) => {
|
|
1943
|
+
return { fen: fen, comment: this._comments[fen] };
|
|
1944
|
+
});
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* @deprecated Renamed to `removeComments` for consistency
|
|
1948
|
+
*/
|
|
1949
|
+
deleteComments() {
|
|
1950
|
+
return this.removeComments();
|
|
1951
|
+
}
|
|
1952
|
+
removeComments() {
|
|
1953
|
+
this._pruneComments();
|
|
1954
|
+
return Object.keys(this._comments).map((fen) => {
|
|
1955
|
+
const comment = this._comments[fen];
|
|
1956
|
+
delete this._comments[fen];
|
|
1957
|
+
return { fen: fen, comment: comment };
|
|
1958
|
+
});
|
|
1959
|
+
}
|
|
1960
|
+
setCastlingRights(color, rights) {
|
|
1961
|
+
for (const side of [KING, QUEEN]) {
|
|
1962
|
+
if (rights[side] !== undefined) {
|
|
1963
|
+
if (rights[side]) {
|
|
1964
|
+
this._castling[color] |= SIDES[side];
|
|
1965
|
+
}
|
|
1966
|
+
else {
|
|
1967
|
+
this._castling[color] &= ~SIDES[side];
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
this._updateCastlingRights();
|
|
1972
|
+
const result = this.getCastlingRights(color);
|
|
1973
|
+
return ((rights[KING] === undefined || rights[KING] === result[KING]) &&
|
|
1974
|
+
(rights[QUEEN] === undefined || rights[QUEEN] === result[QUEEN]));
|
|
1975
|
+
}
|
|
1976
|
+
getCastlingRights(color) {
|
|
1977
|
+
return {
|
|
1978
|
+
[KING]: (this._castling[color] & SIDES[KING]) !== 0,
|
|
1979
|
+
[QUEEN]: (this._castling[color] & SIDES[QUEEN]) !== 0,
|
|
1980
|
+
};
|
|
1981
|
+
}
|
|
1982
|
+
moveNumber() {
|
|
1983
|
+
return this._moveNumber;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
const animationTime = {
|
|
1988
|
+
'fast': 200,
|
|
1989
|
+
'slow': 600,
|
|
1990
|
+
'normal': 400,
|
|
1991
|
+
'verySlow': 1000,
|
|
1992
|
+
'veryFast': 100
|
|
1993
|
+
};
|
|
1994
|
+
|
|
1995
|
+
const transitionFunctions = {
|
|
1996
|
+
'ease': 'ease',
|
|
1997
|
+
'linear': 'linear',
|
|
1998
|
+
'ease-in': 'ease-in',
|
|
1999
|
+
'ease-out': 'ease-out',
|
|
2000
|
+
'ease-in-out': 'ease-in-out'
|
|
2001
|
+
};
|
|
2002
|
+
|
|
2003
|
+
class ChessboardConfig {
|
|
2004
|
+
constructor(settings) {
|
|
2005
|
+
const defaults = {
|
|
2006
|
+
id: 'board',
|
|
2007
|
+
position: 'start',
|
|
2008
|
+
orientation: 'w',
|
|
2009
|
+
mode: 'normal',
|
|
2010
|
+
size: 'auto',
|
|
2011
|
+
draggable: true,
|
|
2012
|
+
hints: true,
|
|
2013
|
+
clickable: true,
|
|
2014
|
+
movableColors: 'both',
|
|
2015
|
+
moveHighlight: true,
|
|
2016
|
+
overHighlight: true,
|
|
2017
|
+
moveAnimation: 'ease',
|
|
2018
|
+
moveTime: 'fast',
|
|
2019
|
+
dropOffBoard: 'snapback',
|
|
2020
|
+
snapbackTime: 'fast',
|
|
2021
|
+
snapbackAnimation: 'ease',
|
|
2022
|
+
fadeTime: 'fast',
|
|
2023
|
+
fadeAnimation: 'ease',
|
|
2024
|
+
ratio: 0.9,
|
|
2025
|
+
piecesPath: 'https://cdn.jsdelivr.net/npm/@alepot55/chessboardjs/default_pieces',
|
|
2026
|
+
onMove: () => true,
|
|
2027
|
+
onMoveEnd: () => true,
|
|
2028
|
+
onChange: () => true,
|
|
2029
|
+
onDragStart: () => true,
|
|
2030
|
+
onDragMove: () => true,
|
|
2031
|
+
onDrop: () => true,
|
|
2032
|
+
onSnapbackEnd: () => true,
|
|
2033
|
+
whiteSquare: '#f0d9b5',
|
|
2034
|
+
blackSquare: '#b58863',
|
|
2035
|
+
highlight: 'yellow',
|
|
2036
|
+
selectedSquareWhite: '#ababaa',
|
|
2037
|
+
selectedSquareBlack: '#ababaa',
|
|
2038
|
+
movedSquareWhite: '#f1f1a0',
|
|
2039
|
+
movedSquareBlack: '#e9e981',
|
|
2040
|
+
choiceSquare: 'white',
|
|
2041
|
+
coverSquare: 'black',
|
|
2042
|
+
hintColor: '#ababaa'
|
|
2043
|
+
};
|
|
2044
|
+
|
|
2045
|
+
const config = Object.assign({}, defaults, settings);
|
|
2046
|
+
|
|
2047
|
+
this.id_div = config.id;
|
|
2048
|
+
this.position = config.position;
|
|
2049
|
+
this.orientation = config.orientation;
|
|
2050
|
+
this.mode = config.mode;
|
|
2051
|
+
this.dropOffBoard = config.dropOffBoard;
|
|
2052
|
+
this.size = config.size;
|
|
2053
|
+
this.movableColors = config.movableColors;
|
|
2054
|
+
this.moveAnimation = config.moveAnimation;
|
|
2055
|
+
this.snapbackAnimation = config.snapbackAnimation;
|
|
2056
|
+
this.fadeAnimation = config.fadeAnimation;
|
|
2057
|
+
this.piecesPath = config.piecesPath;
|
|
2058
|
+
this.onMove = config.onMove;
|
|
2059
|
+
this.onMoveEnd = config.onMoveEnd;
|
|
2060
|
+
this.onChange = config.onChange;
|
|
2061
|
+
this.onDragStart = config.onDragStart;
|
|
2062
|
+
this.onDragMove = config.onDragMove;
|
|
2063
|
+
this.onDrop = config.onDrop;
|
|
2064
|
+
this.onSnapbackEnd = config.onSnapbackEnd;
|
|
2065
|
+
|
|
2066
|
+
this.hints = this.setBoolean(config.hints);
|
|
2067
|
+
this.clickable = this.setBoolean(config.clickable);
|
|
2068
|
+
this.draggable = this.setBoolean(config.draggable);
|
|
2069
|
+
this.moveHighlight = this.setBoolean(config.moveHighlight);
|
|
2070
|
+
this.overHighlight = this.setBoolean(config.overHighlight);
|
|
2071
|
+
|
|
2072
|
+
this.moveTime = this.setTime(config.moveTime);
|
|
2073
|
+
this.snapbackTime = this.setTime(config.snapbackTime);
|
|
2074
|
+
this.fadeTime = this.setTime(config.fadeTime);
|
|
2075
|
+
|
|
2076
|
+
this.setCSSProperty('pieceRatio', config.ratio);
|
|
2077
|
+
this.setCSSProperty('whiteSquare', config.whiteSquare);
|
|
2078
|
+
this.setCSSProperty('blackSquare', config.blackSquare);
|
|
2079
|
+
this.setCSSProperty('highlightSquare', config.highlight);
|
|
2080
|
+
this.setCSSProperty('selectedSquareWhite', config.selectedSquareWhite);
|
|
2081
|
+
this.setCSSProperty('selectedSquareBlack', config.selectedSquareBlack);
|
|
2082
|
+
this.setCSSProperty('movedSquareWhite', config.movedSquareWhite);
|
|
2083
|
+
this.setCSSProperty('movedSquareBlack', config.movedSquareBlack);
|
|
2084
|
+
this.setCSSProperty('choiceSquare', config.choiceSquare);
|
|
2085
|
+
this.setCSSProperty('coverSquare', config.coverSquare);
|
|
2086
|
+
this.setCSSProperty('hintColor', config.hintColor);
|
|
2087
|
+
|
|
2088
|
+
// Configure modes
|
|
2089
|
+
if (this.mode === 'creative') {
|
|
2090
|
+
this.onlyLegalMoves = false;
|
|
2091
|
+
this.hints = false;
|
|
2092
|
+
} else if (this.mode === 'normal') {
|
|
2093
|
+
this.onlyLegalMoves = true;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
setCSSProperty(property, value) {
|
|
2098
|
+
document.documentElement.style.setProperty(`--${property}`, value);
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
setOrientation(orientation) {
|
|
2102
|
+
this.orientation = orientation;
|
|
2103
|
+
return this;
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
setTime(value) {
|
|
2107
|
+
if (typeof value === 'number') return value;
|
|
2108
|
+
if (value in animationTime) return animationTime[value];
|
|
2109
|
+
throw new Error('Invalid time value');
|
|
2110
|
+
}
|
|
2111
|
+
|
|
2112
|
+
setBoolean(value) {
|
|
2113
|
+
if (typeof value === 'boolean') return value;
|
|
2114
|
+
throw new Error('Invalid boolean value');
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
setTransitionFunction(value) {
|
|
2118
|
+
if (transitionFunctions[value]) return transitionFunctions[value];
|
|
2119
|
+
throw new Error('Invalid transition function');
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
class Piece {
|
|
2124
|
+
constructor(color, type, src, opacity = 1) {
|
|
2125
|
+
this.color = color;
|
|
2126
|
+
this.type = type;
|
|
2127
|
+
this.id = this.getId();
|
|
2128
|
+
this.src = src;
|
|
2129
|
+
this.element = this.createElement(src, opacity);
|
|
2130
|
+
|
|
2131
|
+
this.check();
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
getId() { return this.type + this.color }
|
|
2135
|
+
|
|
2136
|
+
createElement(opacity) {
|
|
2137
|
+
let element = document.createElement("img");
|
|
2138
|
+
element.classList.add("piece");
|
|
2139
|
+
element.id = this.id;
|
|
2140
|
+
element.src = this.src;
|
|
2141
|
+
element.style.opacity = opacity;
|
|
2142
|
+
return element;
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
visible() { this.element.style.opacity = 1; }
|
|
2146
|
+
|
|
2147
|
+
invisible() { this.element.style.opacity = 0; }
|
|
2148
|
+
|
|
2149
|
+
fadeIn(duration, speed, transition_f) {
|
|
2150
|
+
let start = performance.now();
|
|
2151
|
+
let opacity = 0;
|
|
2152
|
+
let piece = this;
|
|
2153
|
+
let fade = function () {
|
|
2154
|
+
let elapsed = performance.now() - start;
|
|
2155
|
+
opacity = transition_f(elapsed, duration, speed);
|
|
2156
|
+
piece.element.style.opacity = opacity;
|
|
2157
|
+
if (elapsed < duration) {
|
|
2158
|
+
requestAnimationFrame(fade);
|
|
2159
|
+
} else {
|
|
2160
|
+
piece.element.style.opacity = 1;
|
|
2161
|
+
}
|
|
2162
|
+
};
|
|
2163
|
+
fade();
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
fadeOut(duration, speed, transition_f) {
|
|
2167
|
+
performance.now();
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
setDrag(f) {
|
|
2171
|
+
this.element.ondragstart = () => false;
|
|
2172
|
+
this.element.onmousedown = f;
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
destroy() {
|
|
2176
|
+
this.element.remove();
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
translate(to, duration, transition_f, speed, callback = null) {
|
|
2180
|
+
|
|
2181
|
+
let sourceRect = this.element.getBoundingClientRect();
|
|
2182
|
+
let targetRect = to.getBoundingClientRect();
|
|
2183
|
+
let x_start = sourceRect.left + sourceRect.width / 2;
|
|
2184
|
+
let y_start = sourceRect.top + sourceRect.height / 2;
|
|
2185
|
+
let x_end = targetRect.left + targetRect.width / 2;
|
|
2186
|
+
let y_end = targetRect.top + targetRect.height / 2;
|
|
2187
|
+
let dx = x_end - x_start;
|
|
2188
|
+
let dy = y_end - y_start;
|
|
2189
|
+
|
|
2190
|
+
let keyframes = [
|
|
2191
|
+
{ transform: 'translate(0, 0)' },
|
|
2192
|
+
{ transform: `translate(${dx}px, ${dy}px)` }
|
|
2193
|
+
];
|
|
2194
|
+
|
|
2195
|
+
if (this.element.animate) {
|
|
2196
|
+
let animation = this.element.animate(keyframes, {
|
|
2197
|
+
duration: duration,
|
|
2198
|
+
easing: 'ease',
|
|
2199
|
+
fill: 'none'
|
|
2200
|
+
});
|
|
2201
|
+
|
|
2202
|
+
animation.onfinish = () => {
|
|
2203
|
+
if (callback) callback();
|
|
2204
|
+
this.element.style = '';
|
|
2205
|
+
};
|
|
2206
|
+
} else {
|
|
2207
|
+
this.element.style.transition = `transform ${duration}ms ease`;
|
|
2208
|
+
this.element.style.transform = `translate(${dx}px, ${dy}px)`;
|
|
2209
|
+
if (callback) callback();
|
|
2210
|
+
this.element.style = '';
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
check() {
|
|
2215
|
+
if (['p', 'r', 'n', 'b', 'q', 'k'].indexOf(this.type) === -1) {
|
|
2216
|
+
throw new Error("Invalid piece type");
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
if (['w', 'b'].indexOf(this.color) === -1) {
|
|
2220
|
+
throw new Error("Invalid piece color");
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
class Square {
|
|
2226
|
+
|
|
2227
|
+
constructor(row, col) {
|
|
2228
|
+
this.row = row;
|
|
2229
|
+
this.col = col;
|
|
2230
|
+
this.id = this.getId();
|
|
2231
|
+
this.element = this.createElement();
|
|
2232
|
+
this.piece = null;
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
getPiece() {
|
|
2236
|
+
return this.piece;
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2239
|
+
opposite() {
|
|
2240
|
+
this.row = 9 - this.row;
|
|
2241
|
+
this.col = 9 - this.col;
|
|
2242
|
+
this.id = this.getId();
|
|
2243
|
+
this.element = this.resetElement();
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
isWhite() {
|
|
2247
|
+
return (this.row + this.col) % 2 === 0;
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
getId() {
|
|
2251
|
+
let letters = 'abcdefgh';
|
|
2252
|
+
let letter = letters[this.col - 1];
|
|
2253
|
+
return letter + this.row;
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
resetElement() {
|
|
2257
|
+
this.element.id = this.id;
|
|
2258
|
+
this.element.className = '';
|
|
2259
|
+
this.element.classList.add('square');
|
|
2260
|
+
this.element.classList.add(this.isWhite() ? 'whiteSquare' : 'blackSquare');
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
createElement() {
|
|
2264
|
+
let element = document.createElement('div');
|
|
2265
|
+
element.id = this.id;
|
|
2266
|
+
element.classList.add('square');
|
|
2267
|
+
element.classList.add(this.isWhite() ? 'whiteSquare' : 'blackSquare');
|
|
2268
|
+
return element;
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
getElement() {
|
|
2272
|
+
return this.element;
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
getBoundingClientRect() {
|
|
2276
|
+
return this.element.getBoundingClientRect();
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
removePiece() {
|
|
2280
|
+
this.element.removeChild(this.piece.element);
|
|
2281
|
+
const piece = this.piece;
|
|
2282
|
+
this.piece = null;
|
|
2283
|
+
return piece;
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
addEventListener(event, callback) {
|
|
2287
|
+
this.element.addEventListener(event, callback);
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
putPiece(piece) {
|
|
2291
|
+
this.piece = piece;
|
|
2292
|
+
this.element.appendChild(piece.element);
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
putHint(catchable) {
|
|
2296
|
+
if (this.element.querySelector('.hint')) {
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
let hint = document.createElement("div");
|
|
2300
|
+
hint.classList.add('hint');
|
|
2301
|
+
this.element.appendChild(hint);
|
|
2302
|
+
if (catchable) {
|
|
2303
|
+
hint.classList.add('catchable');
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
removeHint() {
|
|
2308
|
+
let hint = this.element.querySelector('.hint');
|
|
2309
|
+
if (hint) {
|
|
2310
|
+
this.element.removeChild(hint);
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
select() {
|
|
2315
|
+
this.element.classList.add(this.isWhite() ? 'selectedSquareWhite' : 'selectedSquareBlack');
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
deselect() {
|
|
2319
|
+
this.element.classList.remove('selectedSquareWhite');
|
|
2320
|
+
this.element.classList.remove('selectedSquareBlack');
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
moved() {
|
|
2324
|
+
this.element.classList.add(this.isWhite() ? 'movedSquareWhite' : 'movedSquareBlack');
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
unmoved() {
|
|
2328
|
+
this.element.classList.remove('movedSquareWhite');
|
|
2329
|
+
this.element.classList.remove('movedSquareBlack');
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
highlight() {
|
|
2333
|
+
this.element.classList.add('highlighted');
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
dehighlight() {
|
|
2337
|
+
this.element.classList.remove('highlighted');
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
putCover(callback) {
|
|
2341
|
+
let cover = document.createElement("div");
|
|
2342
|
+
cover.classList.add('square');
|
|
2343
|
+
cover.classList.add('cover');
|
|
2344
|
+
this.element.appendChild(cover);
|
|
2345
|
+
cover.addEventListener('click', (e) => {
|
|
2346
|
+
e.stopPropagation();
|
|
2347
|
+
callback();
|
|
2348
|
+
});
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
removeCover() {
|
|
2352
|
+
let cover = this.element.querySelector('.cover');
|
|
2353
|
+
if (cover) {
|
|
2354
|
+
this.element.removeChild(cover);
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
|
|
2358
|
+
putPromotion(src, callback) {
|
|
2359
|
+
let choice = document.createElement("div");
|
|
2360
|
+
choice.classList.add('square');
|
|
2361
|
+
choice.classList.add('choice');
|
|
2362
|
+
this.element.appendChild(choice);
|
|
2363
|
+
let img = document.createElement("img");
|
|
2364
|
+
img.classList.add("piece");
|
|
2365
|
+
img.classList.add("choicable");
|
|
2366
|
+
img.src = src;
|
|
2367
|
+
choice.appendChild(img);
|
|
2368
|
+
choice.addEventListener('click', (e) => {
|
|
2369
|
+
e.stopPropagation();
|
|
2370
|
+
callback();
|
|
2371
|
+
});
|
|
2372
|
+
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
removePromotion() {
|
|
2376
|
+
let choice = this.element.querySelector('.choice');
|
|
2377
|
+
if (choice) {
|
|
2378
|
+
choice.removeChild(choice.firstChild);
|
|
2379
|
+
this.element.removeChild(choice);
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
destroy() {
|
|
2384
|
+
this.element.remove();
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
hasPiece() {
|
|
2388
|
+
return this.piece !== null;
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
getColor() {
|
|
2392
|
+
return this.piece.getColor();
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
check() {
|
|
2396
|
+
if (this.row < 1 || this.row > 8) {
|
|
2397
|
+
throw new Error("Invalid square: row is out of bounds");
|
|
2398
|
+
}
|
|
2399
|
+
if (this.col < 1 || this.col > 8) {
|
|
2400
|
+
throw new Error("Invalid square: col is out of bounds");
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
class Move {
|
|
2407
|
+
|
|
2408
|
+
constructor(from, to, promotion = null, check = false) {
|
|
2409
|
+
this.piece = from.getPiece();
|
|
2410
|
+
this.from = from;
|
|
2411
|
+
this.to = to;
|
|
2412
|
+
this.promotion = promotion;
|
|
2413
|
+
|
|
2414
|
+
if (check) this.check();
|
|
2415
|
+
}
|
|
2416
|
+
|
|
2417
|
+
hasPromotion() {
|
|
2418
|
+
return this.promotion !== null;
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
setPromotion(promotion) {
|
|
2422
|
+
this.promotion = promotion;
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
check() {
|
|
2426
|
+
if (this.piece === null) {
|
|
2427
|
+
console.log(this);
|
|
2428
|
+
throw new Error("Invalid move: piece is null");
|
|
2429
|
+
}
|
|
2430
|
+
if (!(this.piece instanceof Piece)) {
|
|
2431
|
+
throw new Error("Invalid move: piece is not an instance of Piece");
|
|
2432
|
+
}
|
|
2433
|
+
if (['q', 'r', 'b', 'n', null].indexOf(this.promotion) === -1) {
|
|
2434
|
+
throw new Error("Invalid move: promotion is not valid");
|
|
2435
|
+
}
|
|
2436
|
+
if (!(this.from instanceof Square)) {
|
|
2437
|
+
throw new Error("Invalid move: from is not an instance of Square");
|
|
2438
|
+
}
|
|
2439
|
+
if (!(this.to instanceof Square)) {
|
|
2440
|
+
throw new Error("Invalid move: to is not an instance of Square");
|
|
2441
|
+
}
|
|
2442
|
+
if (!this.to) {
|
|
2443
|
+
throw new Error("Invalid move: to is null or undefined");
|
|
2444
|
+
}
|
|
2445
|
+
if (!this.from) {
|
|
2446
|
+
throw new Error("Invalid move: from is null or undefined");
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
isLegal(game) {
|
|
2451
|
+
let destinations = game.moves({ square: this.from.id, verbose: true }).map(move => move.to);
|
|
2452
|
+
return destinations.indexOf(this.to.id) !== -1;
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
class Chessboard {
|
|
2459
|
+
|
|
2460
|
+
standard_positions = {
|
|
2461
|
+
'start': 'start',
|
|
2462
|
+
'default': 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
|
|
2463
|
+
}
|
|
2464
|
+
|
|
2465
|
+
error_messages = {
|
|
2466
|
+
'invalid_position': 'Invalid position - ',
|
|
2467
|
+
'invalid_id_div': 'Board id not found - ',
|
|
2468
|
+
'invalid_value': 'Invalid value - ',
|
|
2469
|
+
'invalid_piece': 'Invalid piece - ',
|
|
2470
|
+
'invalid_square': 'Invalid square - ',
|
|
2471
|
+
'invalid_fen': 'Invalid fen - ',
|
|
2472
|
+
'invalid_orientation': 'Invalid orientation - ',
|
|
2473
|
+
'invalid_color': 'Invalid color - ',
|
|
2474
|
+
'invalid_mode': 'Invalid mode - ',
|
|
2475
|
+
'invalid_dropOffBoard': 'Invalid dropOffBoard - ',
|
|
2476
|
+
'invalid_snapbackTime': 'Invalid snapbackTime - ',
|
|
2477
|
+
'invalid_snapbackAnimation': 'Invalid snapbackAnimation - ',
|
|
2478
|
+
'invalid_fadeTime': 'Invalid fadeTime - ',
|
|
2479
|
+
'invalid_fadeAnimation': 'Invalid fadeAnimation - ',
|
|
2480
|
+
'invalid_ratio': 'Invalid ratio - ',
|
|
2481
|
+
'invalid_piecesPath': 'Invalid piecesPath - ',
|
|
2482
|
+
'invalid_onMove': 'Invalid onMove - ',
|
|
2483
|
+
'invalid_onMoveEnd': 'Invalid onMoveEnd - ',
|
|
2484
|
+
'invalid_onChange': 'Invalid onChange - ',
|
|
2485
|
+
'invalid_onDragStart': 'Invalid onDragStart - ',
|
|
2486
|
+
'invalid_onDragMove': 'Invalid onDragMove - ',
|
|
2487
|
+
'invalid_onDrop': 'Invalid onDrop - ',
|
|
2488
|
+
'invalid_onSnapbackEnd': 'Invalid onSnapbackEnd - ',
|
|
2489
|
+
'invalid_whiteSquare': 'Invalid whiteSquare - ',
|
|
2490
|
+
'invalid_blackSquare': 'Invalid blackSquare - ',
|
|
2491
|
+
'invalid_highlight': 'Invalid highlight - ',
|
|
2492
|
+
'invalid_selectedSquareWhite': 'Invalid selectedSquareWhite - ',
|
|
2493
|
+
'invalid_selectedSquareBlack': 'Invalid selectedSquareBlack - ',
|
|
2494
|
+
'invalid_movedSquareWhite': 'Invalid movedSquareWhite - ',
|
|
2495
|
+
'invalid_movedSquareBlack': 'Invalid movedSquareBlack - ',
|
|
2496
|
+
'invalid_choiceSquare': 'Invalid choiceSquare - ',
|
|
2497
|
+
'invalid_coverSquare': 'Invalid coverSquare - ',
|
|
2498
|
+
'invalid_hintColor': 'Invalid hintColor - ',
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
constructor(config) {
|
|
2502
|
+
this.config = new ChessboardConfig(config);
|
|
2503
|
+
this.init();
|
|
2504
|
+
}
|
|
2505
|
+
|
|
2506
|
+
// Build
|
|
2507
|
+
|
|
2508
|
+
init() {
|
|
2509
|
+
this.initParams();
|
|
2510
|
+
this.buildGame(this.config.position);
|
|
2511
|
+
this.buildBoard();
|
|
2512
|
+
this.buildSquares();
|
|
2513
|
+
this.addListeners();
|
|
2514
|
+
this.updateBoardPieces();
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
initParams() {
|
|
2518
|
+
this.board = null;
|
|
2519
|
+
this.squares = {};
|
|
2520
|
+
this.promoting = false;
|
|
2521
|
+
this.clicked = null;
|
|
2522
|
+
this.movesHistory = [];
|
|
2523
|
+
this.mosseIndietro = [];
|
|
2524
|
+
this.clicked = null;
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
buildGame(position) {
|
|
2528
|
+
if (typeof position === 'object') {
|
|
2529
|
+
this.game = new Chess('start');
|
|
2530
|
+
Object.entries(position).forEach(([square, [type, color]]) => {
|
|
2531
|
+
this.game.put({ type, color }, square);
|
|
2532
|
+
});
|
|
2533
|
+
} else if (Object.values(this.standard_positions).includes(position)) {
|
|
2534
|
+
if (position === 'start') this.game = new Chess();
|
|
2535
|
+
else this.game = new Chess(this.standard_positions[position]);
|
|
2536
|
+
} else if (validateFen(position)) {
|
|
2537
|
+
this.game = new Chess(position);
|
|
2538
|
+
} else {
|
|
2539
|
+
throw new Error(this.error_messages['invalid_position'] + position);
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2543
|
+
buildBoard() {
|
|
2544
|
+
this.board = document.getElementById(this.config.id_div);
|
|
2545
|
+
if (!this.board) {
|
|
2546
|
+
throw new Error(this.error_messages['invalid_id_div'] + this.config.id_div);
|
|
2547
|
+
}
|
|
2548
|
+
this.resize(this.config.size);
|
|
2549
|
+
this.board.className = "board";
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
realCoord(row, col) {
|
|
2553
|
+
if (this.isWhiteOriented()) row = 7 - row;
|
|
2554
|
+
else col = 7 - col;
|
|
2555
|
+
return [row + 1, col + 1];
|
|
2556
|
+
}
|
|
2557
|
+
|
|
2558
|
+
buildSquares() {
|
|
2559
|
+
|
|
2560
|
+
for (let row = 0; row < 8; row++) {
|
|
2561
|
+
for (let col = 0; col < 8; col++) {
|
|
2562
|
+
|
|
2563
|
+
let [square_row, square_col] = this.realCoord(row, col);
|
|
2564
|
+
let square = new Square(square_row, square_col);
|
|
2565
|
+
this.squares[square.getId()] = square;
|
|
2566
|
+
|
|
2567
|
+
this.board.appendChild(square.element);
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
|
|
2572
|
+
removeBoard() {
|
|
2573
|
+
|
|
2574
|
+
this.board.innerHTML = '';
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
// Pieces
|
|
2578
|
+
|
|
2579
|
+
getPiecePath(piece) {
|
|
2580
|
+
if (typeof this.config.piecesPath === 'string')
|
|
2581
|
+
return this.config.piecesPath + '/' + piece + '.svg';
|
|
2582
|
+
else if (typeof this.config.piecesPath === 'object')
|
|
2583
|
+
return this.config.piecesPath[piece];
|
|
2584
|
+
else if (typeof this.config.piecesPath === 'function')
|
|
2585
|
+
return this.config.piecesPath(piece);
|
|
2586
|
+
else
|
|
2587
|
+
throw new Error(this.error_messages['invalid_piecesPath']);
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
colorPiece(square) {
|
|
2591
|
+
let piece = this.piece(square);
|
|
2592
|
+
return piece ? piece[1] : null;
|
|
2593
|
+
}
|
|
2594
|
+
|
|
2595
|
+
movePiece(piece, to, duration, callback) {
|
|
2596
|
+
piece.translate(to, duration, this.transitionTimingFunction, this.config.moveAnimation, callback);
|
|
2597
|
+
}
|
|
2598
|
+
|
|
2599
|
+
translatePiece(move, removeTo, animate, callback = null) {
|
|
2600
|
+
|
|
2601
|
+
if (removeTo) this.removePieceFromSquare(move.to, false);
|
|
2602
|
+
|
|
2603
|
+
let change_square = () => {
|
|
2604
|
+
move.from.removePiece();
|
|
2605
|
+
move.to.putPiece(move.piece);
|
|
2606
|
+
move.piece.setDrag(this.dragFunction(move.to, move.piece));
|
|
2607
|
+
if (callback) callback();
|
|
2608
|
+
};
|
|
2609
|
+
|
|
2610
|
+
let duration = animate ? this.config.moveTime : 0;
|
|
2611
|
+
|
|
2612
|
+
this.movePiece(move.piece, move.to, duration, change_square);
|
|
2613
|
+
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
snapbackPiece(square, animate) {
|
|
2617
|
+
let move = new Move(square, square);
|
|
2618
|
+
this.translatePiece(move, false, animate);
|
|
2619
|
+
}
|
|
2620
|
+
|
|
2621
|
+
convertSquare(square) {
|
|
2622
|
+
if (square instanceof Square) return square;
|
|
2623
|
+
if (typeof square === 'string' && this.squares[square]) return this.squares[square];
|
|
2624
|
+
throw new Error('Invalid square value');
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
removePieceFromSquare(square, fade = true) {
|
|
2628
|
+
|
|
2629
|
+
square = this.convertSquare(square);
|
|
2630
|
+
square.check();
|
|
2631
|
+
|
|
2632
|
+
let piece = square.piece;
|
|
2633
|
+
|
|
2634
|
+
if (!piece) throw Error('Square has no piece to remove.')
|
|
2635
|
+
|
|
2636
|
+
if (fade) piece.fadeOut(
|
|
2637
|
+
this.config.fadeTime,
|
|
2638
|
+
this.config.fadeAnimation,
|
|
2639
|
+
this.transitionTimingFunction);
|
|
2640
|
+
|
|
2641
|
+
square.removePiece();
|
|
2642
|
+
|
|
2643
|
+
return piece;
|
|
2644
|
+
}
|
|
2645
|
+
|
|
2646
|
+
dragFunction(square, piece) {
|
|
2647
|
+
|
|
2648
|
+
return (event) => {
|
|
2649
|
+
|
|
2650
|
+
event.preventDefault();
|
|
2651
|
+
|
|
2652
|
+
if (!this.config.draggable || !piece) return;
|
|
2653
|
+
if (!this.config.onDragStart(square, piece)) return;
|
|
2654
|
+
|
|
2655
|
+
let prec;
|
|
2656
|
+
let from = square;
|
|
2657
|
+
let to = square;
|
|
2658
|
+
|
|
2659
|
+
const img = piece.element;
|
|
2660
|
+
|
|
2661
|
+
if (!this.canMove(from)) return;
|
|
2662
|
+
if (!this.config.clickable) this.clicked = null;
|
|
2663
|
+
if (this.onClick(from)) return;
|
|
2664
|
+
|
|
2665
|
+
img.style.position = 'absolute';
|
|
2666
|
+
img.style.zIndex = 100;
|
|
2667
|
+
|
|
2668
|
+
const moveAt = (pageX, pageY) => {
|
|
2669
|
+
const halfWidth = img.offsetWidth / 2;
|
|
2670
|
+
const halfHeight = img.offsetHeight / 2;
|
|
2671
|
+
img.style.left = `${pageX - halfWidth}px`;
|
|
2672
|
+
img.style.top = `${pageY - halfHeight}px`;
|
|
2673
|
+
return true;
|
|
2674
|
+
};
|
|
2675
|
+
|
|
2676
|
+
const onMouseMove = (event) => {
|
|
2677
|
+
if (!moveAt(event.pageX, event.pageY)) ;
|
|
2678
|
+
|
|
2679
|
+
const boardRect = this.board.getBoundingClientRect();
|
|
2680
|
+
const { offsetWidth: boardWidth, offsetHeight: boardHeight } = this.board;
|
|
2681
|
+
const x = event.clientX - boardRect.left;
|
|
2682
|
+
const y = event.clientY - boardRect.top;
|
|
2683
|
+
|
|
2684
|
+
let newTo = null;
|
|
2685
|
+
if (x >= 0 && x <= boardWidth && y >= 0 && y <= boardHeight) {
|
|
2686
|
+
const col = Math.floor(x / (boardWidth / 8));
|
|
2687
|
+
const row = Math.floor(y / (boardHeight / 8));
|
|
2688
|
+
newTo = this.squares[this.getSquareID(row, col)];
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
to = newTo;
|
|
2692
|
+
this.config.onDragMove(from, to, piece);
|
|
2693
|
+
|
|
2694
|
+
if (to !== prec) {
|
|
2695
|
+
to?.highlight();
|
|
2696
|
+
prec?.dehighlight();
|
|
2697
|
+
prec = to;
|
|
2698
|
+
}
|
|
2699
|
+
};
|
|
2700
|
+
|
|
2701
|
+
const onMouseUp = () => {
|
|
2702
|
+
prec?.dehighlight();
|
|
2703
|
+
document.removeEventListener('mousemove', onMouseMove);
|
|
2704
|
+
window.removeEventListener('mouseup', onMouseUp);
|
|
2705
|
+
img.style.zIndex = 20;
|
|
2706
|
+
|
|
2707
|
+
const dropResult = this.config.onDrop(from, to, piece);
|
|
2708
|
+
const isTrashDrop = !to && (this.config.dropOffBoard === 'trash' || dropResult === 'trash');
|
|
2709
|
+
|
|
2710
|
+
if (isTrashDrop) {
|
|
2711
|
+
this.allSquares("unmoved");
|
|
2712
|
+
this.allSquares('removeHint');
|
|
2713
|
+
from.deselect();
|
|
2714
|
+
this.remove(from);
|
|
2715
|
+
} else if (!to || !this.onClick(to, true)) {
|
|
2716
|
+
this.snapbackPiece(from, !this.promoting);
|
|
2717
|
+
this.config.onSnapbackEnd(from, piece);
|
|
2718
|
+
}
|
|
2719
|
+
};
|
|
2720
|
+
|
|
2721
|
+
window.addEventListener('mouseup', onMouseUp, { once: true });
|
|
2722
|
+
document.addEventListener('mousemove', onMouseMove);
|
|
2723
|
+
img.addEventListener('mouseup', onMouseUp, { once: true });
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
convertPiece(piece) {
|
|
2728
|
+
if (piece instanceof Piece) return piece;
|
|
2729
|
+
if (typeof piece === 'string') {
|
|
2730
|
+
let [type, color] = piece.split('');
|
|
2731
|
+
return new Piece(color, type, this.getPiecePath(piece));
|
|
2732
|
+
}
|
|
2733
|
+
throw new Error(this.error_messages['invalid_piece'] + piece);
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
addPieceOnSquare(square, piece, fade = true) {
|
|
2737
|
+
|
|
2738
|
+
square.putPiece(piece);
|
|
2739
|
+
piece.setDrag(this.dragFunction(square, piece));
|
|
2740
|
+
|
|
2741
|
+
if (fade) piece.fadeIn(
|
|
2742
|
+
this.config.fadeTime,
|
|
2743
|
+
this.config.fadeAnimation,
|
|
2744
|
+
this.transitionTimingFunction
|
|
2745
|
+
);
|
|
2746
|
+
|
|
2747
|
+
piece.visible();
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2750
|
+
updateBoardPieces(animation = false) {
|
|
2751
|
+
let { updatedFlags, escapeFlags, movableFlags, pendingTranslations } = this.prepareBoardUpdateData();
|
|
2752
|
+
|
|
2753
|
+
this.identifyPieceTranslations(updatedFlags, escapeFlags, movableFlags, pendingTranslations);
|
|
2754
|
+
|
|
2755
|
+
this.executePieceTranslations(pendingTranslations, escapeFlags, animation);
|
|
2756
|
+
|
|
2757
|
+
this.processRemainingPieceUpdates(updatedFlags, animation);
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
prepareBoardUpdateData() {
|
|
2761
|
+
let updatedFlags = {};
|
|
2762
|
+
let escapeFlags = {};
|
|
2763
|
+
let movableFlags = {};
|
|
2764
|
+
let pendingTranslations = [];
|
|
2765
|
+
|
|
2766
|
+
for (let squareId in this.squares) {
|
|
2767
|
+
let cellPiece = this.squares[squareId].piece;
|
|
2768
|
+
let cellPieceId = cellPiece ? cellPiece.getId() : null;
|
|
2769
|
+
updatedFlags[squareId] = this.piece(squareId) === cellPieceId;
|
|
2770
|
+
escapeFlags[squareId] = false;
|
|
2771
|
+
movableFlags[squareId] = cellPiece ? this.piece(squareId) !== cellPieceId : false;
|
|
2772
|
+
}
|
|
2773
|
+
|
|
2774
|
+
return { updatedFlags, escapeFlags, movableFlags, pendingTranslations };
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2777
|
+
identifyPieceTranslations(updatedFlags, escapeFlags, movableFlags, pendingTranslations) {
|
|
2778
|
+
Object.values(this.squares).forEach(targetSquare => {
|
|
2779
|
+
const newPieceId = this.piece(targetSquare.id);
|
|
2780
|
+
const newPiece = newPieceId && this.convertPiece(newPieceId);
|
|
2781
|
+
const currentPiece = targetSquare.piece;
|
|
2782
|
+
const currentPieceId = currentPiece ? currentPiece.getId() : null;
|
|
2783
|
+
|
|
2784
|
+
if (currentPieceId === newPieceId || updatedFlags[targetSquare.id]) return;
|
|
2785
|
+
|
|
2786
|
+
this.evaluateTranslationCandidates(
|
|
2787
|
+
targetSquare,
|
|
2788
|
+
newPiece,
|
|
2789
|
+
currentPiece,
|
|
2790
|
+
updatedFlags,
|
|
2791
|
+
escapeFlags,
|
|
2792
|
+
movableFlags,
|
|
2793
|
+
pendingTranslations
|
|
2794
|
+
);
|
|
2795
|
+
});
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
evaluateTranslationCandidates(targetSquare, newPiece, oldPiece, updatedFlags, escapeFlags, movableFlags, pendingTranslations) {
|
|
2799
|
+
if (!newPiece) return;
|
|
2800
|
+
const newPieceId = newPiece.getId();
|
|
2801
|
+
|
|
2802
|
+
for (const sourceSquare of Object.values(this.squares)) {
|
|
2803
|
+
if (sourceSquare.id === targetSquare.id || updatedFlags[targetSquare.id]) continue;
|
|
2804
|
+
|
|
2805
|
+
const sourcePiece = sourceSquare.piece;
|
|
2806
|
+
if (!sourcePiece || !movableFlags[sourceSquare.id] || this.isPiece(newPieceId, sourceSquare.id)) continue;
|
|
2807
|
+
|
|
2808
|
+
if (sourcePiece.id === newPieceId) {
|
|
2809
|
+
this.handleTranslationMovement(targetSquare, sourceSquare, oldPiece, sourcePiece, updatedFlags, escapeFlags, movableFlags, pendingTranslations);
|
|
2810
|
+
break;
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
handleTranslationMovement(targetSquare, sourceSquare, oldPiece, currentSource, updatedFlags, escapeFlags, movableFlags, pendingTranslations) {
|
|
2816
|
+
// Verifica il caso specifico "en passant"
|
|
2817
|
+
let lastMove = this.lastMove();
|
|
2818
|
+
if (!oldPiece && lastMove && lastMove['captured'] === 'p') {
|
|
2819
|
+
this.removePieceFromSquare(this.squares[targetSquare.id[0] + sourceSquare.id[1]]);
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
pendingTranslations.push([currentSource, sourceSquare, targetSquare]);
|
|
2823
|
+
|
|
2824
|
+
if (!this.piece(sourceSquare.id)) updatedFlags[sourceSquare.id] = true;
|
|
2825
|
+
|
|
2826
|
+
escapeFlags[sourceSquare.id] = true;
|
|
2827
|
+
movableFlags[sourceSquare.id] = false;
|
|
2828
|
+
updatedFlags[targetSquare.id] = true;
|
|
2829
|
+
}
|
|
2830
|
+
|
|
2831
|
+
executePieceTranslations(pendingTranslations, escapeFlags, animation) {
|
|
2832
|
+
for (let [_, sourceSquare, targetSquare] of pendingTranslations) {
|
|
2833
|
+
console.log('executing translation: ', sourceSquare.id, targetSquare.id);
|
|
2834
|
+
let removeTarget = !escapeFlags[targetSquare.id] && targetSquare.piece;
|
|
2835
|
+
let moveObj = new Move(sourceSquare, targetSquare);
|
|
2836
|
+
this.translatePiece(moveObj, removeTarget, animation);
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
|
|
2840
|
+
// Gestisce gli aggiornamenti residui per ogni cella che non è ancora stata correttamente aggiornata
|
|
2841
|
+
processRemainingPieceUpdates(updatedFlags, animation) {
|
|
2842
|
+
for (const square of Object.values(this.squares)) {
|
|
2843
|
+
let newPieceId = this.piece(square.id);
|
|
2844
|
+
let newPiece = newPieceId ? this.convertPiece(newPieceId) : null;
|
|
2845
|
+
let currentPiece = square.piece;
|
|
2846
|
+
let currentPieceId = currentPiece ? currentPiece.getId() : null;
|
|
2847
|
+
|
|
2848
|
+
if (currentPieceId !== newPieceId && !updatedFlags[square.id]) {
|
|
2849
|
+
this.updateSinglePiece(square, newPiece, updatedFlags, animation);
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
|
|
2854
|
+
// Aggiorna il pezzo in una cella specifica. Gestisce anche il caso di promozione
|
|
2855
|
+
updateSinglePiece(square, newPiece, updatedFlags, animation) {
|
|
2856
|
+
if (!updatedFlags[square.id]) {
|
|
2857
|
+
let lastMove = this.lastMove();
|
|
2858
|
+
|
|
2859
|
+
if (lastMove?.promotion) {
|
|
2860
|
+
if (lastMove['to'] === square.id) {
|
|
2861
|
+
|
|
2862
|
+
let move = new Move(this.squares[lastMove['from']], square);
|
|
2863
|
+
this.translatePiece(move, true, animation
|
|
2864
|
+
, () => {
|
|
2865
|
+
move.to.removePiece();
|
|
2866
|
+
this.addPieceOnSquare(square, newPiece);
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
} else {
|
|
2870
|
+
if (square.piece) this.removePieceFromSquare(square);
|
|
2871
|
+
if (newPiece) this.addPieceOnSquare(square, newPiece);
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
|
|
2876
|
+
isPiece(piece, square) { return this.piece(square) === piece }
|
|
2877
|
+
|
|
2878
|
+
// Listeners
|
|
2879
|
+
|
|
2880
|
+
addListeners() {
|
|
2881
|
+
for (const square of Object.values(this.squares)) {
|
|
2882
|
+
|
|
2883
|
+
let piece = square.piece;
|
|
2884
|
+
|
|
2885
|
+
square.element.addEventListener("mouseover", (e) => {
|
|
2886
|
+
if (!this.clicked) this.hintMoves(square);
|
|
2887
|
+
});
|
|
2888
|
+
square.element.addEventListener("mouseout", (e) => {
|
|
2889
|
+
if (!this.clicked) this.dehintMoves(square);
|
|
2890
|
+
});
|
|
2891
|
+
|
|
2892
|
+
const handleClick = (e) => {
|
|
2893
|
+
e.stopPropagation();
|
|
2894
|
+
if (this.config.clickable && (!piece || this.config.onlyLegalMoves)) this.onClick(square);
|
|
2895
|
+
};
|
|
2896
|
+
|
|
2897
|
+
square.element.addEventListener("click", handleClick);
|
|
2898
|
+
square.element.addEventListener("touch", handleClick);
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
|
|
2902
|
+
onClick(square, animation = this.config.moveAnimation) {
|
|
2903
|
+
|
|
2904
|
+
if (square.id === this.clicked?.id) return false;
|
|
2905
|
+
|
|
2906
|
+
let from = this.clicked;
|
|
2907
|
+
this.clicked = null;
|
|
2908
|
+
|
|
2909
|
+
let promotion = null;
|
|
2910
|
+
|
|
2911
|
+
if (this.promoting) {
|
|
2912
|
+
if (this.promoting === 'none') from = null;
|
|
2913
|
+
else promotion = this.promoting;
|
|
2914
|
+
|
|
2915
|
+
this.promoting = false;
|
|
2916
|
+
this.allSquares("removePromotion");
|
|
2917
|
+
this.allSquares("removeCover");
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2920
|
+
if (!from) {
|
|
2921
|
+
|
|
2922
|
+
if (this.canMove(square)) {
|
|
2923
|
+
square.select();
|
|
2924
|
+
this.hintMoves(square);
|
|
2925
|
+
this.clicked = square;
|
|
2926
|
+
}
|
|
2927
|
+
|
|
2928
|
+
return false;
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
if (!this.canMove(from)) return false;
|
|
2932
|
+
|
|
2933
|
+
let move = new Move(from, square, promotion);
|
|
2934
|
+
|
|
2935
|
+
move.from.deselect();
|
|
2936
|
+
this.allSquares("removeHint");
|
|
2937
|
+
|
|
2938
|
+
if (this.config.onlyLegalMoves && !move.isLegal(this.game)) return false;
|
|
2939
|
+
|
|
2940
|
+
if (!move.hasPromotion() && this.promote(move)) return false;
|
|
2941
|
+
|
|
2942
|
+
if (this.config.onMove(move)) {
|
|
2943
|
+
this.move(move, animation);
|
|
2944
|
+
return true;
|
|
2945
|
+
}
|
|
2946
|
+
|
|
2947
|
+
return false;
|
|
2948
|
+
}
|
|
2949
|
+
|
|
2950
|
+
// Hint
|
|
2951
|
+
|
|
2952
|
+
hint(square) {
|
|
2953
|
+
if (!this.config.hints || !this.squares[square]) return;
|
|
2954
|
+
this.squares[square].putHint(this.colorPiece(square) && this.colorPiece(square) !== this.turn());
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
hintMoves(square) {
|
|
2958
|
+
if (!this.canMove(square)) return;
|
|
2959
|
+
let mosse = this.game.moves({ square: square.id, verbose: true });
|
|
2960
|
+
for (let mossa of mosse) {
|
|
2961
|
+
if (mossa['to'].length === 2) this.hint(mossa['to']);
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
|
|
2965
|
+
dehintMoves(square) {
|
|
2966
|
+
let mosse = this.game.moves({ square: square.id, verbose: true });
|
|
2967
|
+
for (let mossa of mosse) {
|
|
2968
|
+
let to = this.squares[mossa['to']];
|
|
2969
|
+
to.removeHint();
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
|
|
2973
|
+
// Moves
|
|
2974
|
+
|
|
2975
|
+
canMove(square) {
|
|
2976
|
+
if (!square.piece) return false;
|
|
2977
|
+
if (this.config.movableColors === 'none') return false;
|
|
2978
|
+
if (this.config.movableColors === 'w' && square.piece.color === 'b') return false;
|
|
2979
|
+
if (this.config.movableColors === 'b' && square.piece.color === 'w') return false;
|
|
2980
|
+
if (!this.config.onlyLegalMoves) return true;
|
|
2981
|
+
return square.piece.color == this.turn();
|
|
2982
|
+
}
|
|
2983
|
+
|
|
2984
|
+
convertMove(move) {
|
|
2985
|
+
if (move instanceof Move) return move;
|
|
2986
|
+
if (typeof move == 'string') {
|
|
2987
|
+
let fromId = move.slice(0, 2);
|
|
2988
|
+
let toId = move.slice(2, 4);
|
|
2989
|
+
let promotion = move.slice(4, 5) ? move.slice(4, 5) : null;
|
|
2990
|
+
return new Move(this.squares[fromId], this.squares[toId], promotion);
|
|
2991
|
+
}
|
|
2992
|
+
throw new Error("Invalid move format");
|
|
2993
|
+
}
|
|
2994
|
+
|
|
2995
|
+
allSquares(method) {
|
|
2996
|
+
for (const square of Object.values(this.squares)) {
|
|
2997
|
+
square[method]();
|
|
2998
|
+
this.squares[square.id] = square;
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
legalMove(move) {
|
|
3003
|
+
let legal_moves = this.legalMoves(move.from.id);
|
|
3004
|
+
|
|
3005
|
+
for (let i in legal_moves) {
|
|
3006
|
+
if (legal_moves[i]['to'] === move.to.id &&
|
|
3007
|
+
move.promotion == legal_moves[i]['promotion'])
|
|
3008
|
+
return true;
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
return false;
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
legalMoves(from = null, verb = true) {
|
|
3015
|
+
if (from) return this.game.moves({ square: from, verbose: verb });
|
|
3016
|
+
return this.game.moves({ verbose: verb });
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
// Position
|
|
3020
|
+
|
|
3021
|
+
chageFenTurn(fen, color) {
|
|
3022
|
+
let parts = fen.split(' ');
|
|
3023
|
+
parts[1] = color;
|
|
3024
|
+
return parts.join(' ');
|
|
3025
|
+
}
|
|
3026
|
+
|
|
3027
|
+
changeFenColor(fen) {
|
|
3028
|
+
let parts = fen.split(' ');
|
|
3029
|
+
parts[1] = parts[1] === 'w' ? 'b' : 'w';
|
|
3030
|
+
return parts.join(' ');
|
|
3031
|
+
}
|
|
3032
|
+
|
|
3033
|
+
playerTurn() {
|
|
3034
|
+
return this.getOrientation() == this.game.turn()
|
|
3035
|
+
}
|
|
3036
|
+
|
|
3037
|
+
isWhiteOriented() { return this.config.orientation === 'w' }
|
|
3038
|
+
|
|
3039
|
+
// Squares
|
|
3040
|
+
|
|
3041
|
+
getSquareID(row, col) {
|
|
3042
|
+
row = parseInt(row);
|
|
3043
|
+
col = parseInt(col);
|
|
3044
|
+
if (this.isWhiteOriented()) {
|
|
3045
|
+
row = 8 - row;
|
|
3046
|
+
col = col + 1;
|
|
3047
|
+
} else {
|
|
3048
|
+
row = row + 1;
|
|
3049
|
+
col = 8 - col;
|
|
3050
|
+
}
|
|
3051
|
+
let letters = 'abcdefgh';
|
|
3052
|
+
let letter = letters[col - 1];
|
|
3053
|
+
return letter + row;
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
removeSquares() {
|
|
3057
|
+
for (const square of Object.values(this.squares)) {
|
|
3058
|
+
this.board.removeChild(square.element);
|
|
3059
|
+
square.destroy();
|
|
3060
|
+
|
|
3061
|
+
}
|
|
3062
|
+
this.squares = {};
|
|
3063
|
+
}
|
|
3064
|
+
|
|
3065
|
+
promote(move) {
|
|
3066
|
+
|
|
3067
|
+
if (!this.config.onlyLegalMoves) return false;
|
|
3068
|
+
|
|
3069
|
+
let to = move.to;
|
|
3070
|
+
let from = move.from;
|
|
3071
|
+
let pezzo = this.game.get(from.id);
|
|
3072
|
+
let choichable = ['q', 'r', 'b', 'n'];
|
|
3073
|
+
|
|
3074
|
+
if (pezzo['type'] !== 'p' || !(to.row === 1 || to.row === 8)) return false;
|
|
3075
|
+
|
|
3076
|
+
for (const square of Object.values(this.squares)) {
|
|
3077
|
+
let distance = Math.abs(to.row - square.row);
|
|
3078
|
+
|
|
3079
|
+
if (to.col === square.col && distance <= 3) {
|
|
3080
|
+
|
|
3081
|
+
let pieceId = choichable[distance] + pezzo['color'];
|
|
3082
|
+
|
|
3083
|
+
square.putPromotion(
|
|
3084
|
+
this.getPiecePath(pieceId),
|
|
3085
|
+
() => {
|
|
3086
|
+
this.promoting = pieceId[0];
|
|
3087
|
+
this.clicked = from;
|
|
3088
|
+
this.onClick(to);
|
|
3089
|
+
}
|
|
3090
|
+
);
|
|
3091
|
+
} else
|
|
3092
|
+
square.putCover(
|
|
3093
|
+
() => {
|
|
3094
|
+
this.promoting = 'none';
|
|
3095
|
+
this.onClick(square);
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
|
|
3099
|
+
this.clicked = from.id;
|
|
3100
|
+
|
|
3101
|
+
return true;
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
transitionTimingFunction(elapsed, duration, type = 'ease') {
|
|
3105
|
+
let x = elapsed / duration;
|
|
3106
|
+
switch (type) {
|
|
3107
|
+
case 'linear':
|
|
3108
|
+
return x;
|
|
3109
|
+
case 'ease':
|
|
3110
|
+
return (x ** 2) * (3 - 2 * x);
|
|
3111
|
+
case 'ease-in':
|
|
3112
|
+
return x ** 2;
|
|
3113
|
+
case 'ease-out':
|
|
3114
|
+
return -1 * (x - 1) ** 2 + 1;
|
|
3115
|
+
case 'ease-in-out':
|
|
3116
|
+
return (x < 0.5) ? 2 * x ** 2 : 4 * x - 2 * x ** 2 - 1;
|
|
3117
|
+
}
|
|
3118
|
+
}
|
|
3119
|
+
|
|
3120
|
+
// user
|
|
3121
|
+
|
|
3122
|
+
turn() {
|
|
3123
|
+
return this.game.turn();
|
|
3124
|
+
}
|
|
3125
|
+
|
|
3126
|
+
getOrientation() {
|
|
3127
|
+
return this.config.orientation;
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
fen() {
|
|
3131
|
+
return this.game.fen();
|
|
3132
|
+
}
|
|
3133
|
+
|
|
3134
|
+
lastMove() {
|
|
3135
|
+
return this.movesHistory[this.movesHistory.length - 1];
|
|
3136
|
+
}
|
|
3137
|
+
|
|
3138
|
+
get history() {
|
|
3139
|
+
return this.movesHistory;
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
history() {
|
|
3143
|
+
return this.movesHistory;
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
get(square) {
|
|
3147
|
+
square = this.convertSquare(square);
|
|
3148
|
+
square.check();
|
|
3149
|
+
let piece = square.piece;
|
|
3150
|
+
return piece ? piece.id : null;
|
|
3151
|
+
}
|
|
3152
|
+
|
|
3153
|
+
position(position, color = null) {
|
|
3154
|
+
this.allSquares('removeHint');
|
|
3155
|
+
this.allSquares("deselect");
|
|
3156
|
+
this.allSquares("unmoved");
|
|
3157
|
+
if (color && color !== this.config.orientation) {
|
|
3158
|
+
position = this.changeFenColor(position);
|
|
3159
|
+
this.config.orientation = color;
|
|
3160
|
+
this.destroy();
|
|
3161
|
+
this.init();
|
|
3162
|
+
} else {
|
|
3163
|
+
this.buildGame(this.config.position);
|
|
3164
|
+
this.updateBoardPieces();
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
|
|
3168
|
+
flip() {
|
|
3169
|
+
let position = this.game.fen();
|
|
3170
|
+
this.position(position, this.config.orientation === 'w' ? 'b' : 'w');
|
|
3171
|
+
}
|
|
3172
|
+
|
|
3173
|
+
build() {
|
|
3174
|
+
if (this.board) this.destroy();
|
|
3175
|
+
this.init();
|
|
3176
|
+
}
|
|
3177
|
+
|
|
3178
|
+
move(move, animation) {
|
|
3179
|
+
move = this.convertMove(move);
|
|
3180
|
+
move.check();
|
|
3181
|
+
|
|
3182
|
+
let from = move.from;
|
|
3183
|
+
let to = move.to;
|
|
3184
|
+
|
|
3185
|
+
if (!this.config.onlyLegalMoves) {
|
|
3186
|
+
let piece = this.piece(from.id);
|
|
3187
|
+
this.game.remove(from.id);
|
|
3188
|
+
this.game.remove(to.id);
|
|
3189
|
+
this.game.put({ type: move.hasPromotion() ? move.promotion : piece[0], color: piece[1] }, to.id);
|
|
3190
|
+
this.updateBoardPieces(animation);
|
|
3191
|
+
} else {
|
|
3192
|
+
this.allSquares("unmoved");
|
|
3193
|
+
|
|
3194
|
+
move = this.game.move({
|
|
3195
|
+
from: from.id,
|
|
3196
|
+
to: to.id,
|
|
3197
|
+
promotion: move.hasPromotion() ? move.promotion : undefined
|
|
3198
|
+
});
|
|
3199
|
+
|
|
3200
|
+
if (move === null) {
|
|
3201
|
+
throw new Error("Invalid move: move could not be executed");
|
|
3202
|
+
}
|
|
3203
|
+
|
|
3204
|
+
this.movesHistory.push(move);
|
|
3205
|
+
|
|
3206
|
+
this.updateBoardPieces(animation);
|
|
3207
|
+
|
|
3208
|
+
from.moved();
|
|
3209
|
+
to.moved();
|
|
3210
|
+
this.allSquares("removeHint");
|
|
3211
|
+
|
|
3212
|
+
this.config.onMoveEnd(move);
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
|
|
3216
|
+
clear(animation = true) {
|
|
3217
|
+
this.game.clear();
|
|
3218
|
+
this.updateBoardPieces(animation);
|
|
3219
|
+
}
|
|
3220
|
+
|
|
3221
|
+
insert(square, piece) {
|
|
3222
|
+
square = this.convertSquare(square);
|
|
3223
|
+
piece = this.convertPiece(piece);
|
|
3224
|
+
square.check();
|
|
3225
|
+
piece.check();
|
|
3226
|
+
if (square.piece) this.remove(square);
|
|
3227
|
+
this.game.put({ type: piece.type, color: piece.color }, square.id);
|
|
3228
|
+
this.updateBoardPieces();
|
|
3229
|
+
}
|
|
3230
|
+
|
|
3231
|
+
isGameOver() {
|
|
3232
|
+
if (this.game.isGameOver()) {
|
|
3233
|
+
if (this.game.inCheck()) return this.game.turn() === 'w' ? 'b' : 'w';
|
|
3234
|
+
return 'd';
|
|
3235
|
+
}
|
|
3236
|
+
return null;
|
|
3237
|
+
}
|
|
3238
|
+
|
|
3239
|
+
orientation(color) {
|
|
3240
|
+
if ((color === 'w' || color === 'b') && color !== this.config.orientation) this.flip();
|
|
3241
|
+
}
|
|
3242
|
+
|
|
3243
|
+
resize(value) {
|
|
3244
|
+
if (value === 'auto') {
|
|
3245
|
+
let size;
|
|
3246
|
+
if (this.board.offsetWidth === 0) {
|
|
3247
|
+
size = this.board.offsetHeight;
|
|
3248
|
+
} else if (this.board.offsetHeight === 0) {
|
|
3249
|
+
size = this.board.offsetWidth;
|
|
3250
|
+
} else {
|
|
3251
|
+
size = Math.min(this.board.offsetWidth, this.board.offsetHeight);
|
|
3252
|
+
}
|
|
3253
|
+
this.resize(size);
|
|
3254
|
+
} else if (typeof value !== 'number') {
|
|
3255
|
+
throw new Error(this.error_messages['invalid_value'] + value);
|
|
3256
|
+
} else {
|
|
3257
|
+
document.documentElement.style.setProperty('--dimBoard', value + 'px');
|
|
3258
|
+
this.updateBoardPieces();
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
|
|
3262
|
+
destroy() {
|
|
3263
|
+
this.removeSquares();
|
|
3264
|
+
this.removeBoard();
|
|
3265
|
+
this.game = null;
|
|
3266
|
+
this.clicked = null;
|
|
3267
|
+
this.movesHistory = [];
|
|
3268
|
+
this.mosseIndietro = [];
|
|
3269
|
+
this.clicked = null;
|
|
3270
|
+
this.board = null;
|
|
3271
|
+
}
|
|
3272
|
+
|
|
3273
|
+
remove(square, animation = true) {
|
|
3274
|
+
square = this.convertSquare(square);
|
|
3275
|
+
square.check();
|
|
3276
|
+
this.game.remove(square.id);
|
|
3277
|
+
let piece = square.piece;
|
|
3278
|
+
this.updateBoardPieces(animation);
|
|
3279
|
+
return piece;
|
|
3280
|
+
}
|
|
3281
|
+
|
|
3282
|
+
piece(square) {
|
|
3283
|
+
let piece = this.game.get(square);
|
|
3284
|
+
return piece ? piece['type'] + piece['color'] : null;
|
|
3285
|
+
}
|
|
3286
|
+
|
|
3287
|
+
highlight(square) {
|
|
3288
|
+
square = this.convertSquare(square);
|
|
3289
|
+
square.check();
|
|
3290
|
+
square.highlight();
|
|
3291
|
+
}
|
|
3292
|
+
|
|
3293
|
+
dehighlight(square) {
|
|
3294
|
+
square = this.convertSquare(square);
|
|
3295
|
+
square.check();
|
|
3296
|
+
square.dehighlight();
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
}
|
|
3300
|
+
|
|
3301
|
+
return Chessboard;
|
|
3302
|
+
})();
|
|
3303
|
+
|
|
3304
|
+
// Exporting class for browser window
|
|
3305
|
+
window.Chessboard.Chessboard = Chessboard;
|