Some thoughts on Chakart + fix Hiddenqueen moves notation + better moveslist display
[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 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
84 get showFirstTurn() {
85 return false;
86 }
87
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
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
115 // Some variants use click infos:
116 doClick() {
117 return null;
118 }
119
120 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
121 hoverHighlight() {
122 return false;
123 }
124
125 static get IMAGE_EXTENSION() {
126 // All pieces should be in the SVG format
127 return ".svg";
128 }
129
130 // Turn "wb" into "B" (for FEN)
131 static board2fen(b) {
132 return b[0] == "w" ? b[1].toUpperCase() : b[1];
133 }
134
135 // Turn "p" into "bp" (for board)
136 static fen2board(f) {
137 return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f;
138 }
139
140 // Check if FEN describes a board situation correctly
141 static IsGoodFen(fen) {
142 const fenParsed = V.ParseFen(fen);
143 // 1) Check position
144 if (!V.IsGoodPosition(fenParsed.position)) return false;
145 // 2) Check turn
146 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
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
154 if (
155 V.HasEnpassant &&
156 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
157 ) {
158 return false;
159 }
160 return true;
161 }
162
163 // Is position part of the FEN a priori correct?
164 static IsGoodPosition(position) {
165 if (position.length == 0) return false;
166 const rows = position.split("/");
167 if (rows.length != V.size.x) return false;
168 let kings = { "k": 0, "K": 0 };
169 for (let row of rows) {
170 let sumElts = 0;
171 for (let i = 0; i < row.length; i++) {
172 if (['K','k'].includes(row[i])) kings[row[i]]++;
173 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
174 else {
175 const num = parseInt(row[i]);
176 if (isNaN(num)) return false;
177 sumElts += num;
178 }
179 }
180 if (sumElts != V.size.y) return false;
181 }
182 // Both kings should be on board. Exactly one per color.
183 if (Object.values(kings).some(v => v != 1)) return false;
184 return true;
185 }
186
187 // For FEN checking
188 static IsGoodTurn(turn) {
189 return ["w", "b"].includes(turn);
190 }
191
192 // For FEN checking
193 static IsGoodFlags(flags) {
194 // NOTE: a little too permissive to work with more variants
195 return !!flags.match(/^[a-z]{4,4}$/);
196 }
197
198 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
199 static IsGoodEnpassant(enpassant) {
200 if (enpassant != "-") {
201 const ep = V.SquareToCoords(enpassant);
202 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
203 }
204 return true;
205 }
206
207 // 3 --> d (column number to letter)
208 static CoordToColumn(colnum) {
209 return String.fromCharCode(97 + colnum);
210 }
211
212 // d --> 3 (column letter to number)
213 static ColumnToCoord(column) {
214 return column.charCodeAt(0) - 97;
215 }
216
217 // a4 --> {x:3,y:0}
218 static SquareToCoords(sq) {
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
228 static CoordsToSquare(coords) {
229 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
230 }
231
232 // Path to pieces (standard ones in pieces/ folder)
233 getPpath(b) {
234 return b;
235 }
236
237 // Path to promotion pieces (usually the same)
238 getPPpath(m) {
239 return this.getPpath(m.appear[0].c + m.appear[0].p);
240 }
241
242 // Aggregates flags into one object
243 aggregateFlags() {
244 return this.castleFlags;
245 }
246
247 // Reverse operation
248 disaggregateFlags(flags) {
249 this.castleFlags = flags;
250 }
251
252 // En-passant square, if any
253 getEpSquare(moveOrSquare) {
254 if (!moveOrSquare) return undefined;
255 if (typeof moveOrSquare === "string") {
256 const square = moveOrSquare;
257 if (square == "-") return undefined;
258 return V.SquareToCoords(square);
259 }
260 // Argument is a move:
261 const move = moveOrSquare;
262 const s = move.start,
263 e = move.end;
264 if (
265 s.y == e.y &&
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)
270 ) {
271 return {
272 x: (s.x + e.x) / 2,
273 y: s.y
274 };
275 }
276 return undefined; //default
277 }
278
279 // Can thing on square1 take thing on square2
280 canTake([x1, y1], [x2, y2]) {
281 return this.getColor(x1, y1) !== this.getColor(x2, y2);
282 }
283
284 // Is (x,y) on the chessboard?
285 static OnBoard(x, y) {
286 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
287 }
288
289 // Used in interface: 'side' arg == player color
290 canIplay(side, [x, y]) {
291 return this.turn == side && this.getColor(x, y) == side;
292 }
293
294 // On which squares is color under check ? (for interface)
295 getCheckSquares() {
296 const color = this.turn;
297 return (
298 this.underCheck(color)
299 // kingPos must be duplicated, because it may change:
300 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
301 : []
302 );
303 }
304
305 /////////////
306 // FEN UTILS
307
308 // Setup the initial random (asymmetric) position
309 static GenRandInitFen(randomness) {
310 if (randomness == 0)
311 // Deterministic:
312 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
313
314 let pieces = { w: new Array(8), b: new Array(8) };
315 let flags = "";
316 // Shuffle pieces on first (and last rank if randomness == 2)
317 for (let c of ["w", "b"]) {
318 if (c == 'b' && randomness == 1) {
319 pieces['b'] = pieces['w'];
320 flags += flags;
321 break;
322 }
323
324 let positions = ArrayFun.range(8);
325
326 // Get random squares for bishops
327 let randIndex = 2 * randInt(4);
328 const bishop1Pos = positions[randIndex];
329 // The second bishop must be on a square of different color
330 let randIndex_tmp = 2 * randInt(4) + 1;
331 const bishop2Pos = positions[randIndex_tmp];
332 // Remove chosen squares
333 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
334 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
335
336 // Get random squares for knights
337 randIndex = randInt(6);
338 const knight1Pos = positions[randIndex];
339 positions.splice(randIndex, 1);
340 randIndex = randInt(5);
341 const knight2Pos = positions[randIndex];
342 positions.splice(randIndex, 1);
343
344 // Get random square for queen
345 randIndex = randInt(4);
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
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";
364 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
365 }
366 // Add turn + flags + enpassant
367 return (
368 pieces["b"].join("") +
369 "/pppppppp/8/8/8/8/PPPPPPPP/" +
370 pieces["w"].join("").toUpperCase() +
371 " w 0 " + flags + " -"
372 );
373 }
374
375 // "Parse" FEN: just return untransformed string data
376 static ParseFen(fen) {
377 const fenParts = fen.split(" ");
378 let res = {
379 position: fenParts[0],
380 turn: fenParts[1],
381 movesCount: fenParts[2]
382 };
383 let nextIdx = 3;
384 if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] });
385 if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] });
386 return res;
387 }
388
389 // Return current fen (game state)
390 getFen() {
391 return (
392 this.getBaseFen() + " " +
393 this.getTurnFen() + " " +
394 this.movesCount +
395 (V.HasFlags ? " " + this.getFlagsFen() : "") +
396 (V.HasEnpassant ? " " + this.getEnpassantFen() : "")
397 );
398 }
399
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
410 // Position part of the FEN string
411 getBaseFen() {
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 };
419 let position = "";
420 for (let i = 0; i < V.size.x; i++) {
421 let emptyCount = 0;
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) {
426 // Add empty squares in-between
427 position += format(emptyCount);
428 emptyCount = 0;
429 }
430 position += V.board2fen(this.board[i][j]);
431 }
432 }
433 if (emptyCount > 0) {
434 // "Flush remainder"
435 position += format(emptyCount);
436 }
437 if (i < V.size.x - 1) position += "/"; //separate rows
438 }
439 return position;
440 }
441
442 getTurnFen() {
443 return this.turn;
444 }
445
446 // Flags part of the FEN string
447 getFlagsFen() {
448 let flags = "";
449 // Castling flags
450 for (let c of ["w", "b"])
451 flags += this.castleFlags[c].map(V.CoordToColumn).join("");
452 return flags;
453 }
454
455 // Enpassant part of the FEN string
456 getEnpassantFen() {
457 const L = this.epSquares.length;
458 if (!this.epSquares[L - 1]) return "-"; //no en-passant
459 return V.CoordsToSquare(this.epSquares[L - 1]);
460 }
461
462 // Turn position fen into double array ["wb","wp","bk",...]
463 static GetBoard(position) {
464 const rows = position.split("/");
465 let board = ArrayFun.init(V.size.x, V.size.y, "");
466 for (let i = 0; i < rows.length; i++) {
467 let j = 0;
468 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
469 const character = rows[i][indexInRow];
470 const num = parseInt(character);
471 // If num is a number, just shift j:
472 if (!isNaN(num)) j += num;
473 // Else: something at position i,j
474 else board[i][j++] = V.fen2board(character);
475 }
476 }
477 return board;
478 }
479
480 // Extract (relevant) flags from fen
481 setFlags(fenflags) {
482 // white a-castle, h-castle, black a-castle, h-castle
483 this.castleFlags = { w: [-1, -1], b: [-1, -1] };
484 for (let i = 0; i < 4; i++) {
485 this.castleFlags[i < 2 ? "w" : "b"][i % 2] =
486 V.ColumnToCoord(fenflags.charAt(i));
487 }
488 }
489
490 //////////////////
491 // INITIALIZATION
492
493 // Fen string fully describes the game state
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;
499 const fenParsed = V.ParseFen(fen);
500 this.board = V.GetBoard(fenParsed.position);
501 this.turn = fenParsed.turn;
502 this.movesCount = parseInt(fenParsed.movesCount);
503 this.setOtherVariables(fen);
504 }
505
506 // Scan board for kings positions
507 scanKings(fen) {
508 this.INIT_COL_KING = { w: -1, b: -1 };
509 // Squares of white and black king:
510 this.kingPos = { w: [-1, -1], b: [-1, -1] };
511 const fenRows = V.ParseFen(fen).position.split("/");
512 const startRow = { 'w': V.size.x - 1, 'b': 0 };
513 for (let i = 0; i < fenRows.length; i++) {
514 let k = 0; //column index on board
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;
520 break;
521 case "K":
522 this.kingPos["w"] = [i, k];
523 this.INIT_COL_KING["w"] = k;
524 break;
525 default: {
526 const num = parseInt(fenRows[i].charAt(j));
527 if (!isNaN(num)) k += num - 1;
528 }
529 }
530 k++;
531 }
532 }
533 }
534
535 // Some additional variables from FEN (variant dependant)
536 setOtherVariables(fen) {
537 // Set flags and enpassant:
538 const parsedFen = V.ParseFen(fen);
539 if (V.HasFlags) this.setFlags(parsedFen.flags);
540 if (V.HasEnpassant) {
541 const epSq =
542 parsedFen.enpassant != "-"
543 ? this.getEpSquare(parsedFen.enpassant)
544 : undefined;
545 this.epSquares = [epSq];
546 }
547 // Search for kings positions:
548 this.scanKings(fen);
549 }
550
551 /////////////////////
552 // GETTERS & SETTERS
553
554 static get size() {
555 return { x: 8, y: 8 };
556 }
557
558 // Color of thing on square (i,j). 'undefined' if square is empty
559 getColor(i, j) {
560 return this.board[i][j].charAt(0);
561 }
562
563 // Piece type on square (i,j). 'undefined' if square is empty
564 getPiece(i, j) {
565 return this.board[i][j].charAt(1);
566 }
567
568 // Get opponent color
569 static GetOppCol(color) {
570 return color == "w" ? "b" : "w";
571 }
572
573 // Pieces codes (for a clearer code)
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 }
592
593 // For FEN checking:
594 static get PIECES() {
595 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
596 }
597
598 // Empty square
599 static get EMPTY() {
600 return "";
601 }
602
603 // Some pieces movements
604 static get steps() {
605 return {
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 ]
628 };
629 }
630
631 ////////////////////
632 // MOVES GENERATION
633
634 // All possible moves from selected square
635 getPotentialMovesFrom([x, y]) {
636 switch (this.getPiece(x, y)) {
637 case V.PAWN:
638 return this.getPotentialPawnMoves([x, y]);
639 case V.ROOK:
640 return this.getPotentialRookMoves([x, y]);
641 case V.KNIGHT:
642 return this.getPotentialKnightMoves([x, y]);
643 case V.BISHOP:
644 return this.getPotentialBishopMoves([x, y]);
645 case V.QUEEN:
646 return this.getPotentialQueenMoves([x, y]);
647 case V.KING:
648 return this.getPotentialKingMoves([x, y]);
649 }
650 return []; //never reached
651 }
652
653 // Build a regular move from its initial and destination squares.
654 // tr: transformation
655 getBasicMove([sx, sy], [ex, ey], tr) {
656 const initColor = this.getColor(sx, sy);
657 const initPiece = this.getPiece(sx, sy);
658 let mv = new Move({
659 appear: [
660 new PiPo({
661 x: ex,
662 y: ey,
663 c: tr ? tr.c : initColor,
664 p: tr ? tr.p : initPiece
665 })
666 ],
667 vanish: [
668 new PiPo({
669 x: sx,
670 y: sy,
671 c: initColor,
672 p: initPiece
673 })
674 ]
675 });
676
677 // The opponent piece disappears if we take it
678 if (this.board[ex][ey] != V.EMPTY) {
679 mv.vanish.push(
680 new PiPo({
681 x: ex,
682 y: ey,
683 c: this.getColor(ex, ey),
684 p: this.getPiece(ex, ey)
685 })
686 );
687 }
688
689 return mv;
690 }
691
692 // Generic method to find possible moves of non-pawn pieces:
693 // "sliding or jumping"
694 getSlideNJumpMoves([x, y], steps, oneStep) {
695 let moves = [];
696 outerLoop: for (let step of steps) {
697 let i = x + step[0];
698 let j = y + step[1];
699 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
700 moves.push(this.getBasicMove([x, y], [i, j]));
701 if (oneStep) continue outerLoop;
702 i += step[0];
703 j += step[1];
704 }
705 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
706 moves.push(this.getBasicMove([x, y], [i, j]));
707 }
708 return moves;
709 }
710
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,
725 // Captured piece is usually a pawn, but next line seems harmless
726 p: this.getPiece(x, epSquare.y),
727 c: this.getColor(x, epSquare.y)
728 });
729 }
730 return !!enpassantMove ? [enpassantMove] : [];
731 }
732
733 // Consider all potential promotions:
734 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
735 let finalPieces = [V.PAWN];
736 const color = this.turn; //this.getColor(x1, y1);
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
751 // What are the pawn moves from square x,y ?
752 getPotentialPawnMoves([x, y], promotions) {
753 const color = this.turn; //this.getColor(x, y);
754 const [sizeX, sizeY] = [V.size.x, V.size.y];
755 const pawnShiftX = V.PawnSpecs.directions[color];
756 const firstRank = (color == "w" ? sizeX - 1 : 0);
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
765 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
766 // Next condition because pawns on 1st rank can generally jump
767 if (
768 V.PawnSpecs.twoSquares &&
769 (
770 (color == 'w' && x >= V.size.x - 1 - V.PawnSpecs.initShift['w'])
771 ||
772 (color == 'b' && x <= V.PawnSpecs.initShift['b'])
773 )
774 ) {
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 }
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 ) {
799 this.addPawnMoves(
800 [x, y], [x + shiftX, y + shiftY],
801 moves, promotions
802 );
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 ) {
810 this.addPawnMoves(
811 [x, y], [x + shiftX, y + shiftY],
812 moves, promotions
813 );
814 }
815 }
816 }
817 }
818 }
819 return moves;
820 }
821
822 let pMoves = getPawnMoves(pawnShiftX);
823 if (V.PawnSpecs.bidirectional)
824 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
825
826 if (V.HasEnpassant) {
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 );
833 }
834
835 return pMoves;
836 }
837
838 // What are the rook moves from square x,y ?
839 getPotentialRookMoves(sq) {
840 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
841 }
842
843 // What are the knight moves from square x,y ?
844 getPotentialKnightMoves(sq) {
845 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
846 }
847
848 // What are the bishop moves from square x,y ?
849 getPotentialBishopMoves(sq) {
850 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
851 }
852
853 // What are the queen moves from square x,y ?
854 getPotentialQueenMoves(sq) {
855 return this.getSlideNJumpMoves(
856 sq,
857 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
858 );
859 }
860
861 // What are the king moves from square x,y ?
862 getPotentialKingMoves(sq) {
863 // Initialize with normal moves
864 let moves = this.getSlideNJumpMoves(
865 sq,
866 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
867 "oneStep"
868 );
869 if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq));
870 return moves;
871 }
872
873 // "castleInCheck" arg to let some variants castle under check
874 getCastleMoves([x, y], castleInCheck) {
875 const c = this.getColor(x, y);
876 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
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;
883 // King, then rook:
884 const finalSquares = [
885 [2, 3],
886 [V.size.y - 2, V.size.y - 3]
887 ];
888 castlingCheck: for (
889 let castleSide = 0;
890 castleSide < 2;
891 castleSide++ //large, then small
892 ) {
893 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
894 // If this code is reached, rook and king are on initial position
895
896 // NOTE: in some variants this is not a rook
897 const rookPos = this.castleFlags[c][castleSide];
898 if (this.board[x][rookPos] == V.EMPTY || this.getColor(x, rookPos) != c)
899 // Rook is not here, or changed color (see Benedict)
900 continue;
901
902 // Nothing on the path of the king ? (and no checks)
903 const castlingPiece = this.getPiece(x, rookPos);
904 const finDist = finalSquares[castleSide][0] - y;
905 let step = finDist / Math.max(1, Math.abs(finDist));
906 i = y;
907 do {
908 if (
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")) ||
912 (this.board[x][i] != V.EMPTY &&
913 // NOTE: next check is enough, because of chessboard constraints
914 (this.getColor(x, i) != c ||
915 ![V.KING, castlingPiece].includes(this.getPiece(x, i))))
916 ) {
917 continue castlingCheck;
918 }
919 i += step;
920 } while (i != finalSquares[castleSide][0]);
921
922 // Nothing on the path to the rook?
923 step = castleSide == 0 ? -1 : 1;
924 for (i = y + step; i != rookPos; i += step) {
925 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
926 }
927
928 // Nothing on final squares, except maybe king and castling rook?
929 for (i = 0; i < 2; i++) {
930 if (
931 finalSquares[castleSide][i] != rookPos &&
932 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
933 (
934 this.getPiece(x, finalSquares[castleSide][i]) != V.KING ||
935 this.getColor(x, finalSquares[castleSide][i]) != c
936 )
937 ) {
938 continue castlingCheck;
939 }
940 }
941
942 // If this code is reached, castle is valid
943 moves.push(
944 new Move({
945 appear: [
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 })
958 ],
959 vanish: [
960 new PiPo({ x: x, y: y, p: V.KING, c: c }),
961 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
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 );
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
978 getPossibleMovesFrom(sq) {
979 return this.filterValid(this.getPotentialMovesFrom(sq));
980 }
981
982 // TODO: promotions (into R,B,N,Q) should be filtered only once
983 filterValid(moves) {
984 if (moves.length == 0) return [];
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
994 getAllPotentialMoves() {
995 const color = this.turn;
996 let potentialMoves = [];
997 for (let i = 0; i < V.size.x; i++) {
998 for (let j = 0; j < V.size.y; j++) {
999 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
1000 Array.prototype.push.apply(
1001 potentialMoves,
1002 this.getPotentialMovesFrom([i, j])
1003 );
1004 }
1005 }
1006 }
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());
1014 }
1015
1016 // Stop at the first move found
1017 // TODO: not really, it explores all moves from a square (one is enough).
1018 atLeastOneMove() {
1019 const color = this.turn;
1020 for (let i = 0; i < V.size.x; i++) {
1021 for (let j = 0; j < V.size.y; j++) {
1022 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
1023 const moves = this.getPotentialMovesFrom([i, j]);
1024 if (moves.length > 0) {
1025 for (let k = 0; k < moves.length; k++)
1026 if (this.filterValid([moves[k]]).length > 0) return true;
1027 }
1028 }
1029 }
1030 }
1031 return false;
1032 }
1033
1034 // Check if pieces of given color are attacking (king) on square x,y
1035 isAttacked(sq, color) {
1036 return (
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)
1043 );
1044 }
1045
1046 // Generic method for non-pawn pieces ("sliding or jumping"):
1047 // is x,y attacked by a piece of given color ?
1048 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
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) &&
1058 this.getPiece(rx, ry) == piece &&
1059 this.getColor(rx, ry) == color
1060 ) {
1061 return true;
1062 }
1063 }
1064 return false;
1065 }
1066
1067 // Is square x,y attacked by 'color' pawns ?
1068 isAttackedByPawn(sq, color) {
1069 const pawnShift = (color == "w" ? 1 : -1);
1070 return this.isAttackedBySlideNJump(
1071 sq,
1072 color,
1073 V.PAWN,
1074 [[pawnShift, 1], [pawnShift, -1]],
1075 "oneStep"
1076 );
1077 }
1078
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]);
1082 }
1083
1084 // Is square x,y attacked by 'color' knights ?
1085 isAttackedByKnight(sq, color) {
1086 return this.isAttackedBySlideNJump(
1087 sq,
1088 color,
1089 V.KNIGHT,
1090 V.steps[V.KNIGHT],
1091 "oneStep"
1092 );
1093 }
1094
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]);
1098 }
1099
1100 // Is square x,y attacked by 'color' queens ?
1101 isAttackedByQueen(sq, color) {
1102 return this.isAttackedBySlideNJump(
1103 sq,
1104 color,
1105 V.QUEEN,
1106 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1107 );
1108 }
1109
1110 // Is square x,y attacked by 'color' king(s) ?
1111 isAttackedByKing(sq, color) {
1112 return this.isAttackedBySlideNJump(
1113 sq,
1114 color,
1115 V.KING,
1116 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1117 "oneStep"
1118 );
1119 }
1120
1121 // Is color under check after his move ?
1122 underCheck(color) {
1123 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1124 }
1125
1126 /////////////////
1127 // MOVES PLAYING
1128
1129 // Apply a move on board
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;
1133 }
1134 // Un-apply the played move
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;
1138 }
1139
1140 prePlay() {}
1141
1142 play(move) {
1143 // DEBUG:
1144 // if (!this.states) this.states = [];
1145 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1146 // this.states.push(stateFen);
1147
1148 this.prePlay(move);
1149 // Save flags (for undo)
1150 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
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
1158 updateCastleFlags(move, piece) {
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
1162 const oppCol = this.turn;
1163 const oppFirstRank = V.size.x - 1 - firstRank;
1164 if (piece == V.KING && move.appear.length > 0)
1165 this.castleFlags[c] = [V.size.y, V.size.y];
1166 else if (
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;
1172 }
1173 // NOTE: not "else if" because a rook could take an opposing rook
1174 if (
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
1183 // After move is played, update variables + flags
1184 postPlay(move) {
1185 const c = V.GetOppCol(this.turn);
1186 let piece = undefined;
1187 if (move.vanish.length >= 1)
1188 // Usual case, something is moved
1189 piece = move.vanish[0].p;
1190 else
1191 // Crazyhouse-like variants
1192 piece = move.appear[0].p;
1193
1194 // Update king position + flags
1195 if (piece == V.KING && move.appear.length > 0) {
1196 this.kingPos[c][0] = move.appear[0].x;
1197 this.kingPos[c][1] = move.appear[0].y;
1198 }
1199 if (V.HasCastle) this.updateCastleFlags(move, piece);
1200 }
1201
1202 preUndo() {}
1203
1204 undo(move) {
1205 this.preUndo(move);
1206 if (V.HasEnpassant) this.epSquares.pop();
1207 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1208 V.UndoOnBoard(this.board, move);
1209 this.turn = V.GetOppCol(this.turn);
1210 this.movesCount--;
1211 this.postUndo(move);
1212
1213 // DEBUG:
1214 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1215 // if (stateFen != this.states[this.states.length-1]) debugger;
1216 // this.states.pop();
1217 }
1218
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
1228 ///////////////
1229 // END OF GAME
1230
1231 // What is the score ? (Interesting if game is over)
1232 getCurrentScore() {
1233 if (this.atLeastOneMove()) return "*";
1234 // Game over
1235 const color = this.turn;
1236 // No valid move: stalemate or checkmate?
1237 if (!this.underCheck(color)) return "1/2";
1238 // OK, checkmate
1239 return (color == "w" ? "0-1" : "1-0");
1240 }
1241
1242 ///////////////
1243 // ENGINE PLAY
1244
1245 // Pieces values
1246 static get VALUES() {
1247 return {
1248 p: 1,
1249 r: 5,
1250 n: 3,
1251 b: 3,
1252 q: 9,
1253 k: 1000
1254 };
1255 }
1256
1257 // "Checkmate" (unreachable eval)
1258 static get INFINITY() {
1259 return 9999;
1260 }
1261
1262 // At this value or above, the game is over
1263 static get THRESHOLD_MATE() {
1264 return V.INFINITY;
1265 }
1266
1267 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1268 static get SEARCH_DEPTH() {
1269 return 3;
1270 }
1271
1272 // 'movesList' arg for some variants to provide a custom list
1273 getComputerMove(movesList) {
1274 const maxeval = V.INFINITY;
1275 const color = this.turn;
1276 let moves1 = movesList || this.getAllValidMoves();
1277
1278 if (moves1.length == 0)
1279 // TODO: this situation should not happen
1280 return null;
1281
1282 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1283 for (let i = 0; i < moves1.length; i++) {
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]);
1295 continue;
1296 }
1297 // Initial self evaluation is very low: "I'm checkmated"
1298 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
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;
1317 }
1318 if (
1319 (color == "w" && evalPos < eval2) ||
1320 (color == "b" && evalPos > eval2)
1321 ) {
1322 eval2 = evalPos;
1323 }
1324 this.undo(moves2[j]);
1325 }
1326 if (
1327 (color == "w" && eval2 > moves1[i].eval) ||
1328 (color == "b" && eval2 < moves1[i].eval)
1329 ) {
1330 moves1[i].eval = eval2;
1331 }
1332 this.undo(moves1[i]);
1333 }
1334 moves1.sort((a, b) => {
1335 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1336 });
1337 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1338
1339 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1340 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
1341 for (let i = 0; i < moves1.length; i++) {
1342 this.play(moves1[i]);
1343 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1344 moves1[i].eval =
1345 0.1 * moves1[i].eval +
1346 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1347 this.undo(moves1[i]);
1348 }
1349 moves1.sort((a, b) => {
1350 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1351 });
1352 }
1353
1354 let candidates = [0];
1355 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1356 candidates.push(i);
1357 return moves1[candidates[randInt(candidates.length)]];
1358 }
1359
1360 alphabeta(depth, alpha, beta) {
1361 const maxeval = V.INFINITY;
1362 const color = this.turn;
1363 const score = this.getCurrentScore();
1364 if (score != "*")
1365 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1366 if (depth == 0) return this.evalPosition();
1367 const moves = this.getAllValidMoves();
1368 let v = color == "w" ? -maxeval : maxeval;
1369 if (color == "w") {
1370 for (let i = 0; i < moves.length; i++) {
1371 this.play(moves[i]);
1372 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1373 this.undo(moves[i]);
1374 alpha = Math.max(alpha, v);
1375 if (alpha >= beta) break; //beta cutoff
1376 }
1377 }
1378 else {
1379 // color=="b"
1380 for (let i = 0; i < moves.length; i++) {
1381 this.play(moves[i]);
1382 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1383 this.undo(moves[i]);
1384 beta = Math.min(beta, v);
1385 if (alpha >= beta) break; //alpha cutoff
1386 }
1387 }
1388 return v;
1389 }
1390
1391 evalPosition() {
1392 let evaluation = 0;
1393 // Just count material for now
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)];
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...)
1411 getNotation(move) {
1412 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1413 // Castle
1414 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1415
1416 // Translate final square
1417 const finalSquare = V.CoordsToSquare(move.end);
1418
1419 const piece = this.getPiece(move.start.x, move.start.y);
1420 if (piece == V.PAWN) {
1421 // Pawn move
1422 let notation = "";
1423 if (move.vanish.length > move.appear.length) {
1424 // Capture
1425 const startColumn = V.CoordToColumn(move.start.y);
1426 notation = startColumn + "x" + finalSquare;
1427 }
1428 else notation = finalSquare;
1429 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
1430 // Promotion
1431 notation += "=" + move.appear[0].p.toUpperCase();
1432 return notation;
1433 }
1434 // Piece movement
1435 return (
1436 piece.toUpperCase() +
1437 (move.vanish.length > move.appear.length ? "x" : "") +
1438 finalSquare
1439 );
1440 }
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 }
1465 };