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