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