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