'update'
[vchess.git] / client / src / base_rules.js
CommitLineData
92342261
BA
1// (Orthodox) Chess rules are defined in ChessRules class.
2// Variants generally inherit from it, and modify some parts.
3
e2732923 4import { ArrayFun } from "@/utils/array";
0c3fe8a6 5import { randInt, shuffle } from "@/utils/alea";
e2732923 6
910d631b 7// class "PiPo": Piece + Position
6808d7a1 8export const PiPo = class PiPo {
1c9f093d 9 // o: {piece[p], color[c], posX[x], posY[y]}
6808d7a1 10 constructor(o) {
1c9f093d
BA
11 this.p = o.p;
12 this.c = o.c;
13 this.x = o.x;
14 this.y = o.y;
15 }
6808d7a1 16};
1d184b4c 17
6808d7a1 18export const Move = class Move {
1c9f093d
BA
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
6808d7a1 22 constructor(o) {
1c9f093d
BA
23 this.appear = o.appear;
24 this.vanish = o.vanish;
6808d7a1
BA
25 this.start = o.start ? o.start : { x: o.vanish[0].x, y: o.vanish[0].y };
26 this.end = o.end ? o.end : { x: o.appear[0].x, y: o.appear[0].y };
1c9f093d 27 }
6808d7a1 28};
1d184b4c 29
2c5d7b20
BA
30// NOTE: x coords = top to bottom; y = left to right
31// (from white player perspective)
6808d7a1 32export const ChessRules = class ChessRules {
1c9f093d
BA
33 //////////////
34 // MISC UTILS
35
20620465 36 // Some variants don't have flags:
6808d7a1
BA
37 static get HasFlags() {
38 return true;
20620465 39 }
1c9f093d 40
3a2a7b5f
BA
41 // Or castle
42 static get HasCastle() {
43 return V.HasFlags;
44 }
45
32f6285e
BA
46 // Pawns specifications
47 static get PawnSpecs() {
48 return {
49 directions: { 'w': -1, 'b': 1 },
472c0c4f 50 initShift: { w: 1, b: 1 },
32f6285e 51 twoSquares: true,
472c0c4f 52 threeSquares: false,
32f6285e
BA
53 promotions: [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN],
54 canCapture: true,
55 captureBackward: false,
56 bidirectional: false
57 };
58 }
59
60 // En-passant captures need a stack of squares:
6808d7a1
BA
61 static get HasEnpassant() {
62 return true;
20620465
BA
63 }
64
65 // Some variants cannot have analyse mode
8477e53d 66 static get CanAnalyze() {
20620465
BA
67 return true;
68 }
933fd1f9
BA
69 // Patch: issues with javascript OOP, objects can't access static fields.
70 get canAnalyze() {
71 return V.CanAnalyze;
72 }
20620465
BA
73
74 // Some variants show incomplete information,
75 // and thus show only a partial moves list or no list at all.
76 static get ShowMoves() {
77 return "all";
78 }
933fd1f9
BA
79 get showMoves() {
80 return V.ShowMoves;
81 }
1c9f093d 82
5246b49d
BA
83 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
84 get showFirstTurn() {
85 return false;
86 }
87
71ef1664
BA
88 // Some variants always show the same orientation
89 static get CanFlip() {
90 return true;
91 }
92 get canFlip() {
93 return V.CanFlip;
94 }
95
107dc1bd
BA
96 // For (generally old) variants without checkered board
97 static get Monochrome() {
98 return false;
99 }
100
101 // Some variants require lines drawing
102 static get Lines() {
103 if (V.Monochrome) {
104 let lines = [];
105 // Draw all inter-squares lines
106 for (let i = 0; i <= V.size.x; i++)
107 lines.push([[i, 0], [i, V.size.y]]);
108 for (let j = 0; j <= V.size.y; j++)
109 lines.push([[0, j], [V.size.x, j]]);
110 return lines;
111 }
112 return null;
113 }
114
61656127
BA
115 // Some variants use click infos:
116 doClick() {
117 return null;
118 }
119
90df90bc
BA
120 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
121 hoverHighlight() {
122 return false;
123 }
124
14edde72
BA
125 static get IMAGE_EXTENSION() {
126 // All pieces should be in the SVG format
127 return ".svg";
128 }
129
1c9f093d 130 // Turn "wb" into "B" (for FEN)
6808d7a1
BA
131 static board2fen(b) {
132 return b[0] == "w" ? b[1].toUpperCase() : b[1];
1c9f093d
BA
133 }
134
135 // Turn "p" into "bp" (for board)
6808d7a1
BA
136 static fen2board(f) {
137 return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f;
1c9f093d
BA
138 }
139
68e19a44 140 // Check if FEN describes a board situation correctly
6808d7a1 141 static IsGoodFen(fen) {
1c9f093d
BA
142 const fenParsed = V.ParseFen(fen);
143 // 1) Check position
6808d7a1 144 if (!V.IsGoodPosition(fenParsed.position)) return false;
1c9f093d 145 // 2) Check turn
6808d7a1 146 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
1c9f093d
BA
147 // 3) Check moves count
148 if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0))
149 return false;
150 // 4) Check flags
151 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
152 return false;
153 // 5) Check enpassant
6808d7a1
BA
154 if (
155 V.HasEnpassant &&
156 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
157 ) {
1c9f093d
BA
158 return false;
159 }
160 return true;
161 }
162
163 // Is position part of the FEN a priori correct?
6808d7a1
BA
164 static IsGoodPosition(position) {
165 if (position.length == 0) return false;
1c9f093d 166 const rows = position.split("/");
6808d7a1 167 if (rows.length != V.size.x) return false;
6f2f9437 168 let kings = { "k": 0, "K": 0 };
6808d7a1 169 for (let row of rows) {
1c9f093d 170 let sumElts = 0;
6808d7a1 171 for (let i = 0; i < row.length; i++) {
6f2f9437 172 if (['K','k'].includes(row[i])) kings[row[i]]++;
6808d7a1
BA
173 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
174 else {
1c9f093d 175 const num = parseInt(row[i]);
6808d7a1 176 if (isNaN(num)) return false;
1c9f093d
BA
177 sumElts += num;
178 }
179 }
6808d7a1 180 if (sumElts != V.size.y) return false;
1c9f093d 181 }
6f2f9437
BA
182 // Both kings should be on board. Exactly one per color.
183 if (Object.values(kings).some(v => v != 1)) return false;
1c9f093d
BA
184 return true;
185 }
186
187 // For FEN checking
6808d7a1
BA
188 static IsGoodTurn(turn) {
189 return ["w", "b"].includes(turn);
1c9f093d
BA
190 }
191
192 // For FEN checking
6808d7a1 193 static IsGoodFlags(flags) {
3a2a7b5f
BA
194 // NOTE: a little too permissive to work with more variants
195 return !!flags.match(/^[a-z]{4,4}$/);
1c9f093d
BA
196 }
197
472c0c4f 198 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
6808d7a1
BA
199 static IsGoodEnpassant(enpassant) {
200 if (enpassant != "-") {
201 const ep = V.SquareToCoords(enpassant);
202 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
1c9f093d
BA
203 }
204 return true;
205 }
206
207 // 3 --> d (column number to letter)
6808d7a1 208 static CoordToColumn(colnum) {
1c9f093d
BA
209 return String.fromCharCode(97 + colnum);
210 }
211
212 // d --> 3 (column letter to number)
6808d7a1 213 static ColumnToCoord(column) {
1c9f093d
BA
214 return column.charCodeAt(0) - 97;
215 }
216
217 // a4 --> {x:3,y:0}
6808d7a1 218 static SquareToCoords(sq) {
1c9f093d
BA
219 return {
220 // NOTE: column is always one char => max 26 columns
221 // row is counted from black side => subtraction
222 x: V.size.x - parseInt(sq.substr(1)),
223 y: sq[0].charCodeAt() - 97
224 };
225 }
226
227 // {x:0,y:4} --> e8
6808d7a1 228 static CoordsToSquare(coords) {
1c9f093d
BA
229 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
230 }
231
305ede7e 232 // Path to pieces (standard ones in pieces/ folder)
241bf8f2 233 getPpath(b) {
305ede7e 234 return b;
241bf8f2
BA
235 }
236
3a2a7b5f 237 // Path to promotion pieces (usually the same)
c7550017
BA
238 getPPpath(m) {
239 return this.getPpath(m.appear[0].c + m.appear[0].p);
3a2a7b5f
BA
240 }
241
1c9f093d 242 // Aggregates flags into one object
6808d7a1 243 aggregateFlags() {
1c9f093d
BA
244 return this.castleFlags;
245 }
246
247 // Reverse operation
6808d7a1 248 disaggregateFlags(flags) {
1c9f093d
BA
249 this.castleFlags = flags;
250 }
251
252 // En-passant square, if any
6808d7a1
BA
253 getEpSquare(moveOrSquare) {
254 if (!moveOrSquare) return undefined;
255 if (typeof moveOrSquare === "string") {
1c9f093d 256 const square = moveOrSquare;
6808d7a1 257 if (square == "-") return undefined;
1c9f093d
BA
258 return V.SquareToCoords(square);
259 }
260 // Argument is a move:
261 const move = moveOrSquare;
1c5bfdf2
BA
262 const s = move.start,
263 e = move.end;
6808d7a1 264 if (
1c5bfdf2 265 s.y == e.y &&
0d5335de
BA
266 Math.abs(s.x - e.x) == 2 &&
267 // Next conditions for variants like Atomic or Rifle, Recycle...
268 (move.appear.length > 0 && move.appear[0].p == V.PAWN) &&
269 (move.vanish.length > 0 && move.vanish[0].p == V.PAWN)
6808d7a1 270 ) {
1c9f093d 271 return {
1c5bfdf2
BA
272 x: (s.x + e.x) / 2,
273 y: s.y
1c9f093d
BA
274 };
275 }
276 return undefined; //default
277 }
278
279 // Can thing on square1 take thing on square2
6808d7a1
BA
280 canTake([x1, y1], [x2, y2]) {
281 return this.getColor(x1, y1) !== this.getColor(x2, y2);
1c9f093d
BA
282 }
283
284 // Is (x,y) on the chessboard?
6808d7a1
BA
285 static OnBoard(x, y) {
286 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
1c9f093d
BA
287 }
288
289 // Used in interface: 'side' arg == player color
6808d7a1
BA
290 canIplay(side, [x, y]) {
291 return this.turn == side && this.getColor(x, y) == side;
1c9f093d
BA
292 }
293
294 // On which squares is color under check ? (for interface)
af34341d
BA
295 getCheckSquares() {
296 const color = this.turn;
b0a0468a
BA
297 return (
298 this.underCheck(color)
2c5d7b20
BA
299 // kingPos must be duplicated, because it may change:
300 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
b0a0468a
BA
301 : []
302 );
1c9f093d
BA
303 }
304
305 /////////////
306 // FEN UTILS
307
7ba4a5bc
BA
308 // Setup the initial random (asymmetric) position
309 static GenRandInitFen(randomness) {
7ba4a5bc
BA
310 if (randomness == 0)
311 // Deterministic:
3a2a7b5f 312 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
7ba4a5bc 313
6808d7a1 314 let pieces = { w: new Array(8), b: new Array(8) };
3a2a7b5f 315 let flags = "";
7ba4a5bc 316 // Shuffle pieces on first (and last rank if randomness == 2)
6808d7a1 317 for (let c of ["w", "b"]) {
7ba4a5bc
BA
318 if (c == 'b' && randomness == 1) {
319 pieces['b'] = pieces['w'];
3a2a7b5f 320 flags += flags;
7ba4a5bc
BA
321 break;
322 }
323
1c9f093d
BA
324 let positions = ArrayFun.range(8);
325
326 // Get random squares for bishops
656b1878 327 let randIndex = 2 * randInt(4);
1c9f093d
BA
328 const bishop1Pos = positions[randIndex];
329 // The second bishop must be on a square of different color
656b1878 330 let randIndex_tmp = 2 * randInt(4) + 1;
1c9f093d
BA
331 const bishop2Pos = positions[randIndex_tmp];
332 // Remove chosen squares
6808d7a1
BA
333 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
334 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
1c9f093d
BA
335
336 // Get random squares for knights
656b1878 337 randIndex = randInt(6);
1c9f093d
BA
338 const knight1Pos = positions[randIndex];
339 positions.splice(randIndex, 1);
656b1878 340 randIndex = randInt(5);
1c9f093d
BA
341 const knight2Pos = positions[randIndex];
342 positions.splice(randIndex, 1);
343
344 // Get random square for queen
656b1878 345 randIndex = randInt(4);
1c9f093d
BA
346 const queenPos = positions[randIndex];
347 positions.splice(randIndex, 1);
348
349 // Rooks and king positions are now fixed,
350 // because of the ordering rook-king-rook
351 const rook1Pos = positions[0];
352 const kingPos = positions[1];
353 const rook2Pos = positions[2];
354
355 // Finally put the shuffled pieces in the board array
6808d7a1
BA
356 pieces[c][rook1Pos] = "r";
357 pieces[c][knight1Pos] = "n";
358 pieces[c][bishop1Pos] = "b";
359 pieces[c][queenPos] = "q";
360 pieces[c][kingPos] = "k";
361 pieces[c][bishop2Pos] = "b";
362 pieces[c][knight2Pos] = "n";
363 pieces[c][rook2Pos] = "r";
3a2a7b5f 364 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
1c9f093d 365 }
e3e2cc44 366 // Add turn + flags + enpassant
6808d7a1
BA
367 return (
368 pieces["b"].join("") +
1c9f093d
BA
369 "/pppppppp/8/8/8/8/PPPPPPPP/" +
370 pieces["w"].join("").toUpperCase() +
3a2a7b5f 371 " w 0 " + flags + " -"
e3e2cc44 372 );
1c9f093d
BA
373 }
374
375 // "Parse" FEN: just return untransformed string data
6808d7a1 376 static ParseFen(fen) {
1c9f093d 377 const fenParts = fen.split(" ");
6808d7a1 378 let res = {
1c9f093d
BA
379 position: fenParts[0],
380 turn: fenParts[1],
6808d7a1 381 movesCount: fenParts[2]
1c9f093d
BA
382 };
383 let nextIdx = 3;
6808d7a1
BA
384 if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] });
385 if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] });
1c9f093d
BA
386 return res;
387 }
388
389 // Return current fen (game state)
6808d7a1
BA
390 getFen() {
391 return (
f9c36b2d
BA
392 this.getBaseFen() + " " +
393 this.getTurnFen() + " " +
6808d7a1
BA
394 this.movesCount +
395 (V.HasFlags ? " " + this.getFlagsFen() : "") +
396 (V.HasEnpassant ? " " + this.getEnpassantFen() : "")
397 );
1c9f093d
BA
398 }
399
f9c36b2d
BA
400 getFenForRepeat() {
401 // Omit movesCount, only variable allowed to differ
402 return (
403 this.getBaseFen() + "_" +
404 this.getTurnFen() +
405 (V.HasFlags ? "_" + this.getFlagsFen() : "") +
406 (V.HasEnpassant ? "_" + this.getEnpassantFen() : "")
407 );
408 }
409
1c9f093d 410 // Position part of the FEN string
6808d7a1 411 getBaseFen() {
6f2f9437
BA
412 const format = (count) => {
413 // if more than 9 consecutive free spaces, break the integer,
414 // otherwise FEN parsing will fail.
415 if (count <= 9) return count;
416 // Currently only boards of size up to 11 or 12:
417 return "9" + (count - 9);
418 };
1c9f093d 419 let position = "";
6808d7a1 420 for (let i = 0; i < V.size.x; i++) {
1c9f093d 421 let emptyCount = 0;
6808d7a1
BA
422 for (let j = 0; j < V.size.y; j++) {
423 if (this.board[i][j] == V.EMPTY) emptyCount++;
424 else {
425 if (emptyCount > 0) {
1c9f093d 426 // Add empty squares in-between
6f2f9437 427 position += format(emptyCount);
1c9f093d
BA
428 emptyCount = 0;
429 }
430 position += V.board2fen(this.board[i][j]);
431 }
432 }
6808d7a1 433 if (emptyCount > 0) {
1c9f093d 434 // "Flush remainder"
6f2f9437 435 position += format(emptyCount);
1c9f093d 436 }
6808d7a1 437 if (i < V.size.x - 1) position += "/"; //separate rows
1c9f093d
BA
438 }
439 return position;
440 }
441
6808d7a1 442 getTurnFen() {
1c9f093d
BA
443 return this.turn;
444 }
445
446 // Flags part of the FEN string
6808d7a1 447 getFlagsFen() {
1c9f093d 448 let flags = "";
3a2a7b5f
BA
449 // Castling flags
450 for (let c of ["w", "b"])
451 flags += this.castleFlags[c].map(V.CoordToColumn).join("");
1c9f093d
BA
452 return flags;
453 }
454
455 // Enpassant part of the FEN string
6808d7a1 456 getEnpassantFen() {
1c9f093d 457 const L = this.epSquares.length;
6808d7a1
BA
458 if (!this.epSquares[L - 1]) return "-"; //no en-passant
459 return V.CoordsToSquare(this.epSquares[L - 1]);
1c9f093d
BA
460 }
461
462 // Turn position fen into double array ["wb","wp","bk",...]
6808d7a1 463 static GetBoard(position) {
1c9f093d
BA
464 const rows = position.split("/");
465 let board = ArrayFun.init(V.size.x, V.size.y, "");
6808d7a1 466 for (let i = 0; i < rows.length; i++) {
1c9f093d 467 let j = 0;
6808d7a1 468 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
1c9f093d
BA
469 const character = rows[i][indexInRow];
470 const num = parseInt(character);
a13cbc0f 471 // If num is a number, just shift j:
6808d7a1 472 if (!isNaN(num)) j += num;
a13cbc0f 473 // Else: something at position i,j
6808d7a1 474 else board[i][j++] = V.fen2board(character);
1c9f093d
BA
475 }
476 }
477 return board;
478 }
479
480 // Extract (relevant) flags from fen
6808d7a1 481 setFlags(fenflags) {
1c9f093d 482 // white a-castle, h-castle, black a-castle, h-castle
bb688df5 483 this.castleFlags = { w: [-1, -1], b: [-1, -1] };
3a2a7b5f
BA
484 for (let i = 0; i < 4; i++) {
485 this.castleFlags[i < 2 ? "w" : "b"][i % 2] =
486 V.ColumnToCoord(fenflags.charAt(i));
487 }
1c9f093d
BA
488 }
489
490 //////////////////
491 // INITIALIZATION
492
37cdcbf3 493 // Fen string fully describes the game state
b627d118
BA
494 constructor(fen) {
495 if (!fen)
496 // In printDiagram() fen isn't supply because only getPpath() is used
497 // TODO: find a better solution!
498 return;
1c9f093d
BA
499 const fenParsed = V.ParseFen(fen);
500 this.board = V.GetBoard(fenParsed.position);
af34341d 501 this.turn = fenParsed.turn;
1c9f093d
BA
502 this.movesCount = parseInt(fenParsed.movesCount);
503 this.setOtherVariables(fen);
504 }
505
3a2a7b5f
BA
506 // Scan board for kings positions
507 scanKings(fen) {
6808d7a1 508 this.INIT_COL_KING = { w: -1, b: -1 };
2c5d7b20
BA
509 // Squares of white and black king:
510 this.kingPos = { w: [-1, -1], b: [-1, -1] };
1c9f093d 511 const fenRows = V.ParseFen(fen).position.split("/");
90e814b6 512 const startRow = { 'w': V.size.x - 1, 'b': 0 };
6808d7a1 513 for (let i = 0; i < fenRows.length; i++) {
1c9f093d 514 let k = 0; //column index on board
6808d7a1
BA
515 for (let j = 0; j < fenRows[i].length; j++) {
516 switch (fenRows[i].charAt(j)) {
517 case "k":
518 this.kingPos["b"] = [i, k];
519 this.INIT_COL_KING["b"] = k;
1c9f093d 520 break;
6808d7a1
BA
521 case "K":
522 this.kingPos["w"] = [i, k];
523 this.INIT_COL_KING["w"] = k;
1c9f093d 524 break;
6808d7a1 525 default: {
1c9f093d 526 const num = parseInt(fenRows[i].charAt(j));
6808d7a1
BA
527 if (!isNaN(num)) k += num - 1;
528 }
1c9f093d
BA
529 }
530 k++;
531 }
532 }
533 }
534
535 // Some additional variables from FEN (variant dependant)
6808d7a1 536 setOtherVariables(fen) {
1c9f093d
BA
537 // Set flags and enpassant:
538 const parsedFen = V.ParseFen(fen);
6808d7a1
BA
539 if (V.HasFlags) this.setFlags(parsedFen.flags);
540 if (V.HasEnpassant) {
541 const epSq =
542 parsedFen.enpassant != "-"
9bd6786b 543 ? this.getEpSquare(parsedFen.enpassant)
6808d7a1
BA
544 : undefined;
545 this.epSquares = [epSq];
1c9f093d 546 }
3a2a7b5f
BA
547 // Search for kings positions:
548 this.scanKings(fen);
1c9f093d
BA
549 }
550
551 /////////////////////
552 // GETTERS & SETTERS
553
6808d7a1
BA
554 static get size() {
555 return { x: 8, y: 8 };
1c9f093d
BA
556 }
557
0ba6420d 558 // Color of thing on square (i,j). 'undefined' if square is empty
6808d7a1 559 getColor(i, j) {
1c9f093d
BA
560 return this.board[i][j].charAt(0);
561 }
562
563 // Piece type on square (i,j). 'undefined' if square is empty
6808d7a1 564 getPiece(i, j) {
1c9f093d
BA
565 return this.board[i][j].charAt(1);
566 }
567
568 // Get opponent color
6808d7a1
BA
569 static GetOppCol(color) {
570 return color == "w" ? "b" : "w";
1c9f093d
BA
571 }
572
1c9f093d 573 // Pieces codes (for a clearer code)
6808d7a1
BA
574 static get PAWN() {
575 return "p";
576 }
577 static get ROOK() {
578 return "r";
579 }
580 static get KNIGHT() {
581 return "n";
582 }
583 static get BISHOP() {
584 return "b";
585 }
586 static get QUEEN() {
587 return "q";
588 }
589 static get KING() {
590 return "k";
591 }
1c9f093d
BA
592
593 // For FEN checking:
6808d7a1
BA
594 static get PIECES() {
595 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
1c9f093d
BA
596 }
597
598 // Empty square
6808d7a1
BA
599 static get EMPTY() {
600 return "";
601 }
1c9f093d
BA
602
603 // Some pieces movements
6808d7a1 604 static get steps() {
1c9f093d 605 return {
6808d7a1
BA
606 r: [
607 [-1, 0],
608 [1, 0],
609 [0, -1],
610 [0, 1]
611 ],
612 n: [
613 [-1, -2],
614 [-1, 2],
615 [1, -2],
616 [1, 2],
617 [-2, -1],
618 [-2, 1],
619 [2, -1],
620 [2, 1]
621 ],
622 b: [
623 [-1, -1],
624 [-1, 1],
625 [1, -1],
626 [1, 1]
627 ]
1c9f093d
BA
628 };
629 }
630
631 ////////////////////
632 // MOVES GENERATION
633
0ba6420d 634 // All possible moves from selected square
6808d7a1
BA
635 getPotentialMovesFrom([x, y]) {
636 switch (this.getPiece(x, y)) {
1c9f093d 637 case V.PAWN:
6808d7a1 638 return this.getPotentialPawnMoves([x, y]);
1c9f093d 639 case V.ROOK:
6808d7a1 640 return this.getPotentialRookMoves([x, y]);
1c9f093d 641 case V.KNIGHT:
6808d7a1 642 return this.getPotentialKnightMoves([x, y]);
1c9f093d 643 case V.BISHOP:
6808d7a1 644 return this.getPotentialBishopMoves([x, y]);
1c9f093d 645 case V.QUEEN:
6808d7a1 646 return this.getPotentialQueenMoves([x, y]);
1c9f093d 647 case V.KING:
6808d7a1 648 return this.getPotentialKingMoves([x, y]);
1c9f093d 649 }
6808d7a1 650 return []; //never reached
1c9f093d
BA
651 }
652
653 // Build a regular move from its initial and destination squares.
654 // tr: transformation
6808d7a1 655 getBasicMove([sx, sy], [ex, ey], tr) {
1c58eb76
BA
656 const initColor = this.getColor(sx, sy);
657 const initPiece = this.getPiece(sx, sy);
1c9f093d
BA
658 let mv = new Move({
659 appear: [
660 new PiPo({
661 x: ex,
662 y: ey,
1c58eb76
BA
663 c: tr ? tr.c : initColor,
664 p: tr ? tr.p : initPiece
1c9f093d
BA
665 })
666 ],
667 vanish: [
668 new PiPo({
669 x: sx,
670 y: sy,
1c58eb76
BA
671 c: initColor,
672 p: initPiece
1c9f093d
BA
673 })
674 ]
675 });
676
677 // The opponent piece disappears if we take it
6808d7a1 678 if (this.board[ex][ey] != V.EMPTY) {
1c9f093d
BA
679 mv.vanish.push(
680 new PiPo({
681 x: ex,
682 y: ey,
6808d7a1
BA
683 c: this.getColor(ex, ey),
684 p: this.getPiece(ex, ey)
1c9f093d
BA
685 })
686 );
687 }
1c5bfdf2 688
1c9f093d
BA
689 return mv;
690 }
691
692 // Generic method to find possible moves of non-pawn pieces:
693 // "sliding or jumping"
6808d7a1 694 getSlideNJumpMoves([x, y], steps, oneStep) {
1c9f093d 695 let moves = [];
6808d7a1 696 outerLoop: for (let step of steps) {
1c9f093d
BA
697 let i = x + step[0];
698 let j = y + step[1];
6808d7a1
BA
699 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
700 moves.push(this.getBasicMove([x, y], [i, j]));
d1be8046 701 if (oneStep) continue outerLoop;
1c9f093d
BA
702 i += step[0];
703 j += step[1];
704 }
6808d7a1
BA
705 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
706 moves.push(this.getBasicMove([x, y], [i, j]));
1c9f093d
BA
707 }
708 return moves;
709 }
710
32f6285e
BA
711 // Special case of en-passant captures: treated separately
712 getEnpassantCaptures([x, y], shiftX) {
713 const Lep = this.epSquares.length;
714 const epSquare = this.epSquares[Lep - 1]; //always at least one element
715 let enpassantMove = null;
716 if (
717 !!epSquare &&
718 epSquare.x == x + shiftX &&
719 Math.abs(epSquare.y - y) == 1
720 ) {
721 enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
722 enpassantMove.vanish.push({
723 x: x,
724 y: epSquare.y,
8c1ec210 725 // Captured piece is usually a pawn, but next line seems harmless
6f2f9437 726 p: this.getPiece(x, epSquare.y),
32f6285e
BA
727 c: this.getColor(x, epSquare.y)
728 });
729 }
730 return !!enpassantMove ? [enpassantMove] : [];
731 }
732
1c58eb76
BA
733 // Consider all potential promotions:
734 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
735 let finalPieces = [V.PAWN];
af34341d 736 const color = this.turn; //this.getColor(x1, y1);
1c58eb76
BA
737 const lastRank = (color == "w" ? 0 : V.size.x - 1);
738 if (x2 == lastRank) {
739 // promotions arg: special override for Hiddenqueen variant
740 if (!!promotions) finalPieces = promotions;
741 else if (!!V.PawnSpecs.promotions)
742 finalPieces = V.PawnSpecs.promotions;
743 }
744 let tr = null;
745 for (let piece of finalPieces) {
746 tr = (piece != V.PAWN ? { c: color, p: piece } : null);
747 moves.push(this.getBasicMove([x1, y1], [x2, y2], tr));
748 }
749 }
750
1c9f093d 751 // What are the pawn moves from square x,y ?
32f6285e 752 getPotentialPawnMoves([x, y], promotions) {
af34341d 753 const color = this.turn; //this.getColor(x, y);
6808d7a1 754 const [sizeX, sizeY] = [V.size.x, V.size.y];
32f6285e 755 const pawnShiftX = V.PawnSpecs.directions[color];
1c58eb76 756 const firstRank = (color == "w" ? sizeX - 1 : 0);
32f6285e
BA
757
758 // Pawn movements in shiftX direction:
759 const getPawnMoves = (shiftX) => {
760 let moves = [];
761 // NOTE: next condition is generally true (no pawn on last rank)
762 if (x + shiftX >= 0 && x + shiftX < sizeX) {
763 if (this.board[x + shiftX][y] == V.EMPTY) {
764 // One square forward
1c58eb76 765 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
32f6285e
BA
766 // Next condition because pawns on 1st rank can generally jump
767 if (
768 V.PawnSpecs.twoSquares &&
472c0c4f
BA
769 (
770 (color == 'w' && x >= V.size.x - 1 - V.PawnSpecs.initShift['w'])
771 ||
772 (color == 'b' && x <= V.PawnSpecs.initShift['b'])
773 )
32f6285e 774 ) {
472c0c4f
BA
775 if (this.board[x + 2 * shiftX][y] == V.EMPTY) {
776 // Two squares jump
777 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
778 if (
779 V.PawnSpecs.threeSquares &&
780 this.board[x + 3 * shiftX][y] == V.EMPTY
781 ) {
782 // Three squares jump
783 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
784 }
785 }
32f6285e
BA
786 }
787 }
788 // Captures
789 if (V.PawnSpecs.canCapture) {
790 for (let shiftY of [-1, 1]) {
791 if (
792 y + shiftY >= 0 &&
793 y + shiftY < sizeY
794 ) {
795 if (
796 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
797 this.canTake([x, y], [x + shiftX, y + shiftY])
798 ) {
1c58eb76
BA
799 this.addPawnMoves(
800 [x, y], [x + shiftX, y + shiftY],
801 moves, promotions
802 );
32f6285e
BA
803 }
804 if (
805 V.PawnSpecs.captureBackward &&
806 x - shiftX >= 0 && x - shiftX < V.size.x &&
807 this.board[x - shiftX][y + shiftY] != V.EMPTY &&
808 this.canTake([x, y], [x - shiftX, y + shiftY])
809 ) {
1c58eb76
BA
810 this.addPawnMoves(
811 [x, y], [x + shiftX, y + shiftY],
812 moves, promotions
813 );
32f6285e
BA
814 }
815 }
1c9f093d
BA
816 }
817 }
818 }
32f6285e 819 return moves;
1c9f093d
BA
820 }
821
32f6285e
BA
822 let pMoves = getPawnMoves(pawnShiftX);
823 if (V.PawnSpecs.bidirectional)
824 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
825
6808d7a1 826 if (V.HasEnpassant) {
32f6285e
BA
827 // NOTE: backward en-passant captures are not considered
828 // because no rules define them (for now).
829 Array.prototype.push.apply(
830 pMoves,
831 this.getEnpassantCaptures([x, y], pawnShiftX)
832 );
1c9f093d 833 }
294fe29f 834
32f6285e 835 return pMoves;
1c9f093d
BA
836 }
837
838 // What are the rook moves from square x,y ?
6808d7a1 839 getPotentialRookMoves(sq) {
1c9f093d
BA
840 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
841 }
842
843 // What are the knight moves from square x,y ?
6808d7a1 844 getPotentialKnightMoves(sq) {
1c9f093d
BA
845 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
846 }
847
848 // What are the bishop moves from square x,y ?
6808d7a1 849 getPotentialBishopMoves(sq) {
1c9f093d
BA
850 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
851 }
852
853 // What are the queen moves from square x,y ?
6808d7a1
BA
854 getPotentialQueenMoves(sq) {
855 return this.getSlideNJumpMoves(
856 sq,
857 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
858 );
1c9f093d
BA
859 }
860
861 // What are the king moves from square x,y ?
6808d7a1 862 getPotentialKingMoves(sq) {
1c9f093d 863 // Initialize with normal moves
c583ef1c 864 let moves = this.getSlideNJumpMoves(
6808d7a1
BA
865 sq,
866 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
867 "oneStep"
868 );
c583ef1c
BA
869 if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq));
870 return moves;
1c9f093d
BA
871 }
872
a6836242
BA
873 // "castleInCheck" arg to let some variants castle under check
874 getCastleMoves([x, y], castleInCheck) {
6808d7a1
BA
875 const c = this.getColor(x, y);
876 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
1c9f093d
BA
877 return []; //x isn't first rank, or king has moved (shortcut)
878
879 // Castling ?
880 const oppCol = V.GetOppCol(c);
881 let moves = [];
882 let i = 0;
9bd6786b 883 // King, then rook:
6808d7a1
BA
884 const finalSquares = [
885 [2, 3],
886 [V.size.y - 2, V.size.y - 3]
9bd6786b 887 ];
6808d7a1
BA
888 castlingCheck: for (
889 let castleSide = 0;
890 castleSide < 2;
891 castleSide++ //large, then small
892 ) {
3a2a7b5f 893 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
3f22c2c3 894 // If this code is reached, rook and king are on initial position
1c9f093d 895
2c5d7b20 896 // NOTE: in some variants this is not a rook
32f6285e 897 const rookPos = this.castleFlags[c][castleSide];
61656127
BA
898 if (this.board[x][rookPos] == V.EMPTY || this.getColor(x, rookPos) != c)
899 // Rook is not here, or changed color (see Benedict)
32f6285e
BA
900 continue;
901
2beba6db 902 // Nothing on the path of the king ? (and no checks)
61656127 903 const castlingPiece = this.getPiece(x, rookPos);
2beba6db
BA
904 const finDist = finalSquares[castleSide][0] - y;
905 let step = finDist / Math.max(1, Math.abs(finDist));
906 i = y;
6808d7a1
BA
907 do {
908 if (
5e1bc651
BA
909 // NOTE: "castling" arg is used by some variants (Monster),
910 // where "isAttacked" is overloaded in an infinite-recursive way.
911 (!castleInCheck && this.isAttacked([x, i], oppCol, "castling")) ||
6808d7a1
BA
912 (this.board[x][i] != V.EMPTY &&
913 // NOTE: next check is enough, because of chessboard constraints
914 (this.getColor(x, i) != c ||
a6836242 915 ![V.KING, castlingPiece].includes(this.getPiece(x, i))))
6808d7a1 916 ) {
1c9f093d
BA
917 continue castlingCheck;
918 }
2beba6db 919 i += step;
6808d7a1 920 } while (i != finalSquares[castleSide][0]);
1c9f093d
BA
921
922 // Nothing on the path to the rook?
6808d7a1 923 step = castleSide == 0 ? -1 : 1;
3a2a7b5f 924 for (i = y + step; i != rookPos; i += step) {
6808d7a1 925 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
1c9f093d 926 }
1c9f093d
BA
927
928 // Nothing on final squares, except maybe king and castling rook?
6808d7a1
BA
929 for (i = 0; i < 2; i++) {
930 if (
5e1bc651 931 finalSquares[castleSide][i] != rookPos &&
6808d7a1 932 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
5e1bc651
BA
933 (
934 this.getPiece(x, finalSquares[castleSide][i]) != V.KING ||
935 this.getColor(x, finalSquares[castleSide][i]) != c
936 )
6808d7a1 937 ) {
1c9f093d
BA
938 continue castlingCheck;
939 }
940 }
941
942 // If this code is reached, castle is valid
6808d7a1
BA
943 moves.push(
944 new Move({
945 appear: [
2c5d7b20
BA
946 new PiPo({
947 x: x,
948 y: finalSquares[castleSide][0],
949 p: V.KING,
950 c: c
951 }),
952 new PiPo({
953 x: x,
954 y: finalSquares[castleSide][1],
955 p: castlingPiece,
956 c: c
957 })
6808d7a1
BA
958 ],
959 vanish: [
960 new PiPo({ x: x, y: y, p: V.KING, c: c }),
a6836242 961 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
6808d7a1
BA
962 ],
963 end:
964 Math.abs(y - rookPos) <= 2
965 ? { x: x, y: rookPos }
966 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
967 })
968 );
1c9f093d
BA
969 }
970
971 return moves;
972 }
973
974 ////////////////////
975 // MOVES VALIDATION
976
977 // For the interface: possible moves for the current turn from square sq
6808d7a1
BA
978 getPossibleMovesFrom(sq) {
979 return this.filterValid(this.getPotentialMovesFrom(sq));
1c9f093d
BA
980 }
981
982 // TODO: promotions (into R,B,N,Q) should be filtered only once
6808d7a1
BA
983 filterValid(moves) {
984 if (moves.length == 0) return [];
1c9f093d
BA
985 const color = this.turn;
986 return moves.filter(m => {
987 this.play(m);
988 const res = !this.underCheck(color);
989 this.undo(m);
990 return res;
991 });
992 }
993
5e1bc651 994 getAllPotentialMoves() {
1c9f093d 995 const color = this.turn;
1c9f093d 996 let potentialMoves = [];
6808d7a1
BA
997 for (let i = 0; i < V.size.x; i++) {
998 for (let j = 0; j < V.size.y; j++) {
156986e6 999 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
6808d7a1
BA
1000 Array.prototype.push.apply(
1001 potentialMoves,
1002 this.getPotentialMovesFrom([i, j])
1003 );
1c9f093d
BA
1004 }
1005 }
1006 }
5e1bc651
BA
1007 return potentialMoves;
1008 }
1009
1010 // Search for all valid moves considering current turn
1011 // (for engine and game end)
1012 getAllValidMoves() {
1013 return this.filterValid(this.getAllPotentialMoves());
1c9f093d
BA
1014 }
1015
1016 // Stop at the first move found
2c5d7b20 1017 // TODO: not really, it explores all moves from a square (one is enough).
6808d7a1 1018 atLeastOneMove() {
1c9f093d 1019 const color = this.turn;
6808d7a1
BA
1020 for (let i = 0; i < V.size.x; i++) {
1021 for (let j = 0; j < V.size.y; j++) {
665eed90 1022 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
6808d7a1
BA
1023 const moves = this.getPotentialMovesFrom([i, j]);
1024 if (moves.length > 0) {
107dc1bd 1025 for (let k = 0; k < moves.length; k++)
6808d7a1 1026 if (this.filterValid([moves[k]]).length > 0) return true;
1c9f093d
BA
1027 }
1028 }
1029 }
1030 }
1031 return false;
1032 }
1033
68e19a44
BA
1034 // Check if pieces of given color are attacking (king) on square x,y
1035 isAttacked(sq, color) {
6808d7a1 1036 return (
68e19a44
BA
1037 this.isAttackedByPawn(sq, color) ||
1038 this.isAttackedByRook(sq, color) ||
1039 this.isAttackedByKnight(sq, color) ||
1040 this.isAttackedByBishop(sq, color) ||
1041 this.isAttackedByQueen(sq, color) ||
1042 this.isAttackedByKing(sq, color)
6808d7a1 1043 );
1c9f093d
BA
1044 }
1045
d1be8046 1046 // Generic method for non-pawn pieces ("sliding or jumping"):
68e19a44
BA
1047 // is x,y attacked by a piece of given color ?
1048 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
d1be8046
BA
1049 for (let step of steps) {
1050 let rx = x + step[0],
1051 ry = y + step[1];
1052 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1053 rx += step[0];
1054 ry += step[1];
1055 }
1056 if (
1057 V.OnBoard(rx, ry) &&
68e19a44
BA
1058 this.getPiece(rx, ry) == piece &&
1059 this.getColor(rx, ry) == color
d1be8046
BA
1060 ) {
1061 return true;
1062 }
1063 }
1064 return false;
1065 }
1066
68e19a44 1067 // Is square x,y attacked by 'color' pawns ?
107dc1bd 1068 isAttackedByPawn(sq, color) {
68e19a44 1069 const pawnShift = (color == "w" ? 1 : -1);
107dc1bd
BA
1070 return this.isAttackedBySlideNJump(
1071 sq,
1072 color,
1073 V.PAWN,
1074 [[pawnShift, 1], [pawnShift, -1]],
1075 "oneStep"
1076 );
1c9f093d
BA
1077 }
1078
68e19a44
BA
1079 // Is square x,y attacked by 'color' rooks ?
1080 isAttackedByRook(sq, color) {
1081 return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]);
1c9f093d
BA
1082 }
1083
68e19a44
BA
1084 // Is square x,y attacked by 'color' knights ?
1085 isAttackedByKnight(sq, color) {
6808d7a1
BA
1086 return this.isAttackedBySlideNJump(
1087 sq,
68e19a44 1088 color,
6808d7a1
BA
1089 V.KNIGHT,
1090 V.steps[V.KNIGHT],
1091 "oneStep"
1092 );
1c9f093d
BA
1093 }
1094
68e19a44
BA
1095 // Is square x,y attacked by 'color' bishops ?
1096 isAttackedByBishop(sq, color) {
1097 return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]);
1c9f093d
BA
1098 }
1099
68e19a44
BA
1100 // Is square x,y attacked by 'color' queens ?
1101 isAttackedByQueen(sq, color) {
6808d7a1
BA
1102 return this.isAttackedBySlideNJump(
1103 sq,
68e19a44 1104 color,
6808d7a1
BA
1105 V.QUEEN,
1106 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1107 );
1c9f093d
BA
1108 }
1109
68e19a44
BA
1110 // Is square x,y attacked by 'color' king(s) ?
1111 isAttackedByKing(sq, color) {
6808d7a1
BA
1112 return this.isAttackedBySlideNJump(
1113 sq,
68e19a44 1114 color,
6808d7a1
BA
1115 V.KING,
1116 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1117 "oneStep"
1118 );
1c9f093d
BA
1119 }
1120
1c9f093d 1121 // Is color under check after his move ?
6808d7a1 1122 underCheck(color) {
1c58eb76 1123 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1c9f093d
BA
1124 }
1125
1126 /////////////////
1127 // MOVES PLAYING
1128
1129 // Apply a move on board
6808d7a1
BA
1130 static PlayOnBoard(board, move) {
1131 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
1132 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
1133 }
1134 // Un-apply the played move
6808d7a1
BA
1135 static UndoOnBoard(board, move) {
1136 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
1137 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
1138 }
1139
3a2a7b5f
BA
1140 prePlay() {}
1141
1142 play(move) {
1143 // DEBUG:
1144// if (!this.states) this.states = [];
1c58eb76 1145// const stateFen = this.getFen() + JSON.stringify(this.kingPos);
3a2a7b5f
BA
1146// this.states.push(stateFen);
1147
1148 this.prePlay(move);
2c5d7b20
BA
1149 // Save flags (for undo)
1150 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
3a2a7b5f
BA
1151 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1152 V.PlayOnBoard(this.board, move);
1153 this.turn = V.GetOppCol(this.turn);
1154 this.movesCount++;
1155 this.postPlay(move);
1156 }
1157
bb688df5 1158 updateCastleFlags(move, piece) {
1c58eb76
BA
1159 const c = V.GetOppCol(this.turn);
1160 const firstRank = (c == "w" ? V.size.x - 1 : 0);
1161 // Update castling flags if rooks are moved
c7550017 1162 const oppCol = this.turn;
1c58eb76 1163 const oppFirstRank = V.size.x - 1 - firstRank;
bb688df5
BA
1164 if (piece == V.KING && move.appear.length > 0)
1165 this.castleFlags[c] = [V.size.y, V.size.y];
1166 else if (
1c58eb76
BA
1167 move.start.x == firstRank && //our rook moves?
1168 this.castleFlags[c].includes(move.start.y)
1169 ) {
1170 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
1171 this.castleFlags[c][flagIdx] = V.size.y;
305ede7e
BA
1172 }
1173 // NOTE: not "else if" because a rook could take an opposing rook
1174 if (
1c58eb76
BA
1175 move.end.x == oppFirstRank && //we took opponent rook?
1176 this.castleFlags[oppCol].includes(move.end.y)
1177 ) {
1178 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
1179 this.castleFlags[oppCol][flagIdx] = V.size.y;
1180 }
1181 }
1182
1c9f093d 1183 // After move is played, update variables + flags
3a2a7b5f
BA
1184 postPlay(move) {
1185 const c = V.GetOppCol(this.turn);
1c9f093d 1186 let piece = undefined;
3a2a7b5f 1187 if (move.vanish.length >= 1)
1c9f093d
BA
1188 // Usual case, something is moved
1189 piece = move.vanish[0].p;
3a2a7b5f 1190 else
1c9f093d
BA
1191 // Crazyhouse-like variants
1192 piece = move.appear[0].p;
1c9f093d
BA
1193
1194 // Update king position + flags
6808d7a1 1195 if (piece == V.KING && move.appear.length > 0) {
1c9f093d
BA
1196 this.kingPos[c][0] = move.appear[0].x;
1197 this.kingPos[c][1] = move.appear[0].y;
1c9f093d 1198 }
bb688df5 1199 if (V.HasCastle) this.updateCastleFlags(move, piece);
1c9f093d
BA
1200 }
1201
3a2a7b5f 1202 preUndo() {}
1c9f093d 1203
6808d7a1 1204 undo(move) {
3a2a7b5f 1205 this.preUndo(move);
6808d7a1
BA
1206 if (V.HasEnpassant) this.epSquares.pop();
1207 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1c9f093d
BA
1208 V.UndoOnBoard(this.board, move);
1209 this.turn = V.GetOppCol(this.turn);
1210 this.movesCount--;
3a2a7b5f 1211 this.postUndo(move);
1c9f093d
BA
1212
1213 // DEBUG:
1c58eb76 1214// const stateFen = this.getFen() + JSON.stringify(this.kingPos);
9bd6786b
BA
1215// if (stateFen != this.states[this.states.length-1]) debugger;
1216// this.states.pop();
1c9f093d
BA
1217 }
1218
3a2a7b5f
BA
1219 // After move is undo-ed *and flags resetted*, un-update other variables
1220 // TODO: more symmetry, by storing flags increment in move (?!)
1221 postUndo(move) {
1222 // (Potentially) Reset king position
1223 const c = this.getColor(move.start.x, move.start.y);
1224 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1225 this.kingPos[c] = [move.start.x, move.start.y];
1226 }
1227
1c9f093d
BA
1228 ///////////////
1229 // END OF GAME
1230
1231 // What is the score ? (Interesting if game is over)
6808d7a1 1232 getCurrentScore() {
bb688df5 1233 if (this.atLeastOneMove()) return "*";
1c9f093d
BA
1234 // Game over
1235 const color = this.turn;
1236 // No valid move: stalemate or checkmate?
bb688df5 1237 if (!this.underCheck(color)) return "1/2";
1c9f093d 1238 // OK, checkmate
68e19a44 1239 return (color == "w" ? "0-1" : "1-0");
1c9f093d
BA
1240 }
1241
1242 ///////////////
1243 // ENGINE PLAY
1244
1245 // Pieces values
6808d7a1 1246 static get VALUES() {
1c9f093d 1247 return {
6808d7a1
BA
1248 p: 1,
1249 r: 5,
1250 n: 3,
1251 b: 3,
1252 q: 9,
1253 k: 1000
1c9f093d
BA
1254 };
1255 }
1256
1257 // "Checkmate" (unreachable eval)
6808d7a1
BA
1258 static get INFINITY() {
1259 return 9999;
1260 }
1c9f093d
BA
1261
1262 // At this value or above, the game is over
6808d7a1
BA
1263 static get THRESHOLD_MATE() {
1264 return V.INFINITY;
1265 }
1c9f093d 1266
2c5d7b20 1267 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
6808d7a1
BA
1268 static get SEARCH_DEPTH() {
1269 return 3;
1270 }
1c9f093d 1271
af34341d
BA
1272 // 'movesList' arg for some variants to provide a custom list
1273 getComputerMove(movesList) {
1c9f093d
BA
1274 const maxeval = V.INFINITY;
1275 const color = this.turn;
af34341d 1276 let moves1 = movesList || this.getAllValidMoves();
c322a844 1277
6808d7a1 1278 if (moves1.length == 0)
e71161fb 1279 // TODO: this situation should not happen
41cb9b94 1280 return null;
1c9f093d 1281
b83a675a 1282 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
6808d7a1 1283 for (let i = 0; i < moves1.length; i++) {
afbf3ca7
BA
1284 this.play(moves1[i]);
1285 const score1 = this.getCurrentScore();
1286 if (score1 != "*") {
1287 moves1[i].eval =
1288 score1 == "1/2"
1289 ? 0
1290 : (score1 == "1-0" ? 1 : -1) * maxeval;
1291 }
1292 if (V.SEARCH_DEPTH == 1 || score1 != "*") {
1293 if (!moves1[i].eval) moves1[i].eval = this.evalPosition();
1294 this.undo(moves1[i]);
b83a675a
BA
1295 continue;
1296 }
1c9f093d 1297 // Initial self evaluation is very low: "I'm checkmated"
6808d7a1 1298 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
afbf3ca7
BA
1299 // Initial enemy evaluation is very low too, for him
1300 let eval2 = (color == "w" ? 1 : -1) * maxeval;
1301 // Second half-move:
1302 let moves2 = this.getAllValidMoves();
1303 for (let j = 0; j < moves2.length; j++) {
1304 this.play(moves2[j]);
1305 const score2 = this.getCurrentScore();
1306 let evalPos = 0; //1/2 value
1307 switch (score2) {
1308 case "*":
1309 evalPos = this.evalPosition();
1310 break;
1311 case "1-0":
1312 evalPos = maxeval;
1313 break;
1314 case "0-1":
1315 evalPos = -maxeval;
1316 break;
1c9f093d 1317 }
afbf3ca7
BA
1318 if (
1319 (color == "w" && evalPos < eval2) ||
1320 (color == "b" && evalPos > eval2)
1321 ) {
1322 eval2 = evalPos;
1323 }
1324 this.undo(moves2[j]);
1325 }
6808d7a1
BA
1326 if (
1327 (color == "w" && eval2 > moves1[i].eval) ||
1328 (color == "b" && eval2 < moves1[i].eval)
1329 ) {
1c9f093d
BA
1330 moves1[i].eval = eval2;
1331 }
1332 this.undo(moves1[i]);
1333 }
6808d7a1
BA
1334 moves1.sort((a, b) => {
1335 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1336 });
a97bdbda 1337// console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1c9f093d 1338
1c9f093d 1339 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
6808d7a1 1340 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
6808d7a1 1341 for (let i = 0; i < moves1.length; i++) {
1c9f093d
BA
1342 this.play(moves1[i]);
1343 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
6808d7a1
BA
1344 moves1[i].eval =
1345 0.1 * moves1[i].eval +
1346 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1c9f093d
BA
1347 this.undo(moves1[i]);
1348 }
6808d7a1
BA
1349 moves1.sort((a, b) => {
1350 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1351 });
b83a675a 1352 }
1c9f093d 1353
b83a675a 1354 let candidates = [0];
d54f6261
BA
1355 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1356 candidates.push(i);
656b1878 1357 return moves1[candidates[randInt(candidates.length)]];
1c9f093d
BA
1358 }
1359
6808d7a1 1360 alphabeta(depth, alpha, beta) {
1c9f093d
BA
1361 const maxeval = V.INFINITY;
1362 const color = this.turn;
1363 const score = this.getCurrentScore();
1364 if (score != "*")
6808d7a1
BA
1365 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1366 if (depth == 0) return this.evalPosition();
a97bdbda 1367 const moves = this.getAllValidMoves();
6808d7a1
BA
1368 let v = color == "w" ? -maxeval : maxeval;
1369 if (color == "w") {
1370 for (let i = 0; i < moves.length; i++) {
1c9f093d 1371 this.play(moves[i]);
6808d7a1 1372 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1373 this.undo(moves[i]);
1374 alpha = Math.max(alpha, v);
6808d7a1 1375 if (alpha >= beta) break; //beta cutoff
1c9f093d 1376 }
1c5bfdf2 1377 }
6808d7a1 1378 else {
1c5bfdf2 1379 // color=="b"
6808d7a1 1380 for (let i = 0; i < moves.length; i++) {
1c9f093d 1381 this.play(moves[i]);
6808d7a1 1382 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1383 this.undo(moves[i]);
1384 beta = Math.min(beta, v);
6808d7a1 1385 if (alpha >= beta) break; //alpha cutoff
1c9f093d
BA
1386 }
1387 }
1388 return v;
1389 }
1390
6808d7a1 1391 evalPosition() {
1c9f093d
BA
1392 let evaluation = 0;
1393 // Just count material for now
6808d7a1
BA
1394 for (let i = 0; i < V.size.x; i++) {
1395 for (let j = 0; j < V.size.y; j++) {
1396 if (this.board[i][j] != V.EMPTY) {
1397 const sign = this.getColor(i, j) == "w" ? 1 : -1;
1398 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1c9f093d
BA
1399 }
1400 }
1401 }
1402 return evaluation;
1403 }
1404
1405 /////////////////////////
1406 // MOVES + GAME NOTATION
1407 /////////////////////////
1408
1409 // Context: just before move is played, turn hasn't changed
1410 // TODO: un-ambiguous notation (switch on piece type, check directions...)
6808d7a1
BA
1411 getNotation(move) {
1412 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1cd3e362 1413 // Castle
6808d7a1 1414 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1c9f093d
BA
1415
1416 // Translate final square
1417 const finalSquare = V.CoordsToSquare(move.end);
1418
1419 const piece = this.getPiece(move.start.x, move.start.y);
6808d7a1 1420 if (piece == V.PAWN) {
1c9f093d
BA
1421 // Pawn move
1422 let notation = "";
6808d7a1 1423 if (move.vanish.length > move.appear.length) {
1c9f093d
BA
1424 // Capture
1425 const startColumn = V.CoordToColumn(move.start.y);
1426 notation = startColumn + "x" + finalSquare;
78d64531 1427 }
6808d7a1
BA
1428 else notation = finalSquare;
1429 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
78d64531 1430 // Promotion
1c9f093d
BA
1431 notation += "=" + move.appear[0].p.toUpperCase();
1432 return notation;
1433 }
6808d7a1
BA
1434 // Piece movement
1435 return (
1436 piece.toUpperCase() +
1437 (move.vanish.length > move.appear.length ? "x" : "") +
1438 finalSquare
1439 );
1440 }
2c5d7b20
BA
1441
1442 static GetUnambiguousNotation(move) {
1443 // Machine-readable format with all the informations about the move
1444 return (
1445 (!!move.start && V.OnBoard(move.start.x, move.start.y)
1446 ? V.CoordsToSquare(move.start)
1447 : "-"
1448 ) + "." +
1449 (!!move.end && V.OnBoard(move.end.x, move.end.y)
1450 ? V.CoordsToSquare(move.end)
1451 : "-"
1452 ) + " " +
1453 (!!move.appear && move.appear.length > 0
1454 ? move.appear.map(a =>
1455 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1456 : "-"
1457 ) + "/" +
1458 (!!move.vanish && move.vanish.length > 0
1459 ? move.vanish.map(a =>
1460 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1461 : "-"
1462 )
1463 );
1464 }
6808d7a1 1465};