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