1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
4 class PiPo
//Piece+Position
6 // o: {piece[p], color[c], posX[x], posY[y]}
16 // TODO: for animation, moves should contains "moving" and "fading" maybe...
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
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
};
31 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
37 return b
; //usual pieces in pieces/ folder
39 // Turn "wb" into "B" (for FEN)
42 return b
[0]=='w' ? b
[1].toUpperCase() : b
[1];
44 // Turn "p" into "bp" (for board)
47 return f
.charCodeAt()<=90 ? "w"+f
.toLowerCase() : "b"+f
;
53 // fen == "position [flags [turn]]"
54 constructor(fen
, moves
)
57 // Use fen string to initialize variables, flags, turn and board
58 const fenParts
= fen
.split(" ");
59 this.board
= V
.GetBoard(fenParts
[0]);
60 this.setFlags(fenParts
[1]); //NOTE: fenParts[1] might be undefined
61 this.setTurn(fenParts
[2]); //Same note
62 this.initVariables(fen
);
65 // Some additional variables from FEN (variant dependant)
68 this.INIT_COL_KING
= {'w':-1, 'b':-1};
69 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
70 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
71 const fenParts
= fen
.split(" ");
72 const position
= fenParts
[0].split("/");
73 for (let i
=0; i
<position
.length
; i
++)
75 let k
= 0; //column index on board
76 for (let j
=0; j
<position
[i
].length
; j
++)
78 switch (position
[i
].charAt(j
))
81 this.kingPos
['b'] = [i
,k
];
82 this.INIT_COL_KING
['b'] = k
;
85 this.kingPos
['w'] = [i
,k
];
86 this.INIT_COL_KING
['w'] = k
;
89 if (this.INIT_COL_ROOK
['b'][0] < 0)
90 this.INIT_COL_ROOK
['b'][0] = k
;
92 this.INIT_COL_ROOK
['b'][1] = k
;
95 if (this.INIT_COL_ROOK
['w'][0] < 0)
96 this.INIT_COL_ROOK
['w'][0] = k
;
98 this.INIT_COL_ROOK
['w'][1] = k
;
101 const num
= parseInt(position
[i
].charAt(j
));
108 const epSq
= (this.moves
.length
> 0 ? this.getEpSquare(this.lastMove
) : undefined);
109 this.epSquares
= [ epSq
];
112 // Check if FEN describe a position
113 static IsGoodFen(fen
)
115 const fenParts
= fen
.split(" ");
116 if (fenParts
.length
== 0 || fenParts
.length
> 3)
119 const position
= fenParts
[0];
120 const rows
= position
.split("/");
121 if (rows
.length
!= V
.size
.x
)
123 for (let row
of rows
)
126 for (let i
=0; i
<row
.length
; i
++)
128 if (V
.PIECES
.includes(row
[i
].toLowerCase()))
132 const num
= parseInt(row
[i
]);
138 if (sumElts
!= V
.size
.y
)
141 // 2) Check flags (if present)
142 if (fenParts
.length
>= 2)
144 if (!V
.IsGoodFlags(fenParts
[1]))
147 // 3) Check turn (if present)
148 if (fenParts
.length
== 3)
150 if (!["w","b"].includes(fenParts
[2]))
157 static IsGoodFlags(flags
)
159 return !!flags
.match(/^[01]{4,4}$/);
162 // Turn diagram fen into double array ["wb","wp","bk",...]
165 const rows
= fen
.split(" ")[0].split("/");
166 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
167 for (let i
=0; i
<rows
.length
; i
++)
170 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
172 const character
= rows
[i
][indexInRow
];
173 const num
= parseInt(character
);
175 j
+= num
; //just shift j
176 else //something at position i,j
177 board
[i
][j
++] = V
.fen2board(character
);
183 // Extract (relevant) flags from fen
186 // white a-castle, h-castle, black a-castle, h-castle
187 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
190 for (let i
=0; i
<4; i
++)
191 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
194 // Initialize turn (white or black)
197 this.turn
= turnflag
|| "w";
203 static get size() { return {x:8, y:8}; }
205 // Two next functions return 'undefined' if called on empty square
206 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
207 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
210 getOppCol(color
) { return (color
=="w" ? "b" : "w"); }
213 const L
= this.moves
.length
;
214 return (L
>0 ? this.moves
[L
-1] : null);
218 static get PAWN() { return 'p'; }
219 static get ROOK() { return 'r'; }
220 static get KNIGHT() { return 'n'; }
221 static get BISHOP() { return 'b'; }
222 static get QUEEN() { return 'q'; }
223 static get KING() { return 'k'; }
226 static get PIECES() {
227 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
231 static get EMPTY() { return ''; }
233 // Some pieces movements
236 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
237 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
238 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
242 // Aggregates flags into one object
244 return this.castleFlags
;
250 this.castleFlags
= flags
;
253 // En-passant square, if any
256 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
257 if (this.getPiece(sx
,sy
) == V
.PAWN
&& Math
.abs(sx
- ex
) == 2)
264 return undefined; //default
267 // Can thing on square1 take thing on square2
268 canTake([x1
,y1
], [x2
,y2
])
270 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
276 // All possible moves from selected square (assumption: color is OK)
277 getPotentialMovesFrom([x
,y
])
279 switch (this.getPiece(x
,y
))
282 return this.getPotentialPawnMoves([x
,y
]);
284 return this.getPotentialRookMoves([x
,y
]);
286 return this.getPotentialKnightMoves([x
,y
]);
288 return this.getPotentialBishopMoves([x
,y
]);
290 return this.getPotentialQueenMoves([x
,y
]);
292 return this.getPotentialKingMoves([x
,y
]);
296 // Build a regular move from its initial and destination squares; tr: transformation
297 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
304 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
305 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
312 c: this.getColor(sx
,sy
),
313 p: this.getPiece(sx
,sy
)
318 // The opponent piece disappears if we take it
319 if (this.board
[ex
][ey
] != V
.EMPTY
)
325 c: this.getColor(ex
,ey
),
326 p: this.getPiece(ex
,ey
)
333 // Is (x,y) on the chessboard?
336 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
339 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
340 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
342 const color
= this.getColor(x
,y
);
345 for (let step
of steps
)
349 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
351 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
352 if (oneStep
!== undefined)
357 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
358 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
363 // What are the pawn moves from square x,y ?
364 getPotentialPawnMoves([x
,y
])
366 const color
= this.turn
;
368 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
369 const shift
= (color
== "w" ? -1 : 1);
370 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
371 const startRank
= (color
== "w" ? sizeX
-2 : 1);
372 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
374 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
377 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
379 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
]));
380 // Next condition because variants with pawns on 1st rank allow them to jump
381 if ([startRank
,firstRank
].includes(x
) && this.board
[x
+2*shift
][y
] == V
.EMPTY
)
384 moves
.push(this.getBasicMove([x
,y
], [x
+2*shift
,y
]));
388 if (y
>0 && this.board
[x
+shift
][y
-1] != V
.EMPTY
389 && this.canTake([x
,y
], [x
+shift
,y
-1]))
391 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
393 if (y
<sizeY
-1 && this.board
[x
+shift
][y
+1] != V
.EMPTY
394 && this.canTake([x
,y
], [x
+shift
,y
+1]))
396 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1]));
400 if (x
+shift
== lastRank
)
403 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
404 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
405 promotionPieces
.forEach(p
=> {
407 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
408 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:pawnColor
,p:p
}));
410 if (y
>0 && this.board
[x
+shift
][y
-1] != V
.EMPTY
411 && this.canTake([x
,y
], [x
+shift
,y
-1]))
413 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:pawnColor
,p:p
}));
415 if (y
<sizeY
-1 && this.board
[x
+shift
][y
+1] != V
.EMPTY
416 && this.canTake([x
,y
], [x
+shift
,y
+1]))
418 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:pawnColor
,p:p
}));
424 const Lep
= this.epSquares
.length
;
425 const epSquare
= (Lep
>0 ? this.epSquares
[Lep
-1] : undefined);
426 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
428 const epStep
= epSquare
.y
- y
;
429 let enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
430 enpassantMove
.vanish
.push({
434 c: this.getColor(x
,y
+epStep
)
436 moves
.push(enpassantMove
);
442 // What are the rook moves from square x,y ?
443 getPotentialRookMoves(sq
)
445 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
448 // What are the knight moves from square x,y ?
449 getPotentialKnightMoves(sq
)
451 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
454 // What are the bishop moves from square x,y ?
455 getPotentialBishopMoves(sq
)
457 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
460 // What are the queen moves from square x,y ?
461 getPotentialQueenMoves(sq
)
463 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
466 // What are the king moves from square x,y ?
467 getPotentialKingMoves(sq
)
469 // Initialize with normal moves
470 let moves
= this.getSlideNJumpMoves(sq
,
471 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
472 return moves
.concat(this.getCastleMoves(sq
));
475 getCastleMoves([x
,y
])
477 const c
= this.getColor(x
,y
);
478 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
479 return []; //x isn't first rank, or king has moved (shortcut)
482 const oppCol
= this.getOppCol(c
);
485 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
487 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
489 if (!this.castleFlags
[c
][castleSide
])
491 // If this code is reached, rooks and king are on initial position
493 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
494 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
495 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
497 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
498 // NOTE: next check is enough, because of chessboard constraints
499 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
501 continue castlingCheck
;
505 // Nothing on the path to the rook?
506 step
= castleSide
== 0 ? -1 : 1;
507 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
509 if (this.board
[x
][i
] != V
.EMPTY
)
510 continue castlingCheck
;
512 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
514 // Nothing on final squares, except maybe king and castling rook?
517 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
518 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
519 finalSquares
[castleSide
][i
] != rookPos
)
521 continue castlingCheck
;
525 // If this code is reached, castle is valid
526 moves
.push( new Move({
528 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
529 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
531 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
532 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
533 end: Math
.abs(y
- rookPos
) <= 2
535 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
545 canIplay(side
, [x
,y
])
547 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
550 getPossibleMovesFrom(sq
)
552 // Assuming color is right (already checked)
553 return this.filterValid( this.getPotentialMovesFrom(sq
) );
556 // TODO: promotions (into R,B,N,Q) should be filtered only once
559 if (moves
.length
== 0)
561 return moves
.filter(m
=> { return !this.underCheck(m
); });
564 // Search for all valid moves considering current turn (for engine and game end)
567 const color
= this.turn
;
568 const oppCol
= this.getOppCol(color
);
569 let potentialMoves
= [];
570 for (let i
=0; i
<V
.size
.x
; i
++)
572 for (let j
=0; j
<V
.size
.y
; j
++)
574 // Next condition "!= oppCol" = harmless hack to work with checkered variant
575 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
576 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
579 // NOTE: prefer lazy undercheck tests, letting the king being taken?
580 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
581 return this.filterValid(potentialMoves
);
584 // Stop at the first move found
587 const color
= this.turn
;
588 const oppCol
= this.getOppCol(color
);
589 for (let i
=0; i
<V
.size
.x
; i
++)
591 for (let j
=0; j
<V
.size
.y
; j
++)
593 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
595 const moves
= this.getPotentialMovesFrom([i
,j
]);
596 if (moves
.length
> 0)
598 for (let k
=0; k
<moves
.length
; k
++)
600 if (this.filterValid([moves
[k
]]).length
> 0)
610 // Check if pieces of color in array 'colors' are attacking square x,y
611 isAttacked(sq
, colors
)
613 return (this.isAttackedByPawn(sq
, colors
)
614 || this.isAttackedByRook(sq
, colors
)
615 || this.isAttackedByKnight(sq
, colors
)
616 || this.isAttackedByBishop(sq
, colors
)
617 || this.isAttackedByQueen(sq
, colors
)
618 || this.isAttackedByKing(sq
, colors
));
621 // Is square x,y attacked by 'colors' pawns ?
622 isAttackedByPawn([x
,y
], colors
)
624 for (let c
of colors
)
626 let pawnShift
= (c
=="w" ? 1 : -1);
627 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
629 for (let i
of [-1,1])
631 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
632 && this.getColor(x
+pawnShift
,y
+i
)==c
)
642 // Is square x,y attacked by 'colors' rooks ?
643 isAttackedByRook(sq
, colors
)
645 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
648 // Is square x,y attacked by 'colors' knights ?
649 isAttackedByKnight(sq
, colors
)
651 return this.isAttackedBySlideNJump(sq
, colors
,
652 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
655 // Is square x,y attacked by 'colors' bishops ?
656 isAttackedByBishop(sq
, colors
)
658 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
661 // Is square x,y attacked by 'colors' queens ?
662 isAttackedByQueen(sq
, colors
)
664 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
665 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
668 // Is square x,y attacked by 'colors' king(s) ?
669 isAttackedByKing(sq
, colors
)
671 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
672 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
675 // Generic method for non-pawn pieces ("sliding or jumping"):
676 // is x,y attacked by a piece of color in array 'colors' ?
677 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
679 for (let step
of steps
)
681 let rx
= x
+step
[0], ry
= y
+step
[1];
682 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
687 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
688 && colors
.includes(this.getColor(rx
,ry
)))
696 // Is current player under check after his move ?
699 const color
= this.turn
;
701 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
706 // On which squares is opponent under check after our move ?
707 getCheckSquares(move)
710 const color
= this.turn
; //opponent
711 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
712 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
718 // Apply a move on board
719 static PlayOnBoard(board
, move)
721 for (let psq
of move.vanish
)
722 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
723 for (let psq
of move.appear
)
724 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
726 // Un-apply the played move
727 static UndoOnBoard(board
, move)
729 for (let psq
of move.appear
)
730 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
731 for (let psq
of move.vanish
)
732 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
735 // Before move is played, update variables + flags
736 updateVariables(move)
738 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
740 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
742 // Update king position + flags
743 if (piece
== V
.KING
&& move.appear
.length
> 0)
745 this.kingPos
[c
][0] = move.appear
[0].x
;
746 this.kingPos
[c
][1] = move.appear
[0].y
;
747 this.castleFlags
[c
] = [false,false];
750 const oppCol
= this.getOppCol(c
);
751 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
752 if (move.start
.x
== firstRank
//our rook moves?
753 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
755 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
756 this.castleFlags
[c
][flagIdx
] = false;
758 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
759 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
761 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
762 this.castleFlags
[oppCol
][flagIdx
] = false;
766 // After move is undo-ed, un-update variables (flags are reset)
767 // TODO: more symmetry, by storing flags increment in move...
768 unupdateVariables(move)
770 // (Potentially) Reset king position
771 const c
= this.getColor(move.start
.x
,move.start
.y
);
772 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
773 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
776 // Hash of position+flags+turn after a move is played (to detect repetitions)
779 return hex_md5(this.getFen());
785 // if (!this.states) this.states = [];
786 // if (!ingame) this.states.push(JSON.stringify(this.board));
789 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
791 move.flags
= JSON
.stringify(this.flags
); //save flags (for undo)
792 this.updateVariables(move);
793 this.moves
.push(move);
794 this.epSquares
.push( this.getEpSquare(move) );
795 V
.PlayOnBoard(this.board
, move);
798 move.hash
= this.getHashState();
803 V
.UndoOnBoard(this.board
, move);
804 this.epSquares
.pop();
806 this.unupdateVariables(move);
807 this.parseFlags(JSON
.parse(move.flags
));
810 // if (JSON.stringify(this.board) != this.states[this.states.length-1])
812 // this.states.pop();
818 // Check for 3 repetitions (position + flags + turn)
821 if (!this.hashStates
)
822 this.hashStates
= {};
824 Object
.values(this.hashStates
).reduce((a
,b
) => { return a
+b
; }, 0)
825 // Update this.hashStates with last move (or all moves if continuation)
826 // NOTE: redundant storage, but faster and moderate size
827 for (let i
=startIndex
; i
<this.moves
.length
; i
++)
829 const move = this.moves
[i
];
830 if (!this.hashStates
[move.hash
])
831 this.hashStates
[move.hash
] = 1;
833 this.hashStates
[move.hash
]++;
835 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
838 // Is game over ? And if yes, what is the score ?
841 if (this.checkRepetition())
844 if (this.atLeastOneMove()) // game not over
848 return this.checkGameEnd();
851 // No moves are possible: compute score
854 const color
= this.turn
;
855 // No valid move: stalemate or checkmate?
856 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
859 return color
== "w" ? "0-1" : "1-0";
866 static get VALUES() {
877 static get INFINITY() {
878 return 9999; //"checkmate" (unreachable eval)
881 static get THRESHOLD_MATE() {
882 // At this value or above, the game is over
886 static get SEARCH_DEPTH() {
887 return 3; //2 for high branching factor, 4 for small (Loser chess)
890 // Assumption: at least one legal move
891 // NOTE: works also for extinction chess because depth is 3...
894 const maxeval
= V
.INFINITY
;
895 const color
= this.turn
;
896 // Some variants may show a bigger moves list to the human (Switching),
897 // thus the argument "computer" below (which is generally ignored)
898 let moves1
= this.getAllValidMoves("computer");
900 // Can I mate in 1 ? (for Magnetic & Extinction)
901 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
903 this.play(moves1
[i
]);
904 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
905 if (!finish
&& !this.atLeastOneMove())
907 // Try mate (for other variants)
908 const score
= this.checkGameEnd();
912 this.undo(moves1
[i
]);
917 // Rank moves using a min-max at depth 2
918 for (let i
=0; i
<moves1
.length
; i
++)
920 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
; //very low, I'm checkmated
921 this.play(moves1
[i
]);
922 let eval2
= undefined;
923 if (this.atLeastOneMove())
925 eval2
= (color
=="w" ? 1 : -1) * maxeval
; //initialized with checkmate value
927 let moves2
= this.getAllValidMoves("computer");
928 for (let j
=0; j
<moves2
.length
; j
++)
930 this.play(moves2
[j
]);
931 let evalPos
= undefined;
932 if (this.atLeastOneMove())
933 evalPos
= this.evalPosition()
936 // Work with scores for Loser variant
937 const score
= this.checkGameEnd();
938 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
940 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
942 this.undo(moves2
[j
]);
947 const score
= this.checkGameEnd();
948 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
950 if ((color
=="w" && eval2
> moves1
[i
].eval
)
951 || (color
=="b" && eval2
< moves1
[i
].eval
))
953 moves1
[i
].eval
= eval2
;
955 this.undo(moves1
[i
]);
957 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
958 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
960 let candidates
= [0]; //indices of candidates moves
961 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
963 let currentBest
= moves1
[_
.sample(candidates
, 1)];
965 // From here, depth >= 3: may take a while, so we control time
966 const timeStart
= Date
.now();
968 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
969 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
)
971 for (let i
=0; i
<moves1
.length
; i
++)
973 if (Date
.now()-timeStart
>= 5000) //more than 5 seconds
974 return currentBest
; //depth 2 at least
975 this.play(moves1
[i
]);
976 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
977 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
978 this.alphabeta(V
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
979 this.undo(moves1
[i
]);
981 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
985 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
988 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
990 return moves1
[_
.sample(candidates
, 1)];
993 alphabeta(depth
, alpha
, beta
)
995 const maxeval
= V
.INFINITY
;
996 const color
= this.turn
;
997 if (!this.atLeastOneMove())
999 switch (this.checkGameEnd())
1004 const score
= this.checkGameEnd();
1005 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1009 return this.evalPosition();
1010 const moves
= this.getAllValidMoves("computer");
1011 let v
= color
=="w" ? -maxeval : maxeval
;
1014 for (let i
=0; i
<moves
.length
; i
++)
1016 this.play(moves
[i
]);
1017 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
1018 this.undo(moves
[i
]);
1019 alpha
= Math
.max(alpha
, v
);
1021 break; //beta cutoff
1026 for (let i
=0; i
<moves
.length
; i
++)
1028 this.play(moves
[i
]);
1029 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
1030 this.undo(moves
[i
]);
1031 beta
= Math
.min(beta
, v
);
1033 break; //alpha cutoff
1042 // Just count material for now
1043 for (let i
=0; i
<V
.size
.x
; i
++)
1045 for (let j
=0; j
<V
.size
.y
; j
++)
1047 if (this.board
[i
][j
] != V
.EMPTY
)
1049 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1050 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1060 // Setup the initial random (assymetric) position
1061 static GenRandInitFen()
1063 let pieces
= { "w": new Array(8), "b": new Array(8) };
1064 // Shuffle pieces on first and last rank
1065 for (let c
of ["w","b"])
1067 let positions
= _
.range(8);
1069 // Get random squares for bishops
1070 let randIndex
= 2 * _
.random(3);
1071 let bishop1Pos
= positions
[randIndex
];
1072 // The second bishop must be on a square of different color
1073 let randIndex_tmp
= 2 * _
.random(3) + 1;
1074 let bishop2Pos
= positions
[randIndex_tmp
];
1075 // Remove chosen squares
1076 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
1077 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
1079 // Get random squares for knights
1080 randIndex
= _
.random(5);
1081 let knight1Pos
= positions
[randIndex
];
1082 positions
.splice(randIndex
, 1);
1083 randIndex
= _
.random(4);
1084 let knight2Pos
= positions
[randIndex
];
1085 positions
.splice(randIndex
, 1);
1087 // Get random square for queen
1088 randIndex
= _
.random(3);
1089 let queenPos
= positions
[randIndex
];
1090 positions
.splice(randIndex
, 1);
1092 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
1093 let rook1Pos
= positions
[0];
1094 let kingPos
= positions
[1];
1095 let rook2Pos
= positions
[2];
1097 // Finally put the shuffled pieces in the board array
1098 pieces
[c
][rook1Pos
] = 'r';
1099 pieces
[c
][knight1Pos
] = 'n';
1100 pieces
[c
][bishop1Pos
] = 'b';
1101 pieces
[c
][queenPos
] = 'q';
1102 pieces
[c
][kingPos
] = 'k';
1103 pieces
[c
][bishop2Pos
] = 'b';
1104 pieces
[c
][knight2Pos
] = 'n';
1105 pieces
[c
][rook2Pos
] = 'r';
1107 return pieces
["b"].join("") +
1108 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1109 pieces
["w"].join("").toUpperCase() +
1110 " 1111 w"; //add flags + turn
1113 // Return current fen according to pieces+colors state
1116 return this.getBaseFen() + " " + this.getFlagsFen() + " " + this.turn
;
1119 // Position part of the FEN string
1123 for (let i
=0; i
<V
.size
.x
; i
++)
1126 for (let j
=0; j
<V
.size
.y
; j
++)
1128 if (this.board
[i
][j
] == V
.EMPTY
)
1134 // Add empty squares in-between
1138 fen
+= V
.board2fen(this.board
[i
][j
]);
1143 // "Flush remainder"
1146 if (i
< V
.size
.x
- 1)
1147 fen
+= "/"; //separate rows
1152 // Flags part of the FEN string
1156 // Add castling flags
1157 for (let i
of ['w','b'])
1159 for (let j
=0; j
<2; j
++)
1160 fen
+= (this.castleFlags
[i
][j
] ? '1' : '0');
1165 // Context: just before move is played, turn hasn't changed
1168 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1169 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1171 // Translate final square
1172 const finalSquare
= String
.fromCharCode(97 + move.end
.y
) + (V
.size
.x
-move.end
.x
);
1174 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1175 if (piece
== V
.PAWN
)
1179 if (move.vanish
.length
> move.appear
.length
)
1182 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1183 notation
= startColumn
+ "x" + finalSquare
;
1186 notation
= finalSquare
;
1187 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1188 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1195 return piece
.toUpperCase() +
1196 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1200 // Complete the usual notation, may be required for de-ambiguification
1201 getLongNotation(move)
1204 String
.fromCharCode(97 + move.start
.y
) + (V
.size
.x
-move.start
.x
);
1205 const finalSquare
= String
.fromCharCode(97 + move.end
.y
) + (V
.size
.x
-move.end
.x
);
1206 return startSquare
+ finalSquare
; //not encoding move. But short+long is enough
1209 // The score is already computed when calling this function
1210 getPGN(mycolor
, score
, fenStart
, mode
)
1213 pgn
+= '[Site "vchess.club"]<br>';
1214 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1215 pgn
+= '[Variant "' + variant
+ '"]<br>';
1216 pgn
+= '[Date "' + getDate(new Date()) + '"]<br>';
1217 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1218 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1219 pgn
+= '[FenStart "' + fenStart
+ '"]<br>';
1220 pgn
+= '[Fen "' + this.getFen() + '"]<br>';
1221 pgn
+= '[Result "' + score
+ '"]<br><br>';
1224 for (let i
=0; i
<this.moves
.length
; i
++)
1227 pgn
+= ((i
/2)+1) + ".";
1228 pgn
+= this.moves
[i
].notation
[0] + " ";
1232 // "Complete moves" PGN (helping in ambiguous cases)
1233 for (let i
=0; i
<this.moves
.length
; i
++)
1236 pgn
+= ((i
/2)+1) + ".";
1237 pgn
+= this.moves
[i
].notation
[1] + " ";