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