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