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