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