53001f6373a279f9272876b7e36f09be9746ad8a
[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
811 return pMoves;
812 }
813
814 // What are the rook moves from square x,y ?
815 getPotentialRookMoves(sq) {
816 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
817 }
818
819 // What are the knight moves from square x,y ?
820 getPotentialKnightMoves(sq) {
821 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
822 }
823
824 // What are the bishop moves from square x,y ?
825 getPotentialBishopMoves(sq) {
826 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
827 }
828
829 // What are the queen moves from square x,y ?
830 getPotentialQueenMoves(sq) {
831 return this.getSlideNJumpMoves(
832 sq,
833 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
834 );
835 }
836
837 // What are the king moves from square x,y ?
838 getPotentialKingMoves(sq) {
839 // Initialize with normal moves
840 let moves = this.getSlideNJumpMoves(
841 sq,
842 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
843 "oneStep"
844 );
845 if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq));
846 return moves;
847 }
848
849 // "castleInCheck" arg to let some variants castle under check
850 getCastleMoves([x, y], castleInCheck) {
851 const c = this.getColor(x, y);
852 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
853 return []; //x isn't first rank, or king has moved (shortcut)
854
855 // Castling ?
856 const oppCol = V.GetOppCol(c);
857 let moves = [];
858 let i = 0;
859 // King, then rook:
860 const finalSquares = [
861 [2, 3],
862 [V.size.y - 2, V.size.y - 3]
863 ];
864 castlingCheck: for (
865 let castleSide = 0;
866 castleSide < 2;
867 castleSide++ //large, then small
868 ) {
869 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
870 // If this code is reached, rook and king are on initial position
871
872 // NOTE: in some variants this is not a rook
873 const rookPos = this.castleFlags[c][castleSide];
874 if (this.board[x][rookPos] == V.EMPTY || this.getColor(x, rookPos) != c)
875 // Rook is not here, or changed color (see Benedict)
876 continue;
877
878 // Nothing on the path of the king ? (and no checks)
879 const castlingPiece = this.getPiece(x, rookPos);
880 const finDist = finalSquares[castleSide][0] - y;
881 let step = finDist / Math.max(1, Math.abs(finDist));
882 i = y;
883 do {
884 if (
885 // NOTE: "castling" arg is used by some variants (Monster),
886 // where "isAttacked" is overloaded in an infinite-recursive way.
887 (!castleInCheck && this.isAttacked([x, i], oppCol, "castling")) ||
888 (this.board[x][i] != V.EMPTY &&
889 // NOTE: next check is enough, because of chessboard constraints
890 (this.getColor(x, i) != c ||
891 ![V.KING, castlingPiece].includes(this.getPiece(x, i))))
892 ) {
893 continue castlingCheck;
894 }
895 i += step;
896 } while (i != finalSquares[castleSide][0]);
897
898 // Nothing on the path to the rook?
899 step = castleSide == 0 ? -1 : 1;
900 for (i = y + step; i != rookPos; i += step) {
901 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
902 }
903
904 // Nothing on final squares, except maybe king and castling rook?
905 for (i = 0; i < 2; i++) {
906 if (
907 finalSquares[castleSide][i] != rookPos &&
908 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
909 (
910 this.getPiece(x, finalSquares[castleSide][i]) != V.KING ||
911 this.getColor(x, finalSquares[castleSide][i]) != c
912 )
913 ) {
914 continue castlingCheck;
915 }
916 }
917
918 // If this code is reached, castle is valid
919 moves.push(
920 new Move({
921 appear: [
922 new PiPo({
923 x: x,
924 y: finalSquares[castleSide][0],
925 p: V.KING,
926 c: c
927 }),
928 new PiPo({
929 x: x,
930 y: finalSquares[castleSide][1],
931 p: castlingPiece,
932 c: c
933 })
934 ],
935 vanish: [
936 new PiPo({ x: x, y: y, p: V.KING, c: c }),
937 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
938 ],
939 end:
940 Math.abs(y - rookPos) <= 2
941 ? { x: x, y: rookPos }
942 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
943 })
944 );
945 }
946
947 return moves;
948 }
949
950 ////////////////////
951 // MOVES VALIDATION
952
953 // For the interface: possible moves for the current turn from square sq
954 getPossibleMovesFrom(sq) {
955 return this.filterValid(this.getPotentialMovesFrom(sq));
956 }
957
958 // TODO: promotions (into R,B,N,Q) should be filtered only once
959 filterValid(moves) {
960 if (moves.length == 0) return [];
961 const color = this.turn;
962 return moves.filter(m => {
963 this.play(m);
964 const res = !this.underCheck(color);
965 this.undo(m);
966 return res;
967 });
968 }
969
970 getAllPotentialMoves() {
971 const color = this.turn;
972 let potentialMoves = [];
973 for (let i = 0; i < V.size.x; i++) {
974 for (let j = 0; j < V.size.y; j++) {
975 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
976 Array.prototype.push.apply(
977 potentialMoves,
978 this.getPotentialMovesFrom([i, j])
979 );
980 }
981 }
982 }
983 return potentialMoves;
984 }
985
986 // Search for all valid moves considering current turn
987 // (for engine and game end)
988 getAllValidMoves() {
989 return this.filterValid(this.getAllPotentialMoves());
990 }
991
992 // Stop at the first move found
993 // TODO: not really, it explores all moves from a square (one is enough).
994 atLeastOneMove() {
995 const color = this.turn;
996 for (let i = 0; i < V.size.x; i++) {
997 for (let j = 0; j < V.size.y; j++) {
998 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
999 const moves = this.getPotentialMovesFrom([i, j]);
1000 if (moves.length > 0) {
1001 for (let k = 0; k < moves.length; k++) {
1002 if (this.filterValid([moves[k]]).length > 0) return true;
1003 }
1004 }
1005 }
1006 }
1007 }
1008 return false;
1009 }
1010
1011 // Check if pieces of given color are attacking (king) on square x,y
1012 isAttacked(sq, color) {
1013 return (
1014 this.isAttackedByPawn(sq, color) ||
1015 this.isAttackedByRook(sq, color) ||
1016 this.isAttackedByKnight(sq, color) ||
1017 this.isAttackedByBishop(sq, color) ||
1018 this.isAttackedByQueen(sq, color) ||
1019 this.isAttackedByKing(sq, color)
1020 );
1021 }
1022
1023 // Generic method for non-pawn pieces ("sliding or jumping"):
1024 // is x,y attacked by a piece of given color ?
1025 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
1026 for (let step of steps) {
1027 let rx = x + step[0],
1028 ry = y + step[1];
1029 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1030 rx += step[0];
1031 ry += step[1];
1032 }
1033 if (
1034 V.OnBoard(rx, ry) &&
1035 this.getPiece(rx, ry) == piece &&
1036 this.getColor(rx, ry) == color
1037 ) {
1038 return true;
1039 }
1040 }
1041 return false;
1042 }
1043
1044 // Is square x,y attacked by 'color' pawns ?
1045 isAttackedByPawn([x, y], color) {
1046 const pawnShift = (color == "w" ? 1 : -1);
1047 if (x + pawnShift >= 0 && x + pawnShift < V.size.x) {
1048 for (let i of [-1, 1]) {
1049 if (
1050 y + i >= 0 &&
1051 y + i < V.size.y &&
1052 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
1053 this.getColor(x + pawnShift, y + i) == color
1054 ) {
1055 return true;
1056 }
1057 }
1058 }
1059 return false;
1060 }
1061
1062 // Is square x,y attacked by 'color' rooks ?
1063 isAttackedByRook(sq, color) {
1064 return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]);
1065 }
1066
1067 // Is square x,y attacked by 'color' knights ?
1068 isAttackedByKnight(sq, color) {
1069 return this.isAttackedBySlideNJump(
1070 sq,
1071 color,
1072 V.KNIGHT,
1073 V.steps[V.KNIGHT],
1074 "oneStep"
1075 );
1076 }
1077
1078 // Is square x,y attacked by 'color' bishops ?
1079 isAttackedByBishop(sq, color) {
1080 return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]);
1081 }
1082
1083 // Is square x,y attacked by 'color' queens ?
1084 isAttackedByQueen(sq, color) {
1085 return this.isAttackedBySlideNJump(
1086 sq,
1087 color,
1088 V.QUEEN,
1089 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1090 );
1091 }
1092
1093 // Is square x,y attacked by 'color' king(s) ?
1094 isAttackedByKing(sq, color) {
1095 return this.isAttackedBySlideNJump(
1096 sq,
1097 color,
1098 V.KING,
1099 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1100 "oneStep"
1101 );
1102 }
1103
1104 // Is color under check after his move ?
1105 underCheck(color) {
1106 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1107 }
1108
1109 /////////////////
1110 // MOVES PLAYING
1111
1112 // Apply a move on board
1113 static PlayOnBoard(board, move) {
1114 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
1115 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1116 }
1117 // Un-apply the played move
1118 static UndoOnBoard(board, move) {
1119 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
1120 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1121 }
1122
1123 prePlay() {}
1124
1125 play(move) {
1126 // DEBUG:
1127 // if (!this.states) this.states = [];
1128 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1129 // this.states.push(stateFen);
1130
1131 this.prePlay(move);
1132 // Save flags (for undo)
1133 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
1134 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1135 V.PlayOnBoard(this.board, move);
1136 this.turn = V.GetOppCol(this.turn);
1137 this.movesCount++;
1138 this.postPlay(move);
1139 }
1140
1141 updateCastleFlags(move, piece) {
1142 const c = V.GetOppCol(this.turn);
1143 const firstRank = (c == "w" ? V.size.x - 1 : 0);
1144 // Update castling flags if rooks are moved
1145 const oppCol = this.turn;
1146 const oppFirstRank = V.size.x - 1 - firstRank;
1147 if (piece == V.KING && move.appear.length > 0)
1148 this.castleFlags[c] = [V.size.y, V.size.y];
1149 else if (
1150 move.start.x == firstRank && //our rook moves?
1151 this.castleFlags[c].includes(move.start.y)
1152 ) {
1153 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
1154 this.castleFlags[c][flagIdx] = V.size.y;
1155 }
1156 // NOTE: not "else if" because a rook could take an opposing rook
1157 if (
1158 move.end.x == oppFirstRank && //we took opponent rook?
1159 this.castleFlags[oppCol].includes(move.end.y)
1160 ) {
1161 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
1162 this.castleFlags[oppCol][flagIdx] = V.size.y;
1163 }
1164 }
1165
1166 // After move is played, update variables + flags
1167 postPlay(move) {
1168 const c = V.GetOppCol(this.turn);
1169 let piece = undefined;
1170 if (move.vanish.length >= 1)
1171 // Usual case, something is moved
1172 piece = move.vanish[0].p;
1173 else
1174 // Crazyhouse-like variants
1175 piece = move.appear[0].p;
1176
1177 // Update king position + flags
1178 if (piece == V.KING && move.appear.length > 0) {
1179 this.kingPos[c][0] = move.appear[0].x;
1180 this.kingPos[c][1] = move.appear[0].y;
1181 }
1182 if (V.HasCastle) this.updateCastleFlags(move, piece);
1183 }
1184
1185 preUndo() {}
1186
1187 undo(move) {
1188 this.preUndo(move);
1189 if (V.HasEnpassant) this.epSquares.pop();
1190 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1191 V.UndoOnBoard(this.board, move);
1192 this.turn = V.GetOppCol(this.turn);
1193 this.movesCount--;
1194 this.postUndo(move);
1195
1196 // DEBUG:
1197 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1198 // if (stateFen != this.states[this.states.length-1]) debugger;
1199 // this.states.pop();
1200 }
1201
1202 // After move is undo-ed *and flags resetted*, un-update other variables
1203 // TODO: more symmetry, by storing flags increment in move (?!)
1204 postUndo(move) {
1205 // (Potentially) Reset king position
1206 const c = this.getColor(move.start.x, move.start.y);
1207 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1208 this.kingPos[c] = [move.start.x, move.start.y];
1209 }
1210
1211 ///////////////
1212 // END OF GAME
1213
1214 // What is the score ? (Interesting if game is over)
1215 getCurrentScore() {
1216 if (this.atLeastOneMove()) return "*";
1217 // Game over
1218 const color = this.turn;
1219 // No valid move: stalemate or checkmate?
1220 if (!this.underCheck(color)) return "1/2";
1221 // OK, checkmate
1222 return (color == "w" ? "0-1" : "1-0");
1223 }
1224
1225 ///////////////
1226 // ENGINE PLAY
1227
1228 // Pieces values
1229 static get VALUES() {
1230 return {
1231 p: 1,
1232 r: 5,
1233 n: 3,
1234 b: 3,
1235 q: 9,
1236 k: 1000
1237 };
1238 }
1239
1240 // "Checkmate" (unreachable eval)
1241 static get INFINITY() {
1242 return 9999;
1243 }
1244
1245 // At this value or above, the game is over
1246 static get THRESHOLD_MATE() {
1247 return V.INFINITY;
1248 }
1249
1250 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1251 static get SEARCH_DEPTH() {
1252 return 3;
1253 }
1254
1255 // 'movesList' arg for some variants to provide a custom list
1256 getComputerMove(movesList) {
1257 const maxeval = V.INFINITY;
1258 const color = this.turn;
1259 let moves1 = movesList || this.getAllValidMoves();
1260
1261 if (moves1.length == 0)
1262 // TODO: this situation should not happen
1263 return null;
1264
1265 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1266 for (let i = 0; i < moves1.length; i++) {
1267 this.play(moves1[i]);
1268 const score1 = this.getCurrentScore();
1269 if (score1 != "*") {
1270 moves1[i].eval =
1271 score1 == "1/2"
1272 ? 0
1273 : (score1 == "1-0" ? 1 : -1) * maxeval;
1274 }
1275 if (V.SEARCH_DEPTH == 1 || score1 != "*") {
1276 if (!moves1[i].eval) moves1[i].eval = this.evalPosition();
1277 this.undo(moves1[i]);
1278 continue;
1279 }
1280 // Initial self evaluation is very low: "I'm checkmated"
1281 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
1282 // Initial enemy evaluation is very low too, for him
1283 let eval2 = (color == "w" ? 1 : -1) * maxeval;
1284 // Second half-move:
1285 let moves2 = this.getAllValidMoves();
1286 for (let j = 0; j < moves2.length; j++) {
1287 this.play(moves2[j]);
1288 const score2 = this.getCurrentScore();
1289 let evalPos = 0; //1/2 value
1290 switch (score2) {
1291 case "*":
1292 evalPos = this.evalPosition();
1293 break;
1294 case "1-0":
1295 evalPos = maxeval;
1296 break;
1297 case "0-1":
1298 evalPos = -maxeval;
1299 break;
1300 }
1301 if (
1302 (color == "w" && evalPos < eval2) ||
1303 (color == "b" && evalPos > eval2)
1304 ) {
1305 eval2 = evalPos;
1306 }
1307 this.undo(moves2[j]);
1308 }
1309 if (
1310 (color == "w" && eval2 > moves1[i].eval) ||
1311 (color == "b" && eval2 < moves1[i].eval)
1312 ) {
1313 moves1[i].eval = eval2;
1314 }
1315 this.undo(moves1[i]);
1316 }
1317 moves1.sort((a, b) => {
1318 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1319 });
1320 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1321
1322 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1323 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
1324 for (let i = 0; i < moves1.length; i++) {
1325 this.play(moves1[i]);
1326 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1327 moves1[i].eval =
1328 0.1 * moves1[i].eval +
1329 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1330 this.undo(moves1[i]);
1331 }
1332 moves1.sort((a, b) => {
1333 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1334 });
1335 }
1336
1337 let candidates = [0];
1338 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1339 candidates.push(i);
1340 return moves1[candidates[randInt(candidates.length)]];
1341 }
1342
1343 alphabeta(depth, alpha, beta) {
1344 const maxeval = V.INFINITY;
1345 const color = this.turn;
1346 const score = this.getCurrentScore();
1347 if (score != "*")
1348 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1349 if (depth == 0) return this.evalPosition();
1350 const moves = this.getAllValidMoves();
1351 let v = color == "w" ? -maxeval : maxeval;
1352 if (color == "w") {
1353 for (let i = 0; i < moves.length; i++) {
1354 this.play(moves[i]);
1355 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1356 this.undo(moves[i]);
1357 alpha = Math.max(alpha, v);
1358 if (alpha >= beta) break; //beta cutoff
1359 }
1360 }
1361 else {
1362 // color=="b"
1363 for (let i = 0; i < moves.length; i++) {
1364 this.play(moves[i]);
1365 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1366 this.undo(moves[i]);
1367 beta = Math.min(beta, v);
1368 if (alpha >= beta) break; //alpha cutoff
1369 }
1370 }
1371 return v;
1372 }
1373
1374 evalPosition() {
1375 let evaluation = 0;
1376 // Just count material for now
1377 for (let i = 0; i < V.size.x; i++) {
1378 for (let j = 0; j < V.size.y; j++) {
1379 if (this.board[i][j] != V.EMPTY) {
1380 const sign = this.getColor(i, j) == "w" ? 1 : -1;
1381 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1382 }
1383 }
1384 }
1385 return evaluation;
1386 }
1387
1388 /////////////////////////
1389 // MOVES + GAME NOTATION
1390 /////////////////////////
1391
1392 // Context: just before move is played, turn hasn't changed
1393 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1394 getNotation(move) {
1395 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1396 // Castle
1397 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1398
1399 // Translate final square
1400 const finalSquare = V.CoordsToSquare(move.end);
1401
1402 const piece = this.getPiece(move.start.x, move.start.y);
1403 if (piece == V.PAWN) {
1404 // Pawn move
1405 let notation = "";
1406 if (move.vanish.length > move.appear.length) {
1407 // Capture
1408 const startColumn = V.CoordToColumn(move.start.y);
1409 notation = startColumn + "x" + finalSquare;
1410 }
1411 else notation = finalSquare;
1412 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
1413 // Promotion
1414 notation += "=" + move.appear[0].p.toUpperCase();
1415 return notation;
1416 }
1417 // Piece movement
1418 return (
1419 piece.toUpperCase() +
1420 (move.vanish.length > move.appear.length ? "x" : "") +
1421 finalSquare
1422 );
1423 }
1424
1425 static GetUnambiguousNotation(move) {
1426 // Machine-readable format with all the informations about the move
1427 return (
1428 (!!move.start && V.OnBoard(move.start.x, move.start.y)
1429 ? V.CoordsToSquare(move.start)
1430 : "-"
1431 ) + "." +
1432 (!!move.end && V.OnBoard(move.end.x, move.end.y)
1433 ? V.CoordsToSquare(move.end)
1434 : "-"
1435 ) + " " +
1436 (!!move.appear && move.appear.length > 0
1437 ? move.appear.map(a =>
1438 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1439 : "-"
1440 ) + "/" +
1441 (!!move.vanish && move.vanish.length > 0
1442 ? move.vanish.map(a =>
1443 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1444 : "-"
1445 )
1446 );
1447 }
1448 };