A few small fixes + add Monster 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
31 // (from white player perspective)
32 export const ChessRules = class ChessRules {
33 //////////////
34 // MISC UTILS
35
36 // Some variants don't have flags:
37 static get HasFlags() {
38 return true;
39 }
40
41 // Or castle
42 static get HasCastle() {
43 return V.HasFlags;
44 }
45
46 // Pawns specifications
47 static get PawnSpecs() {
48 return {
49 directions: { 'w': -1, 'b': 1 },
50 twoSquares: true,
51 promotions: [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN],
52 canCapture: true,
53 captureBackward: false,
54 bidirectional: false
55 };
56 }
57
58 // En-passant captures need a stack of squares:
59 static get HasEnpassant() {
60 return true;
61 }
62
63 // Some variants cannot have analyse mode
64 static get CanAnalyze() {
65 return true;
66 }
67 // Patch: issues with javascript OOP, objects can't access static fields.
68 get canAnalyze() {
69 return V.CanAnalyze;
70 }
71
72 // Some variants show incomplete information,
73 // and thus show only a partial moves list or no list at all.
74 static get ShowMoves() {
75 return "all";
76 }
77 get showMoves() {
78 return V.ShowMoves;
79 }
80
81 // Some variants always show the same orientation
82 static get CanFlip() {
83 return true;
84 }
85 get canFlip() {
86 return V.CanFlip;
87 }
88
89 // Some variants use click infos:
90 doClick() {
91 return null;
92 }
93
94 static get IMAGE_EXTENSION() {
95 // All pieces should be in the SVG format
96 return ".svg";
97 }
98
99 // Turn "wb" into "B" (for FEN)
100 static board2fen(b) {
101 return b[0] == "w" ? b[1].toUpperCase() : b[1];
102 }
103
104 // Turn "p" into "bp" (for board)
105 static fen2board(f) {
106 return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f;
107 }
108
109 // Check if FEN describes a board situation correctly
110 static IsGoodFen(fen) {
111 const fenParsed = V.ParseFen(fen);
112 // 1) Check position
113 if (!V.IsGoodPosition(fenParsed.position)) return false;
114 // 2) Check turn
115 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
116 // 3) Check moves count
117 if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0))
118 return false;
119 // 4) Check flags
120 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
121 return false;
122 // 5) Check enpassant
123 if (
124 V.HasEnpassant &&
125 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
126 ) {
127 return false;
128 }
129 return true;
130 }
131
132 // Is position part of the FEN a priori correct?
133 static IsGoodPosition(position) {
134 if (position.length == 0) return false;
135 const rows = position.split("/");
136 if (rows.length != V.size.x) return false;
137 let kings = { "k": 0, "K": 0 };
138 for (let row of rows) {
139 let sumElts = 0;
140 for (let i = 0; i < row.length; i++) {
141 if (['K','k'].includes(row[i])) kings[row[i]]++;
142 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
143 else {
144 const num = parseInt(row[i]);
145 if (isNaN(num)) return false;
146 sumElts += num;
147 }
148 }
149 if (sumElts != V.size.y) return false;
150 }
151 // Both kings should be on board. Exactly one per color.
152 if (Object.values(kings).some(v => v != 1)) return false;
153 return true;
154 }
155
156 // For FEN checking
157 static IsGoodTurn(turn) {
158 return ["w", "b"].includes(turn);
159 }
160
161 // For FEN checking
162 static IsGoodFlags(flags) {
163 // NOTE: a little too permissive to work with more variants
164 return !!flags.match(/^[a-z]{4,4}$/);
165 }
166
167 static IsGoodEnpassant(enpassant) {
168 if (enpassant != "-") {
169 const ep = V.SquareToCoords(enpassant);
170 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
171 }
172 return true;
173 }
174
175 // 3 --> d (column number to letter)
176 static CoordToColumn(colnum) {
177 return String.fromCharCode(97 + colnum);
178 }
179
180 // d --> 3 (column letter to number)
181 static ColumnToCoord(column) {
182 return column.charCodeAt(0) - 97;
183 }
184
185 // a4 --> {x:3,y:0}
186 static SquareToCoords(sq) {
187 return {
188 // NOTE: column is always one char => max 26 columns
189 // row is counted from black side => subtraction
190 x: V.size.x - parseInt(sq.substr(1)),
191 y: sq[0].charCodeAt() - 97
192 };
193 }
194
195 // {x:0,y:4} --> e8
196 static CoordsToSquare(coords) {
197 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
198 }
199
200 // Path to pieces (standard ones in pieces/ folder)
201 getPpath(b) {
202 return b;
203 }
204
205 // Path to promotion pieces (usually the same)
206 getPPpath(m) {
207 return this.getPpath(m.appear[0].c + m.appear[0].p);
208 }
209
210 // Aggregates flags into one object
211 aggregateFlags() {
212 return this.castleFlags;
213 }
214
215 // Reverse operation
216 disaggregateFlags(flags) {
217 this.castleFlags = flags;
218 }
219
220 // En-passant square, if any
221 getEpSquare(moveOrSquare) {
222 if (!moveOrSquare) return undefined;
223 if (typeof moveOrSquare === "string") {
224 const square = moveOrSquare;
225 if (square == "-") return undefined;
226 return V.SquareToCoords(square);
227 }
228 // Argument is a move:
229 const move = moveOrSquare;
230 const s = move.start,
231 e = move.end;
232 if (
233 s.y == e.y &&
234 Math.abs(s.x - e.x) == 2 &&
235 // Next conditions for variants like Atomic or Rifle, Recycle...
236 (move.appear.length > 0 && move.appear[0].p == V.PAWN) &&
237 (move.vanish.length > 0 && move.vanish[0].p == V.PAWN)
238 ) {
239 return {
240 x: (s.x + e.x) / 2,
241 y: s.y
242 };
243 }
244 return undefined; //default
245 }
246
247 // Can thing on square1 take thing on square2
248 canTake([x1, y1], [x2, y2]) {
249 return this.getColor(x1, y1) !== this.getColor(x2, y2);
250 }
251
252 // Is (x,y) on the chessboard?
253 static OnBoard(x, y) {
254 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
255 }
256
257 // Used in interface: 'side' arg == player color
258 canIplay(side, [x, y]) {
259 return this.turn == side && this.getColor(x, y) == side;
260 }
261
262 // On which squares is color under check ? (for interface)
263 getCheckSquares(color) {
264 return (
265 this.underCheck(color)
266 // kingPos must be duplicated, because it may change:
267 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
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 // Squares of white and black king:
477 this.kingPos = { w: [-1, -1], b: [-1, -1] };
478 const fenRows = V.ParseFen(fen).position.split("/");
479 const startRow = { 'w': V.size.x - 1, 'b': 0 };
480 for (let i = 0; i < fenRows.length; i++) {
481 let k = 0; //column index on board
482 for (let j = 0; j < fenRows[i].length; j++) {
483 switch (fenRows[i].charAt(j)) {
484 case "k":
485 this.kingPos["b"] = [i, k];
486 this.INIT_COL_KING["b"] = k;
487 break;
488 case "K":
489 this.kingPos["w"] = [i, k];
490 this.INIT_COL_KING["w"] = k;
491 break;
492 default: {
493 const num = parseInt(fenRows[i].charAt(j));
494 if (!isNaN(num)) k += num - 1;
495 }
496 }
497 k++;
498 }
499 }
500 }
501
502 // Some additional variables from FEN (variant dependant)
503 setOtherVariables(fen) {
504 // Set flags and enpassant:
505 const parsedFen = V.ParseFen(fen);
506 if (V.HasFlags) this.setFlags(parsedFen.flags);
507 if (V.HasEnpassant) {
508 const epSq =
509 parsedFen.enpassant != "-"
510 ? this.getEpSquare(parsedFen.enpassant)
511 : undefined;
512 this.epSquares = [epSq];
513 }
514 // Search for kings positions:
515 this.scanKings(fen);
516 }
517
518 /////////////////////
519 // GETTERS & SETTERS
520
521 static get size() {
522 return { x: 8, y: 8 };
523 }
524
525 // Color of thing on square (i,j). 'undefined' if square is empty
526 getColor(i, j) {
527 return this.board[i][j].charAt(0);
528 }
529
530 // Piece type on square (i,j). 'undefined' if square is empty
531 getPiece(i, j) {
532 return this.board[i][j].charAt(1);
533 }
534
535 // Get opponent color
536 static GetOppCol(color) {
537 return color == "w" ? "b" : "w";
538 }
539
540 // Pieces codes (for a clearer code)
541 static get PAWN() {
542 return "p";
543 }
544 static get ROOK() {
545 return "r";
546 }
547 static get KNIGHT() {
548 return "n";
549 }
550 static get BISHOP() {
551 return "b";
552 }
553 static get QUEEN() {
554 return "q";
555 }
556 static get KING() {
557 return "k";
558 }
559
560 // For FEN checking:
561 static get PIECES() {
562 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
563 }
564
565 // Empty square
566 static get EMPTY() {
567 return "";
568 }
569
570 // Some pieces movements
571 static get steps() {
572 return {
573 r: [
574 [-1, 0],
575 [1, 0],
576 [0, -1],
577 [0, 1]
578 ],
579 n: [
580 [-1, -2],
581 [-1, 2],
582 [1, -2],
583 [1, 2],
584 [-2, -1],
585 [-2, 1],
586 [2, -1],
587 [2, 1]
588 ],
589 b: [
590 [-1, -1],
591 [-1, 1],
592 [1, -1],
593 [1, 1]
594 ]
595 };
596 }
597
598 ////////////////////
599 // MOVES GENERATION
600
601 // All possible moves from selected square
602 getPotentialMovesFrom([x, y]) {
603 switch (this.getPiece(x, y)) {
604 case V.PAWN:
605 return this.getPotentialPawnMoves([x, y]);
606 case V.ROOK:
607 return this.getPotentialRookMoves([x, y]);
608 case V.KNIGHT:
609 return this.getPotentialKnightMoves([x, y]);
610 case V.BISHOP:
611 return this.getPotentialBishopMoves([x, y]);
612 case V.QUEEN:
613 return this.getPotentialQueenMoves([x, y]);
614 case V.KING:
615 return this.getPotentialKingMoves([x, y]);
616 }
617 return []; //never reached
618 }
619
620 // Build a regular move from its initial and destination squares.
621 // tr: transformation
622 getBasicMove([sx, sy], [ex, ey], tr) {
623 const initColor = this.getColor(sx, sy);
624 const initPiece = this.getPiece(sx, sy);
625 let mv = new Move({
626 appear: [
627 new PiPo({
628 x: ex,
629 y: ey,
630 c: tr ? tr.c : initColor,
631 p: tr ? tr.p : initPiece
632 })
633 ],
634 vanish: [
635 new PiPo({
636 x: sx,
637 y: sy,
638 c: initColor,
639 p: initPiece
640 })
641 ]
642 });
643
644 // The opponent piece disappears if we take it
645 if (this.board[ex][ey] != V.EMPTY) {
646 mv.vanish.push(
647 new PiPo({
648 x: ex,
649 y: ey,
650 c: this.getColor(ex, ey),
651 p: this.getPiece(ex, ey)
652 })
653 );
654 }
655
656 return mv;
657 }
658
659 // Generic method to find possible moves of non-pawn pieces:
660 // "sliding or jumping"
661 getSlideNJumpMoves([x, y], steps, oneStep) {
662 let moves = [];
663 outerLoop: for (let step of steps) {
664 let i = x + step[0];
665 let j = y + step[1];
666 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
667 moves.push(this.getBasicMove([x, y], [i, j]));
668 if (oneStep) continue outerLoop;
669 i += step[0];
670 j += step[1];
671 }
672 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
673 moves.push(this.getBasicMove([x, y], [i, j]));
674 }
675 return moves;
676 }
677
678 // Special case of en-passant captures: treated separately
679 getEnpassantCaptures([x, y], shiftX) {
680 const Lep = this.epSquares.length;
681 const epSquare = this.epSquares[Lep - 1]; //always at least one element
682 let enpassantMove = null;
683 if (
684 !!epSquare &&
685 epSquare.x == x + shiftX &&
686 Math.abs(epSquare.y - y) == 1
687 ) {
688 enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
689 enpassantMove.vanish.push({
690 x: x,
691 y: epSquare.y,
692 // Captured piece is usually a pawn, but next line seems harmless
693 p: this.getPiece(x, epSquare.y),
694 c: this.getColor(x, epSquare.y)
695 });
696 }
697 return !!enpassantMove ? [enpassantMove] : [];
698 }
699
700 // Consider all potential promotions:
701 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
702 let finalPieces = [V.PAWN];
703 const color = this.turn;
704 const lastRank = (color == "w" ? 0 : V.size.x - 1);
705 if (x2 == lastRank) {
706 // promotions arg: special override for Hiddenqueen variant
707 if (!!promotions) finalPieces = promotions;
708 else if (!!V.PawnSpecs.promotions)
709 finalPieces = V.PawnSpecs.promotions;
710 }
711 let tr = null;
712 for (let piece of finalPieces) {
713 tr = (piece != V.PAWN ? { c: color, p: piece } : null);
714 moves.push(this.getBasicMove([x1, y1], [x2, y2], tr));
715 }
716 }
717
718 // What are the pawn moves from square x,y ?
719 getPotentialPawnMoves([x, y], promotions) {
720 const color = this.turn;
721 const [sizeX, sizeY] = [V.size.x, V.size.y];
722 const pawnShiftX = V.PawnSpecs.directions[color];
723 const firstRank = (color == "w" ? sizeX - 1 : 0);
724 const startRank = (color == "w" ? sizeX - 2 : 1);
725
726 // Pawn movements in shiftX direction:
727 const getPawnMoves = (shiftX) => {
728 let moves = [];
729 // NOTE: next condition is generally true (no pawn on last rank)
730 if (x + shiftX >= 0 && x + shiftX < sizeX) {
731 if (this.board[x + shiftX][y] == V.EMPTY) {
732 // One square forward
733 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
734 // Next condition because pawns on 1st rank can generally jump
735 if (
736 V.PawnSpecs.twoSquares &&
737 [startRank, firstRank].includes(x) &&
738 this.board[x + 2 * shiftX][y] == V.EMPTY
739 ) {
740 // Two squares jump
741 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
742 }
743 }
744 // Captures
745 if (V.PawnSpecs.canCapture) {
746 for (let shiftY of [-1, 1]) {
747 if (
748 y + shiftY >= 0 &&
749 y + shiftY < sizeY
750 ) {
751 if (
752 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
753 this.canTake([x, y], [x + shiftX, y + shiftY])
754 ) {
755 this.addPawnMoves(
756 [x, y], [x + shiftX, y + shiftY],
757 moves, promotions
758 );
759 }
760 if (
761 V.PawnSpecs.captureBackward &&
762 x - shiftX >= 0 && x - shiftX < V.size.x &&
763 this.board[x - shiftX][y + shiftY] != V.EMPTY &&
764 this.canTake([x, y], [x - shiftX, y + shiftY])
765 ) {
766 this.addPawnMoves(
767 [x, y], [x + shiftX, y + shiftY],
768 moves, promotions
769 );
770 }
771 }
772 }
773 }
774 }
775 return moves;
776 }
777
778 let pMoves = getPawnMoves(pawnShiftX);
779 if (V.PawnSpecs.bidirectional)
780 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
781
782 if (V.HasEnpassant) {
783 // NOTE: backward en-passant captures are not considered
784 // because no rules define them (for now).
785 Array.prototype.push.apply(
786 pMoves,
787 this.getEnpassantCaptures([x, y], pawnShiftX)
788 );
789 }
790
791 return pMoves;
792 }
793
794 // What are the rook moves from square x,y ?
795 getPotentialRookMoves(sq) {
796 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
797 }
798
799 // What are the knight moves from square x,y ?
800 getPotentialKnightMoves(sq) {
801 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
802 }
803
804 // What are the bishop moves from square x,y ?
805 getPotentialBishopMoves(sq) {
806 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
807 }
808
809 // What are the queen moves from square x,y ?
810 getPotentialQueenMoves(sq) {
811 return this.getSlideNJumpMoves(
812 sq,
813 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
814 );
815 }
816
817 // What are the king moves from square x,y ?
818 getPotentialKingMoves(sq) {
819 // Initialize with normal moves
820 let moves = this.getSlideNJumpMoves(
821 sq,
822 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
823 "oneStep"
824 );
825 if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq));
826 return moves;
827 }
828
829 // "castleInCheck" arg to let some variants castle under check
830 getCastleMoves([x, y], castleInCheck) {
831 const c = this.getColor(x, y);
832 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
833 return []; //x isn't first rank, or king has moved (shortcut)
834
835 // Castling ?
836 const oppCol = V.GetOppCol(c);
837 let moves = [];
838 let i = 0;
839 // King, then rook:
840 const finalSquares = [
841 [2, 3],
842 [V.size.y - 2, V.size.y - 3]
843 ];
844 castlingCheck: for (
845 let castleSide = 0;
846 castleSide < 2;
847 castleSide++ //large, then small
848 ) {
849 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
850 // If this code is reached, rook and king are on initial position
851
852 // NOTE: in some variants this is not a rook
853 const rookPos = this.castleFlags[c][castleSide];
854 if (this.board[x][rookPos] == V.EMPTY || this.getColor(x, rookPos) != c)
855 // Rook is not here, or changed color (see Benedict)
856 continue;
857
858 // Nothing on the path of the king ? (and no checks)
859 const castlingPiece = this.getPiece(x, rookPos);
860 const finDist = finalSquares[castleSide][0] - y;
861 let step = finDist / Math.max(1, Math.abs(finDist));
862 i = y;
863 do {
864 if (
865 // NOTE: "castling" arg is used by some variants (Monster),
866 // where "isAttacked" is overloaded in an infinite-recursive way.
867 (!castleInCheck && this.isAttacked([x, i], oppCol, "castling")) ||
868 (this.board[x][i] != V.EMPTY &&
869 // NOTE: next check is enough, because of chessboard constraints
870 (this.getColor(x, i) != c ||
871 ![V.KING, castlingPiece].includes(this.getPiece(x, i))))
872 ) {
873 continue castlingCheck;
874 }
875 i += step;
876 } while (i != finalSquares[castleSide][0]);
877
878 // Nothing on the path to the rook?
879 step = castleSide == 0 ? -1 : 1;
880 for (i = y + step; i != rookPos; i += step) {
881 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
882 }
883
884 // Nothing on final squares, except maybe king and castling rook?
885 for (i = 0; i < 2; i++) {
886 if (
887 finalSquares[castleSide][i] != rookPos &&
888 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
889 (
890 this.getPiece(x, finalSquares[castleSide][i]) != V.KING ||
891 this.getColor(x, finalSquares[castleSide][i]) != c
892 )
893 ) {
894 continue castlingCheck;
895 }
896 }
897
898 // If this code is reached, castle is valid
899 moves.push(
900 new Move({
901 appear: [
902 new PiPo({
903 x: x,
904 y: finalSquares[castleSide][0],
905 p: V.KING,
906 c: c
907 }),
908 new PiPo({
909 x: x,
910 y: finalSquares[castleSide][1],
911 p: castlingPiece,
912 c: c
913 })
914 ],
915 vanish: [
916 new PiPo({ x: x, y: y, p: V.KING, c: c }),
917 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
918 ],
919 end:
920 Math.abs(y - rookPos) <= 2
921 ? { x: x, y: rookPos }
922 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
923 })
924 );
925 }
926
927 return moves;
928 }
929
930 ////////////////////
931 // MOVES VALIDATION
932
933 // For the interface: possible moves for the current turn from square sq
934 getPossibleMovesFrom(sq) {
935 return this.filterValid(this.getPotentialMovesFrom(sq));
936 }
937
938 // TODO: promotions (into R,B,N,Q) should be filtered only once
939 filterValid(moves) {
940 if (moves.length == 0) return [];
941 const color = this.turn;
942 return moves.filter(m => {
943 this.play(m);
944 const res = !this.underCheck(color);
945 this.undo(m);
946 return res;
947 });
948 }
949
950 getAllPotentialMoves() {
951 const color = this.turn;
952 let potentialMoves = [];
953 for (let i = 0; i < V.size.x; i++) {
954 for (let j = 0; j < V.size.y; j++) {
955 if (this.getColor(i, j) == color) {
956 Array.prototype.push.apply(
957 potentialMoves,
958 this.getPotentialMovesFrom([i, j])
959 );
960 }
961 }
962 }
963 return potentialMoves;
964 }
965
966 // Search for all valid moves considering current turn
967 // (for engine and game end)
968 getAllValidMoves() {
969 return this.filterValid(this.getAllPotentialMoves());
970 }
971
972 // Stop at the first move found
973 // TODO: not really, it explores all moves from a square (one is enough).
974 atLeastOneMove() {
975 const color = this.turn;
976 for (let i = 0; i < V.size.x; i++) {
977 for (let j = 0; j < V.size.y; j++) {
978 if (this.getColor(i, j) == color) {
979 const moves = this.getPotentialMovesFrom([i, j]);
980 if (moves.length > 0) {
981 for (let k = 0; k < moves.length; k++) {
982 if (this.filterValid([moves[k]]).length > 0) return true;
983 }
984 }
985 }
986 }
987 }
988 return false;
989 }
990
991 // Check if pieces of given color are attacking (king) on square x,y
992 isAttacked(sq, color) {
993 return (
994 this.isAttackedByPawn(sq, color) ||
995 this.isAttackedByRook(sq, color) ||
996 this.isAttackedByKnight(sq, color) ||
997 this.isAttackedByBishop(sq, color) ||
998 this.isAttackedByQueen(sq, color) ||
999 this.isAttackedByKing(sq, color)
1000 );
1001 }
1002
1003 // Generic method for non-pawn pieces ("sliding or jumping"):
1004 // is x,y attacked by a piece of given color ?
1005 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
1006 for (let step of steps) {
1007 let rx = x + step[0],
1008 ry = y + step[1];
1009 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1010 rx += step[0];
1011 ry += step[1];
1012 }
1013 if (
1014 V.OnBoard(rx, ry) &&
1015 this.getPiece(rx, ry) == piece &&
1016 this.getColor(rx, ry) == color
1017 ) {
1018 return true;
1019 }
1020 }
1021 return false;
1022 }
1023
1024 // Is square x,y attacked by 'color' pawns ?
1025 isAttackedByPawn([x, y], color) {
1026 const pawnShift = (color == "w" ? 1 : -1);
1027 if (x + pawnShift >= 0 && x + pawnShift < V.size.x) {
1028 for (let i of [-1, 1]) {
1029 if (
1030 y + i >= 0 &&
1031 y + i < V.size.y &&
1032 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
1033 this.getColor(x + pawnShift, y + i) == color
1034 ) {
1035 return true;
1036 }
1037 }
1038 }
1039 return false;
1040 }
1041
1042 // Is square x,y attacked by 'color' rooks ?
1043 isAttackedByRook(sq, color) {
1044 return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]);
1045 }
1046
1047 // Is square x,y attacked by 'color' knights ?
1048 isAttackedByKnight(sq, color) {
1049 return this.isAttackedBySlideNJump(
1050 sq,
1051 color,
1052 V.KNIGHT,
1053 V.steps[V.KNIGHT],
1054 "oneStep"
1055 );
1056 }
1057
1058 // Is square x,y attacked by 'color' bishops ?
1059 isAttackedByBishop(sq, color) {
1060 return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]);
1061 }
1062
1063 // Is square x,y attacked by 'color' queens ?
1064 isAttackedByQueen(sq, color) {
1065 return this.isAttackedBySlideNJump(
1066 sq,
1067 color,
1068 V.QUEEN,
1069 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1070 );
1071 }
1072
1073 // Is square x,y attacked by 'color' king(s) ?
1074 isAttackedByKing(sq, color) {
1075 return this.isAttackedBySlideNJump(
1076 sq,
1077 color,
1078 V.KING,
1079 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1080 "oneStep"
1081 );
1082 }
1083
1084 // Is color under check after his move ?
1085 underCheck(color) {
1086 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1087 }
1088
1089 /////////////////
1090 // MOVES PLAYING
1091
1092 // Apply a move on board
1093 static PlayOnBoard(board, move) {
1094 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
1095 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1096 }
1097 // Un-apply the played move
1098 static UndoOnBoard(board, move) {
1099 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
1100 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1101 }
1102
1103 prePlay() {}
1104
1105 play(move) {
1106 // DEBUG:
1107 // if (!this.states) this.states = [];
1108 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1109 // this.states.push(stateFen);
1110
1111 this.prePlay(move);
1112 // Save flags (for undo)
1113 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
1114 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1115 V.PlayOnBoard(this.board, move);
1116 this.turn = V.GetOppCol(this.turn);
1117 this.movesCount++;
1118 this.postPlay(move);
1119 }
1120
1121 updateCastleFlags(move, piece) {
1122 const c = V.GetOppCol(this.turn);
1123 const firstRank = (c == "w" ? V.size.x - 1 : 0);
1124 // Update castling flags if rooks are moved
1125 const oppCol = this.turn;
1126 const oppFirstRank = V.size.x - 1 - firstRank;
1127 if (piece == V.KING && move.appear.length > 0)
1128 this.castleFlags[c] = [V.size.y, V.size.y];
1129 else if (
1130 move.start.x == firstRank && //our rook moves?
1131 this.castleFlags[c].includes(move.start.y)
1132 ) {
1133 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
1134 this.castleFlags[c][flagIdx] = V.size.y;
1135 }
1136 // NOTE: not "else if" because a rook could take an opposing rook
1137 if (
1138 move.end.x == oppFirstRank && //we took opponent rook?
1139 this.castleFlags[oppCol].includes(move.end.y)
1140 ) {
1141 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
1142 this.castleFlags[oppCol][flagIdx] = V.size.y;
1143 }
1144 }
1145
1146 // After move is played, update variables + flags
1147 postPlay(move) {
1148 const c = V.GetOppCol(this.turn);
1149 let piece = undefined;
1150 if (move.vanish.length >= 1)
1151 // Usual case, something is moved
1152 piece = move.vanish[0].p;
1153 else
1154 // Crazyhouse-like variants
1155 piece = move.appear[0].p;
1156
1157 // Update king position + flags
1158 if (piece == V.KING && move.appear.length > 0) {
1159 this.kingPos[c][0] = move.appear[0].x;
1160 this.kingPos[c][1] = move.appear[0].y;
1161 return;
1162 }
1163 if (V.HasCastle) this.updateCastleFlags(move, piece);
1164 }
1165
1166 preUndo() {}
1167
1168 undo(move) {
1169 this.preUndo(move);
1170 if (V.HasEnpassant) this.epSquares.pop();
1171 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1172 V.UndoOnBoard(this.board, move);
1173 this.turn = V.GetOppCol(this.turn);
1174 this.movesCount--;
1175 this.postUndo(move);
1176
1177 // DEBUG:
1178 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1179 // if (stateFen != this.states[this.states.length-1]) debugger;
1180 // this.states.pop();
1181 }
1182
1183 // After move is undo-ed *and flags resetted*, un-update other variables
1184 // TODO: more symmetry, by storing flags increment in move (?!)
1185 postUndo(move) {
1186 // (Potentially) Reset king position
1187 const c = this.getColor(move.start.x, move.start.y);
1188 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1189 this.kingPos[c] = [move.start.x, move.start.y];
1190 }
1191
1192 ///////////////
1193 // END OF GAME
1194
1195 // What is the score ? (Interesting if game is over)
1196 getCurrentScore() {
1197 if (this.atLeastOneMove()) return "*";
1198 // Game over
1199 const color = this.turn;
1200 // No valid move: stalemate or checkmate?
1201 if (!this.underCheck(color)) return "1/2";
1202 // OK, checkmate
1203 return (color == "w" ? "0-1" : "1-0");
1204 }
1205
1206 ///////////////
1207 // ENGINE PLAY
1208
1209 // Pieces values
1210 static get VALUES() {
1211 return {
1212 p: 1,
1213 r: 5,
1214 n: 3,
1215 b: 3,
1216 q: 9,
1217 k: 1000
1218 };
1219 }
1220
1221 // "Checkmate" (unreachable eval)
1222 static get INFINITY() {
1223 return 9999;
1224 }
1225
1226 // At this value or above, the game is over
1227 static get THRESHOLD_MATE() {
1228 return V.INFINITY;
1229 }
1230
1231 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1232 static get SEARCH_DEPTH() {
1233 return 3;
1234 }
1235
1236 getComputerMove() {
1237 const maxeval = V.INFINITY;
1238 const color = this.turn;
1239 let moves1 = this.getAllValidMoves();
1240
1241 if (moves1.length == 0)
1242 // TODO: this situation should not happen
1243 return null;
1244
1245 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1246 for (let i = 0; i < moves1.length; i++) {
1247 this.play(moves1[i]);
1248 const score1 = this.getCurrentScore();
1249 if (score1 != "*") {
1250 moves1[i].eval =
1251 score1 == "1/2"
1252 ? 0
1253 : (score1 == "1-0" ? 1 : -1) * maxeval;
1254 }
1255 if (V.SEARCH_DEPTH == 1 || score1 != "*") {
1256 if (!moves1[i].eval) moves1[i].eval = this.evalPosition();
1257 this.undo(moves1[i]);
1258 continue;
1259 }
1260 // Initial self evaluation is very low: "I'm checkmated"
1261 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
1262 // Initial enemy evaluation is very low too, for him
1263 let eval2 = (color == "w" ? 1 : -1) * maxeval;
1264 // Second half-move:
1265 let moves2 = this.getAllValidMoves();
1266 for (let j = 0; j < moves2.length; j++) {
1267 this.play(moves2[j]);
1268 const score2 = this.getCurrentScore();
1269 let evalPos = 0; //1/2 value
1270 switch (score2) {
1271 case "*":
1272 evalPos = this.evalPosition();
1273 break;
1274 case "1-0":
1275 evalPos = maxeval;
1276 break;
1277 case "0-1":
1278 evalPos = -maxeval;
1279 break;
1280 }
1281 if (
1282 (color == "w" && evalPos < eval2) ||
1283 (color == "b" && evalPos > eval2)
1284 ) {
1285 eval2 = evalPos;
1286 }
1287 this.undo(moves2[j]);
1288 }
1289 if (
1290 (color == "w" && eval2 > moves1[i].eval) ||
1291 (color == "b" && eval2 < moves1[i].eval)
1292 ) {
1293 moves1[i].eval = eval2;
1294 }
1295 this.undo(moves1[i]);
1296 }
1297 moves1.sort((a, b) => {
1298 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1299 });
1300 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1301
1302 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1303 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
1304 for (let i = 0; i < moves1.length; i++) {
1305 this.play(moves1[i]);
1306 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1307 moves1[i].eval =
1308 0.1 * moves1[i].eval +
1309 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1310 this.undo(moves1[i]);
1311 }
1312 moves1.sort((a, b) => {
1313 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1314 });
1315 }
1316
1317 let candidates = [0];
1318 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1319 candidates.push(i);
1320 return moves1[candidates[randInt(candidates.length)]];
1321 }
1322
1323 alphabeta(depth, alpha, beta) {
1324 const maxeval = V.INFINITY;
1325 const color = this.turn;
1326 const score = this.getCurrentScore();
1327 if (score != "*")
1328 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1329 if (depth == 0) return this.evalPosition();
1330 const moves = this.getAllValidMoves();
1331 let v = color == "w" ? -maxeval : maxeval;
1332 if (color == "w") {
1333 for (let i = 0; i < moves.length; i++) {
1334 this.play(moves[i]);
1335 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1336 this.undo(moves[i]);
1337 alpha = Math.max(alpha, v);
1338 if (alpha >= beta) break; //beta cutoff
1339 }
1340 }
1341 else {
1342 // color=="b"
1343 for (let i = 0; i < moves.length; i++) {
1344 this.play(moves[i]);
1345 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1346 this.undo(moves[i]);
1347 beta = Math.min(beta, v);
1348 if (alpha >= beta) break; //alpha cutoff
1349 }
1350 }
1351 return v;
1352 }
1353
1354 evalPosition() {
1355 let evaluation = 0;
1356 // Just count material for now
1357 for (let i = 0; i < V.size.x; i++) {
1358 for (let j = 0; j < V.size.y; j++) {
1359 if (this.board[i][j] != V.EMPTY) {
1360 const sign = this.getColor(i, j) == "w" ? 1 : -1;
1361 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1362 }
1363 }
1364 }
1365 return evaluation;
1366 }
1367
1368 /////////////////////////
1369 // MOVES + GAME NOTATION
1370 /////////////////////////
1371
1372 // Context: just before move is played, turn hasn't changed
1373 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1374 getNotation(move) {
1375 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1376 // Castle
1377 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1378
1379 // Translate final square
1380 const finalSquare = V.CoordsToSquare(move.end);
1381
1382 const piece = this.getPiece(move.start.x, move.start.y);
1383 if (piece == V.PAWN) {
1384 // Pawn move
1385 let notation = "";
1386 if (move.vanish.length > move.appear.length) {
1387 // Capture
1388 const startColumn = V.CoordToColumn(move.start.y);
1389 notation = startColumn + "x" + finalSquare;
1390 }
1391 else notation = finalSquare;
1392 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
1393 // Promotion
1394 notation += "=" + move.appear[0].p.toUpperCase();
1395 return notation;
1396 }
1397 // Piece movement
1398 return (
1399 piece.toUpperCase() +
1400 (move.vanish.length > move.appear.length ? "x" : "") +
1401 finalSquare
1402 );
1403 }
1404
1405 static GetUnambiguousNotation(move) {
1406 // Machine-readable format with all the informations about the move
1407 return (
1408 (!!move.start && V.OnBoard(move.start.x, move.start.y)
1409 ? V.CoordsToSquare(move.start)
1410 : "-"
1411 ) + "." +
1412 (!!move.end && V.OnBoard(move.end.x, move.end.y)
1413 ? V.CoordsToSquare(move.end)
1414 : "-"
1415 ) + " " +
1416 (!!move.appear && move.appear.length > 0
1417 ? move.appear.map(a =>
1418 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1419 : "-"
1420 ) + "/" +
1421 (!!move.vanish && move.vanish.length > 0
1422 ? move.vanish.map(a =>
1423 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1424 : "-"
1425 )
1426 );
1427 }
1428 };