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