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