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