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