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