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 this.epSquares
= [ this.getEpSquare(this.lastMove
|| fenParts
[3]) ];
111 // Check if FEN describe a position
112 static IsGoodFen(fen
)
114 const fenParts
= fen
.split(" ");
115 if (fenParts
.length
== 0)
118 const position
= fenParts
[0];
119 const rows
= position
.split("/");
120 if (rows
.length
!= V
.size
.x
)
122 for (let row
of rows
)
125 for (let i
=0; i
<row
.length
; i
++)
127 if (V
.PIECES
.includes(row
[i
].toLowerCase()))
131 const num
= parseInt(row
[i
]);
137 if (sumElts
!= V
.size
.y
)
140 // 2) Check flags (if present)
141 if (fenParts
.length
>= 2)
143 if (!V
.IsGoodFlags(fenParts
[1]))
146 // 3) Check turn (if present)
147 if (fenParts
.length
>= 3)
149 if (!["w","b"].includes(fenParts
[2]))
156 static IsGoodFlags(flags
)
158 return !!flags
.match(/^[01]{4,4}$/);
161 // Turn diagram fen into double array ["wb","wp","bk",...]
164 const rows
= fen
.split(" ")[0].split("/");
165 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
166 for (let i
=0; i
<rows
.length
; i
++)
169 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
171 const character
= rows
[i
][indexInRow
];
172 const num
= parseInt(character
);
174 j
+= num
; //just shift j
175 else //something at position i,j
176 board
[i
][j
++] = V
.fen2board(character
);
182 // Extract (relevant) flags from fen
185 // white a-castle, h-castle, black a-castle, h-castle
186 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
189 for (let i
=0; i
<4; i
++)
190 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
193 // Initialize turn (white or black)
196 this.turn
= turnflag
|| "w";
202 static get size() { return {x:8, y:8}; }
204 // Two next functions return 'undefined' if called on empty square
205 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
206 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
209 getOppCol(color
) { return (color
=="w" ? "b" : "w"); }
212 const L
= this.moves
.length
;
213 return (L
>0 ? this.moves
[L
-1] : null);
217 static get PAWN() { return 'p'; }
218 static get ROOK() { return 'r'; }
219 static get KNIGHT() { return 'n'; }
220 static get BISHOP() { return 'b'; }
221 static get QUEEN() { return 'q'; }
222 static get KING() { return 'k'; }
225 static get PIECES() {
226 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
230 static get EMPTY() { return ''; }
232 // Some pieces movements
235 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
236 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
237 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
241 // Aggregates flags into one object
243 return this.castleFlags
;
249 this.castleFlags
= flags
;
252 // En-passant square, if any
253 getEpSquare(moveOrSquare
)
255 if (typeof moveOrSquare
=== "string")
257 const square
= moveOrSquare
;
261 x: square
[0].charCodeAt()-97,
262 y: V
.size
.x
-parseInt(square
[1])
265 // Argument is a move:
266 const move = moveOrSquare
;
267 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
268 if (this.getPiece(sx
,sy
) == V
.PAWN
&& Math
.abs(sx
- ex
) == 2)
275 return undefined; //default
278 // Can thing on square1 take thing on square2
279 canTake([x1
,y1
], [x2
,y2
])
281 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
287 // All possible moves from selected square (assumption: color is OK)
288 getPotentialMovesFrom([x
,y
])
290 switch (this.getPiece(x
,y
))
293 return this.getPotentialPawnMoves([x
,y
]);
295 return this.getPotentialRookMoves([x
,y
]);
297 return this.getPotentialKnightMoves([x
,y
]);
299 return this.getPotentialBishopMoves([x
,y
]);
301 return this.getPotentialQueenMoves([x
,y
]);
303 return this.getPotentialKingMoves([x
,y
]);
307 // Build a regular move from its initial and destination squares; tr: transformation
308 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
315 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
316 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
323 c: this.getColor(sx
,sy
),
324 p: this.getPiece(sx
,sy
)
329 // The opponent piece disappears if we take it
330 if (this.board
[ex
][ey
] != V
.EMPTY
)
336 c: this.getColor(ex
,ey
),
337 p: this.getPiece(ex
,ey
)
344 // Is (x,y) on the chessboard?
347 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
350 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
351 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
353 const color
= this.getColor(x
,y
);
356 for (let step
of steps
)
360 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
362 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
363 if (oneStep
!== undefined)
368 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
369 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
374 // What are the pawn moves from square x,y ?
375 getPotentialPawnMoves([x
,y
])
377 const color
= this.turn
;
379 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
380 const shift
= (color
== "w" ? -1 : 1);
381 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
382 const startRank
= (color
== "w" ? sizeX
-2 : 1);
383 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
385 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
388 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
390 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
]));
391 // Next condition because variants with pawns on 1st rank allow them to jump
392 if ([startRank
,firstRank
].includes(x
) && this.board
[x
+2*shift
][y
] == V
.EMPTY
)
395 moves
.push(this.getBasicMove([x
,y
], [x
+2*shift
,y
]));
399 if (y
>0 && this.board
[x
+shift
][y
-1] != V
.EMPTY
400 && this.canTake([x
,y
], [x
+shift
,y
-1]))
402 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
404 if (y
<sizeY
-1 && this.board
[x
+shift
][y
+1] != V
.EMPTY
405 && this.canTake([x
,y
], [x
+shift
,y
+1]))
407 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1]));
411 if (x
+shift
== lastRank
)
414 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
415 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
416 promotionPieces
.forEach(p
=> {
418 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
419 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:pawnColor
,p:p
}));
421 if (y
>0 && this.board
[x
+shift
][y
-1] != V
.EMPTY
422 && this.canTake([x
,y
], [x
+shift
,y
-1]))
424 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:pawnColor
,p:p
}));
426 if (y
<sizeY
-1 && this.board
[x
+shift
][y
+1] != V
.EMPTY
427 && this.canTake([x
,y
], [x
+shift
,y
+1]))
429 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:pawnColor
,p:p
}));
435 const Lep
= this.epSquares
.length
;
436 const epSquare
= (Lep
>0 ? this.epSquares
[Lep
-1] : undefined);
437 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
439 const epStep
= epSquare
.y
- y
;
440 let enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
441 enpassantMove
.vanish
.push({
445 c: this.getColor(x
,y
+epStep
)
447 moves
.push(enpassantMove
);
453 // What are the rook moves from square x,y ?
454 getPotentialRookMoves(sq
)
456 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
459 // What are the knight moves from square x,y ?
460 getPotentialKnightMoves(sq
)
462 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
465 // What are the bishop moves from square x,y ?
466 getPotentialBishopMoves(sq
)
468 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
471 // What are the queen moves from square x,y ?
472 getPotentialQueenMoves(sq
)
474 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
477 // What are the king moves from square x,y ?
478 getPotentialKingMoves(sq
)
480 // Initialize with normal moves
481 let moves
= this.getSlideNJumpMoves(sq
,
482 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
483 return moves
.concat(this.getCastleMoves(sq
));
486 getCastleMoves([x
,y
])
488 const c
= this.getColor(x
,y
);
489 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
490 return []; //x isn't first rank, or king has moved (shortcut)
493 const oppCol
= this.getOppCol(c
);
496 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
498 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
500 if (!this.castleFlags
[c
][castleSide
])
502 // If this code is reached, rooks and king are on initial position
504 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
505 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
506 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
508 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
509 // NOTE: next check is enough, because of chessboard constraints
510 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
512 continue castlingCheck
;
516 // Nothing on the path to the rook?
517 step
= castleSide
== 0 ? -1 : 1;
518 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
520 if (this.board
[x
][i
] != V
.EMPTY
)
521 continue castlingCheck
;
523 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
525 // Nothing on final squares, except maybe king and castling rook?
528 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
529 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
530 finalSquares
[castleSide
][i
] != rookPos
)
532 continue castlingCheck
;
536 // If this code is reached, castle is valid
537 moves
.push( new Move({
539 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
540 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
542 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
543 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
544 end: Math
.abs(y
- rookPos
) <= 2
546 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
556 canIplay(side
, [x
,y
])
558 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
561 getPossibleMovesFrom(sq
)
563 // Assuming color is right (already checked)
564 return this.filterValid( this.getPotentialMovesFrom(sq
) );
567 // TODO: promotions (into R,B,N,Q) should be filtered only once
570 if (moves
.length
== 0)
572 return moves
.filter(m
=> { return !this.underCheck(m
); });
575 // Search for all valid moves considering current turn (for engine and game end)
578 const color
= this.turn
;
579 const oppCol
= this.getOppCol(color
);
580 let potentialMoves
= [];
581 for (let i
=0; i
<V
.size
.x
; i
++)
583 for (let j
=0; j
<V
.size
.y
; j
++)
585 // Next condition "!= oppCol" = harmless hack to work with checkered variant
586 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
587 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
590 // NOTE: prefer lazy undercheck tests, letting the king being taken?
591 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
592 return this.filterValid(potentialMoves
);
595 // Stop at the first move found
598 const color
= this.turn
;
599 const oppCol
= this.getOppCol(color
);
600 for (let i
=0; i
<V
.size
.x
; i
++)
602 for (let j
=0; j
<V
.size
.y
; j
++)
604 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
606 const moves
= this.getPotentialMovesFrom([i
,j
]);
607 if (moves
.length
> 0)
609 for (let k
=0; k
<moves
.length
; k
++)
611 if (this.filterValid([moves
[k
]]).length
> 0)
621 // Check if pieces of color in array 'colors' are attacking square x,y
622 isAttacked(sq
, colors
)
624 return (this.isAttackedByPawn(sq
, colors
)
625 || this.isAttackedByRook(sq
, colors
)
626 || this.isAttackedByKnight(sq
, colors
)
627 || this.isAttackedByBishop(sq
, colors
)
628 || this.isAttackedByQueen(sq
, colors
)
629 || this.isAttackedByKing(sq
, colors
));
632 // Is square x,y attacked by 'colors' pawns ?
633 isAttackedByPawn([x
,y
], colors
)
635 for (let c
of colors
)
637 let pawnShift
= (c
=="w" ? 1 : -1);
638 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
640 for (let i
of [-1,1])
642 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
643 && this.getColor(x
+pawnShift
,y
+i
)==c
)
653 // Is square x,y attacked by 'colors' rooks ?
654 isAttackedByRook(sq
, colors
)
656 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
659 // Is square x,y attacked by 'colors' knights ?
660 isAttackedByKnight(sq
, colors
)
662 return this.isAttackedBySlideNJump(sq
, colors
,
663 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
666 // Is square x,y attacked by 'colors' bishops ?
667 isAttackedByBishop(sq
, colors
)
669 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
672 // Is square x,y attacked by 'colors' queens ?
673 isAttackedByQueen(sq
, colors
)
675 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
676 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
679 // Is square x,y attacked by 'colors' king(s) ?
680 isAttackedByKing(sq
, colors
)
682 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
683 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
686 // Generic method for non-pawn pieces ("sliding or jumping"):
687 // is x,y attacked by a piece of color in array 'colors' ?
688 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
690 for (let step
of steps
)
692 let rx
= x
+step
[0], ry
= y
+step
[1];
693 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
698 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
699 && colors
.includes(this.getColor(rx
,ry
)))
707 // Is current player under check after his move ?
710 const color
= this.turn
;
712 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
717 // On which squares is opponent under check after our move ?
718 getCheckSquares(move)
721 const color
= this.turn
; //opponent
722 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
723 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
729 // Apply a move on board
730 static PlayOnBoard(board
, move)
732 for (let psq
of move.vanish
)
733 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
734 for (let psq
of move.appear
)
735 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
737 // Un-apply the played move
738 static UndoOnBoard(board
, move)
740 for (let psq
of move.appear
)
741 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
742 for (let psq
of move.vanish
)
743 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
746 // Before move is played, update variables + flags
747 updateVariables(move)
749 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
751 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
753 // Update king position + flags
754 if (piece
== V
.KING
&& move.appear
.length
> 0)
756 this.kingPos
[c
][0] = move.appear
[0].x
;
757 this.kingPos
[c
][1] = move.appear
[0].y
;
758 this.castleFlags
[c
] = [false,false];
761 const oppCol
= this.getOppCol(c
);
762 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
763 if (move.start
.x
== firstRank
//our rook moves?
764 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
766 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
767 this.castleFlags
[c
][flagIdx
] = false;
769 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
770 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
772 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
773 this.castleFlags
[oppCol
][flagIdx
] = false;
777 // After move is undo-ed, un-update variables (flags are reset)
778 // TODO: more symmetry, by storing flags increment in move...
779 unupdateVariables(move)
781 // (Potentially) Reset king position
782 const c
= this.getColor(move.start
.x
,move.start
.y
);
783 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
784 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
787 // Hash of position+flags+turn after a move is played (to detect repetitions)
790 return hex_md5(this.getFen());
796 // if (!this.states) this.states = [];
797 // if (!ingame) this.states.push(JSON.stringify(this.board));
800 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
802 move.flags
= JSON
.stringify(this.flags
); //save flags (for undo)
803 this.updateVariables(move);
804 this.moves
.push(move);
805 this.epSquares
.push( this.getEpSquare(move) );
806 this.turn
= this.getOppCol(this.turn
);
807 V
.PlayOnBoard(this.board
, move);
810 move.hash
= this.getHashState();
815 V
.UndoOnBoard(this.board
, move);
816 this.turn
= this.getOppCol(this.turn
);
817 this.epSquares
.pop();
819 this.unupdateVariables(move);
820 this.parseFlags(JSON
.parse(move.flags
));
823 // if (JSON.stringify(this.board) != this.states[this.states.length-1])
825 // this.states.pop();
831 // Check for 3 repetitions (position + flags + turn)
834 if (!this.hashStates
)
835 this.hashStates
= {};
837 Object
.values(this.hashStates
).reduce((a
,b
) => { return a
+b
; }, 0)
838 // Update this.hashStates with last move (or all moves if continuation)
839 // NOTE: redundant storage, but faster and moderate size
840 for (let i
=startIndex
; i
<this.moves
.length
; i
++)
842 const move = this.moves
[i
];
843 if (!this.hashStates
[move.hash
])
844 this.hashStates
[move.hash
] = 1;
846 this.hashStates
[move.hash
]++;
848 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
851 // Is game over ? And if yes, what is the score ?
854 if (this.checkRepetition())
857 if (this.atLeastOneMove()) // game not over
861 return this.checkGameEnd();
864 // No moves are possible: compute score
867 const color
= this.turn
;
868 // No valid move: stalemate or checkmate?
869 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
872 return color
== "w" ? "0-1" : "1-0";
879 static get VALUES() {
890 static get INFINITY() {
891 return 9999; //"checkmate" (unreachable eval)
894 static get THRESHOLD_MATE() {
895 // At this value or above, the game is over
899 static get SEARCH_DEPTH() {
900 return 3; //2 for high branching factor, 4 for small (Loser chess)
903 // Assumption: at least one legal move
904 // NOTE: works also for extinction chess because depth is 3...
907 const maxeval
= V
.INFINITY
;
908 const color
= this.turn
;
909 // Some variants may show a bigger moves list to the human (Switching),
910 // thus the argument "computer" below (which is generally ignored)
911 let moves1
= this.getAllValidMoves("computer");
913 // Can I mate in 1 ? (for Magnetic & Extinction)
914 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
916 this.play(moves1
[i
]);
917 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
918 if (!finish
&& !this.atLeastOneMove())
920 // Try mate (for other variants)
921 const score
= this.checkGameEnd();
925 this.undo(moves1
[i
]);
930 // Rank moves using a min-max at depth 2
931 for (let i
=0; i
<moves1
.length
; i
++)
933 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
; //very low, I'm checkmated
934 this.play(moves1
[i
]);
935 let eval2
= undefined;
936 if (this.atLeastOneMove())
938 eval2
= (color
=="w" ? 1 : -1) * maxeval
; //initialized with checkmate value
940 let moves2
= this.getAllValidMoves("computer");
941 for (let j
=0; j
<moves2
.length
; j
++)
943 this.play(moves2
[j
]);
944 let evalPos
= undefined;
945 if (this.atLeastOneMove())
946 evalPos
= this.evalPosition()
949 // Work with scores for Loser variant
950 const score
= this.checkGameEnd();
951 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
953 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
955 this.undo(moves2
[j
]);
960 const score
= this.checkGameEnd();
961 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
963 if ((color
=="w" && eval2
> moves1
[i
].eval
)
964 || (color
=="b" && eval2
< moves1
[i
].eval
))
966 moves1
[i
].eval
= eval2
;
968 this.undo(moves1
[i
]);
970 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
971 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
973 let candidates
= [0]; //indices of candidates moves
974 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
976 let currentBest
= moves1
[_
.sample(candidates
, 1)];
978 // From here, depth >= 3: may take a while, so we control time
979 const timeStart
= Date
.now();
981 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
982 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
)
984 for (let i
=0; i
<moves1
.length
; i
++)
986 if (Date
.now()-timeStart
>= 5000) //more than 5 seconds
987 return currentBest
; //depth 2 at least
988 this.play(moves1
[i
]);
989 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
990 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
991 this.alphabeta(V
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
992 this.undo(moves1
[i
]);
994 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
998 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1001 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1003 return moves1
[_
.sample(candidates
, 1)];
1006 alphabeta(depth
, alpha
, beta
)
1008 const maxeval
= V
.INFINITY
;
1009 const color
= this.turn
;
1010 if (!this.atLeastOneMove())
1012 switch (this.checkGameEnd())
1017 const score
= this.checkGameEnd();
1018 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1022 return this.evalPosition();
1023 const moves
= this.getAllValidMoves("computer");
1024 let v
= color
=="w" ? -maxeval : maxeval
;
1027 for (let i
=0; i
<moves
.length
; i
++)
1029 this.play(moves
[i
]);
1030 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
1031 this.undo(moves
[i
]);
1032 alpha
= Math
.max(alpha
, v
);
1034 break; //beta cutoff
1039 for (let i
=0; i
<moves
.length
; i
++)
1041 this.play(moves
[i
]);
1042 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
1043 this.undo(moves
[i
]);
1044 beta
= Math
.min(beta
, v
);
1046 break; //alpha cutoff
1055 // Just count material for now
1056 for (let i
=0; i
<V
.size
.x
; i
++)
1058 for (let j
=0; j
<V
.size
.y
; j
++)
1060 if (this.board
[i
][j
] != V
.EMPTY
)
1062 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1063 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1073 // Setup the initial random (assymetric) position
1074 static GenRandInitFen()
1076 let pieces
= { "w": new Array(8), "b": new Array(8) };
1077 // Shuffle pieces on first and last rank
1078 for (let c
of ["w","b"])
1080 let positions
= _
.range(8);
1082 // Get random squares for bishops
1083 let randIndex
= 2 * _
.random(3);
1084 let bishop1Pos
= positions
[randIndex
];
1085 // The second bishop must be on a square of different color
1086 let randIndex_tmp
= 2 * _
.random(3) + 1;
1087 let bishop2Pos
= positions
[randIndex_tmp
];
1088 // Remove chosen squares
1089 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
1090 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
1092 // Get random squares for knights
1093 randIndex
= _
.random(5);
1094 let knight1Pos
= positions
[randIndex
];
1095 positions
.splice(randIndex
, 1);
1096 randIndex
= _
.random(4);
1097 let knight2Pos
= positions
[randIndex
];
1098 positions
.splice(randIndex
, 1);
1100 // Get random square for queen
1101 randIndex
= _
.random(3);
1102 let queenPos
= positions
[randIndex
];
1103 positions
.splice(randIndex
, 1);
1105 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
1106 let rook1Pos
= positions
[0];
1107 let kingPos
= positions
[1];
1108 let rook2Pos
= positions
[2];
1110 // Finally put the shuffled pieces in the board array
1111 pieces
[c
][rook1Pos
] = 'r';
1112 pieces
[c
][knight1Pos
] = 'n';
1113 pieces
[c
][bishop1Pos
] = 'b';
1114 pieces
[c
][queenPos
] = 'q';
1115 pieces
[c
][kingPos
] = 'k';
1116 pieces
[c
][bishop2Pos
] = 'b';
1117 pieces
[c
][knight2Pos
] = 'n';
1118 pieces
[c
][rook2Pos
] = 'r';
1120 return pieces
["b"].join("") +
1121 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1122 pieces
["w"].join("").toUpperCase() +
1123 " 1111 w"; //add flags + turn
1126 // Return current fen according to pieces+colors state
1129 return this.getBaseFen() + " " + this.getFlagsFen() + " " + this.turn
;
1132 // Position part of the FEN string
1136 for (let i
=0; i
<V
.size
.x
; i
++)
1139 for (let j
=0; j
<V
.size
.y
; j
++)
1141 if (this.board
[i
][j
] == V
.EMPTY
)
1147 // Add empty squares in-between
1151 fen
+= V
.board2fen(this.board
[i
][j
]);
1156 // "Flush remainder"
1159 if (i
< V
.size
.x
- 1)
1160 fen
+= "/"; //separate rows
1165 // Flags part of the FEN string
1169 // Add castling flags
1170 for (let i
of ['w','b'])
1172 for (let j
=0; j
<2; j
++)
1173 fen
+= (this.castleFlags
[i
][j
] ? '1' : '0');
1178 // Context: just before move is played, turn hasn't changed
1181 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1182 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1184 // Translate final square
1185 const finalSquare
= String
.fromCharCode(97 + move.end
.y
) + (V
.size
.x
-move.end
.x
);
1187 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1188 if (piece
== V
.PAWN
)
1192 if (move.vanish
.length
> move.appear
.length
)
1195 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1196 notation
= startColumn
+ "x" + finalSquare
;
1199 notation
= finalSquare
;
1200 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1201 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1208 return piece
.toUpperCase() +
1209 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1213 // Complete the usual notation, may be required for de-ambiguification
1214 getLongNotation(move)
1217 String
.fromCharCode(97 + move.start
.y
) + (V
.size
.x
-move.start
.x
);
1218 const finalSquare
= String
.fromCharCode(97 + move.end
.y
) + (V
.size
.x
-move.end
.x
);
1219 return startSquare
+ finalSquare
; //not encoding move. But short+long is enough
1222 // The score is already computed when calling this function
1223 getPGN(mycolor
, score
, fenStart
, mode
)
1226 pgn
+= '[Site "vchess.club"]<br>';
1227 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1228 pgn
+= '[Variant "' + variant
+ '"]<br>';
1229 pgn
+= '[Date "' + getDate(new Date()) + '"]<br>';
1230 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1231 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1232 pgn
+= '[FenStart "' + fenStart
+ '"]<br>';
1233 pgn
+= '[Fen "' + this.getFen() + '"]<br>';
1234 pgn
+= '[Result "' + score
+ '"]<br><br>';
1237 for (let i
=0; i
<this.moves
.length
; i
++)
1240 pgn
+= ((i
/2)+1) + ".";
1241 pgn
+= this.moves
[i
].notation
[0] + " ";
1245 // "Complete moves" PGN (helping in ambiguous cases)
1246 for (let i
=0; i
<this.moves
.length
; i
++)
1249 pgn
+= ((i
/2)+1) + ".";
1250 pgn
+= this.moves
[i
].notation
[1] + " ";