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