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