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