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