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"
54 constructor(fen
, moves
)
57 this.hashStates
= {}; //for repetitions detection
58 // Use fen string to initialize variables, flags and board
59 this.board
= VariantRules
.GetBoard(fen
);
61 this.initVariables(fen
);
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
++)
73 let k
= 0; //column index on board
74 for (let j
=0; j
<position
[i
].length
; j
++)
76 switch (position
[i
].charAt(j
))
79 this.kingPos
['b'] = [i
,k
];
80 this.INIT_COL_KING
['b'] = k
;
83 this.kingPos
['w'] = [i
,k
];
84 this.INIT_COL_KING
['w'] = k
;
87 if (this.INIT_COL_ROOK
['b'][0] < 0)
88 this.INIT_COL_ROOK
['b'][0] = k
;
90 this.INIT_COL_ROOK
['b'][1] = k
;
93 if (this.INIT_COL_ROOK
['w'][0] < 0)
94 this.INIT_COL_ROOK
['w'][0] = k
;
96 this.INIT_COL_ROOK
['w'][1] = k
;
99 let num
= parseInt(position
[i
].charAt(j
));
106 const epSq
= this.moves
.length
> 0 ? this.getEpSquare(this.lastMove
) : undefined;
107 this.epSquares
= [ epSq
];
110 // Turn diagram fen into double array ["wb","wp","bk",...]
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
++)
119 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
121 let character
= rows
[i
][indexInRow
];
122 let num
= parseInt(character
);
124 j
+= num
; //just shift j
125 else //something at position i,j
126 board
[i
][j
++] = VariantRules
.fen2board(character
);
132 // Extract (relevant) flags from fen
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');
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); }
151 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
154 const L
= this.moves
.length
;
155 return L
>0 ? this.moves
[L
-1] : null;
158 return this.moves
.length
%2==0 ? 'w' : 'b';
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'; }
170 static get EMPTY() { return ''; }
172 // Some pieces movements
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] ],
181 // Aggregates flags into one object
183 return this.castleFlags
;
189 this.castleFlags
= flags
;
192 // En-passant square, if any
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)
203 return undefined; //default
206 // Can thing on square1 take thing on square2
207 canTake([x1
,y1
], [x2
,y2
])
209 return this.getColor(x1
,y1
) != this.getColor(x2
,y2
);
215 // All possible moves from selected square (assumption: color is OK)
216 getPotentialMovesFrom([x
,y
])
218 switch (this.getPiece(x
,y
))
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
]);
235 // Build a regular move from its initial and destination squares; tr: transformation
236 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
243 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
244 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
251 c: this.getColor(sx
,sy
),
252 p: this.getPiece(sx
,sy
)
257 // The opponent piece disappears if we take it
258 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
264 c: this.getColor(ex
,ey
),
265 p: this.getPiece(ex
,ey
)
272 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
273 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
275 const color
= this.getColor(x
,y
);
277 const [sizeX
,sizeY
] = VariantRules
.size
;
279 for (let step
of steps
)
283 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
284 && this.board
[i
][j
] == VariantRules
.EMPTY
)
286 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
287 if (oneStep
!== undefined)
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
]));
298 // What are the pawn moves from square x,y ?
299 getPotentialPawnMoves([x
,y
])
301 const color
= this.turn
;
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);
310 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
313 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
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
)
320 moves
.push(this.getBasicMove([x
,y
], [x
+2*shift
,y
]));
324 if (y
>0 && this.canTake([x
,y
], [x
+shift
,y
-1])
325 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
327 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
329 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1])
330 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
332 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1]));
336 if (x
+shift
== lastRank
)
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
=> {
343 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
344 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:pawnColor
,p:p
}));
346 if (y
>0 && this.canTake([x
,y
], [x
+shift
,y
-1])
347 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
349 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:pawnColor
,p:p
}));
351 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1])
352 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
354 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:pawnColor
,p:p
}));
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)
364 let epStep
= epSquare
.y
- y
;
365 var enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
366 enpassantMove
.vanish
.push({
370 c: this.getColor(x
,y
+epStep
)
372 moves
.push(enpassantMove
);
378 // What are the rook moves from square x,y ?
379 getPotentialRookMoves(sq
)
381 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.ROOK
]);
384 // What are the knight moves from square x,y ?
385 getPotentialKnightMoves(sq
)
387 return this.getSlideNJumpMoves(
388 sq
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
391 // What are the bishop moves from square x,y ?
392 getPotentialBishopMoves(sq
)
394 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.BISHOP
]);
397 // What are the queen moves from square x,y ?
398 getPotentialQueenMoves(sq
)
400 const V
= VariantRules
;
401 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
404 // What are the king moves from square x,y ?
405 getPotentialKingMoves(sq
)
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
));
414 getCastleMoves([x
,y
])
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)
421 const V
= VariantRules
;
424 const oppCol
= this.getOppCol(c
);
427 const finalSquares
= [ [2,3], [sizeY
-2,sizeY
-3] ]; //king, then rook
429 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
431 if (!this.castleFlags
[c
][castleSide
])
433 // If this code is reached, rooks and king are on initial position
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
)
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
)))))
443 continue castlingCheck
;
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
)
451 if (this.board
[x
][i
] != V
.EMPTY
)
452 continue castlingCheck
;
454 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
456 // Nothing on final squares, except maybe king and castling rook?
459 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
460 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
461 finalSquares
[castleSide
][i
] != rookPos
)
463 continue castlingCheck
;
467 // If this code is reached, castle is valid
468 moves
.push( new Move({
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
})],
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
477 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
487 canIplay(side
, [x
,y
])
489 return ((side
=='w' && this.moves
.length
%2==0)
490 || (side
=='b' && this.moves
.length
%2==1))
491 && this.getColor(x
,y
) == side
;
494 getPossibleMovesFrom(sq
)
496 // Assuming color is right (already checked)
497 return this.filterValid( this.getPotentialMovesFrom(sq
) );
500 // TODO: promotions (into R,B,N,Q) should be filtered only once
503 if (moves
.length
== 0)
505 return moves
.filter(m
=> { return !this.underCheck(m
); });
508 // Search for all valid moves considering current turn (for engine and game end)
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
++)
517 for (let j
=0; j
<sizeY
; j
++)
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
]));
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
);
529 // Stop at the first move found
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
++)
537 for (let j
=0; j
<sizeY
; j
++)
539 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
541 const moves
= this.getPotentialMovesFrom([i
,j
]);
542 if (moves
.length
> 0)
544 for (let k
=0; k
<moves
.length
; k
++)
546 if (this.filterValid([moves
[k
]]).length
> 0)
556 // Check if pieces of color in array 'colors' are attacking square x,y
557 isAttacked(sq
, colors
)
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
));
567 // Is square x,y attacked by 'colors' pawns ?
568 isAttackedByPawn([x
,y
], colors
)
570 const [sizeX
,sizeY
] = VariantRules
.size
;
571 for (let c
of colors
)
573 let pawnShift
= (c
=="w" ? 1 : -1);
574 if (x
+pawnShift
>=0 && x
+pawnShift
<sizeX
)
576 for (let i
of [-1,1])
578 if (y
+i
>=0 && y
+i
<sizeY
&& this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
579 && this.getColor(x
+pawnShift
,y
+i
)==c
)
589 // Is square x,y attacked by 'colors' rooks ?
590 isAttackedByRook(sq
, colors
)
592 return this.isAttackedBySlideNJump(sq
, colors
,
593 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
596 // Is square x,y attacked by 'colors' knights ?
597 isAttackedByKnight(sq
, colors
)
599 return this.isAttackedBySlideNJump(sq
, colors
,
600 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
603 // Is square x,y attacked by 'colors' bishops ?
604 isAttackedByBishop(sq
, colors
)
606 return this.isAttackedBySlideNJump(sq
, colors
,
607 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
610 // Is square x,y attacked by 'colors' queens ?
611 isAttackedByQueen(sq
, colors
)
613 const V
= VariantRules
;
614 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
615 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
618 // Is square x,y attacked by 'colors' king(s) ?
619 isAttackedByKing(sq
, colors
)
621 const V
= VariantRules
;
622 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
623 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
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
)
630 const [sizeX
,sizeY
] = VariantRules
.size
;
631 for (let step
of steps
)
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
)
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
)))
650 // Is current player under check after his move ?
653 const color
= this.turn
;
655 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
660 // On which squares is opponent under check after our move ?
661 getCheckSquares(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!
672 // Apply a move on board
673 static PlayOnBoard(board
, move)
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
;
680 // Un-apply the played move
681 static UndoOnBoard(board
, move)
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
;
689 // Before move is played, update variables + flags
690 updateVariables(move)
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);
697 // Update king position + flags
698 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
700 this.kingPos
[c
][0] = move.appear
[0].x
;
701 this.kingPos
[c
][1] = move.appear
[0].y
;
702 this.castleFlags
[c
] = [false,false];
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
))
710 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
711 this.castleFlags
[c
][flagIdx
] = false;
713 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
714 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
716 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
717 this.castleFlags
[oppCol
][flagIdx
] = false;
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)
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
];
731 // Store a hash of the position + flags + turn after a move is played
732 // (for repetitions detection)
735 const strToHash
= this.getFen() + " " + this.turn
;
736 const hash
= hex_md5(strToHash
);
737 if (!this.hashStates
[hash
])
738 this.hashStates
[hash
] = 1;
740 this.hashStates
[hash
]++;
746 // if (!this.states) this.states = [];
747 // if (!ingame) this.states.push(JSON.stringify(this.board));
750 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
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);
764 VariantRules
.UndoOnBoard(this.board
, move);
765 this.epSquares
.pop();
767 this.unupdateVariables(move);
768 this.parseFlags(JSON
.parse(move.flags
));
771 // if (JSON.stringify(this.board) != this.states[this.states.length-1])
773 // this.states.pop();
779 // Check for 3 repetitions (position + flags + turn)
782 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
785 // Is game over ? And if yes, what is the score ?
788 if (this.checkRepetition())
791 if (this.atLeastOneMove()) // game not over
795 return this.checkGameEnd();
798 // No moves are possible: compute score
801 const color
= this.turn
;
802 // No valid move: stalemate or checkmate?
803 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
806 return color
== "w" ? "0-1" : "1-0";
813 static get VALUES() {
824 static get INFINITY() {
825 return 9999; //"checkmate" (unreachable eval)
828 static get THRESHOLD_MATE() {
829 // At this value or above, the game is over
830 return VariantRules
.INFINITY
;
833 static get SEARCH_DEPTH() {
834 return 3; //2 for high branching factor, 4 for small (Loser chess)
837 // Assumption: at least one legal move
838 // NOTE: works also for extinction chess because depth is 3...
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");
847 // Can I mate in 1 ? (for Magnetic & Extinction)
848 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
850 this.play(moves1
[i
]);
851 const finish
= (Math
.abs(this.evalPosition()) >= VariantRules
.THRESHOLD_MATE
);
852 this.undo(moves1
[i
]);
857 // Rank moves using a min-max at depth 2
858 for (let i
=0; i
<moves1
.length
; i
++)
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())
865 eval2
= (color
=="w" ? 1 : -1) * maxeval
; //initialized with checkmate value
867 let moves2
= this.getAllValidMoves("computer");
868 for (let j
=0; j
<moves2
.length
; j
++)
870 this.play(moves2
[j
]);
871 let evalPos
= undefined;
872 if (this.atLeastOneMove())
873 evalPos
= this.evalPosition()
876 // Work with scores for Loser variant
877 const score
= this.checkGameEnd();
878 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
880 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
882 this.undo(moves2
[j
]);
887 const score
= this.checkGameEnd();
888 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
890 if ((color
=="w" && eval2
> moves1
[i
].eval
)
891 || (color
=="b" && eval2
< moves1
[i
].eval
))
893 moves1
[i
].eval
= eval2
;
895 this.undo(moves1
[i
]);
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]; }));
900 let candidates
= [0]; //indices of candidates moves
901 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
903 let currentBest
= moves1
[_
.sample(candidates
, 1)];
905 // From here, depth >= 3: may take a while, so we control time
906 const timeStart
= Date
.now();
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
)
912 for (let i
=0; i
<moves1
.length
; i
++)
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
]);
922 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
926 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
929 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
931 return moves1
[_
.sample(candidates
, 1)];
934 alphabeta(depth
, alpha
, beta
)
936 const maxeval
= VariantRules
.INFINITY
;
937 const color
= this.turn
;
938 if (!this.atLeastOneMove())
940 switch (this.checkGameEnd())
945 const score
= this.checkGameEnd();
946 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
950 return this.evalPosition();
951 const moves
= this.getAllValidMoves("computer");
952 let v
= color
=="w" ? -maxeval : maxeval
;
955 for (let i
=0; i
<moves
.length
; i
++)
958 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
960 alpha
= Math
.max(alpha
, v
);
967 for (let i
=0; i
<moves
.length
; i
++)
970 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
972 beta
= Math
.min(beta
, v
);
974 break; //alpha cutoff
982 const [sizeX
,sizeY
] = VariantRules
.size
;
984 // Just count material for now
985 for (let i
=0; i
<sizeX
; i
++)
987 for (let j
=0; j
<sizeY
; j
++)
989 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
991 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
992 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
1002 // Setup the initial random (assymetric) position
1003 static GenRandInitFen()
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"])
1009 let positions
= _
.range(8);
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);
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);
1029 // Get random square for queen
1030 randIndex
= _
.random(3);
1031 let queenPos
= positions
[randIndex
];
1032 positions
.splice(randIndex
, 1);
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];
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';
1049 return pieces
["b"].join("") +
1050 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1051 pieces
["w"].join("").toUpperCase() +
1052 " 1111"; //add flags
1055 // Return current fen according to pieces+colors state
1058 return this.getBaseFen() + " " + this.getFlagsFen();
1061 // Position part of the FEN string
1065 let [sizeX
,sizeY
] = VariantRules
.size
;
1066 for (let i
=0; i
<sizeX
; i
++)
1069 for (let j
=0; j
<sizeY
; j
++)
1071 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
1077 // Add empty squares in-between
1081 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
1086 // "Flush remainder"
1090 fen
+= "/"; //separate rows
1095 // Flags part of the FEN string
1099 // Add castling flags
1100 for (let i
of ['w','b'])
1102 for (let j
=0; j
<2; j
++)
1103 fen
+= (this.castleFlags
[i
][j
] ? '1' : '0');
1108 // Context: just before move is played, turn hasn't changed
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");
1114 // Translate final square
1116 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1118 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1119 if (piece
== VariantRules
.PAWN
)
1123 if (move.vanish
.length
> move.appear
.length
)
1126 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1127 notation
= startColumn
+ "x" + finalSquare
;
1130 notation
= finalSquare
;
1131 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1132 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1139 return piece
.toUpperCase() +
1140 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1144 // Complete the usual notation, may be required for de-ambiguification
1145 getLongNotation(move)
1148 String
.fromCharCode(97 + move.start
.y
) + (VariantRules
.size
[0]-move.start
.x
);
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
1154 // The score is already computed when calling this function
1155 getPGN(mycolor
, score
, fenStart
, mode
)
1157 const zeroPad
= x
=> { return (x
<10 ? "0" : "") + x
; };
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>';
1172 for (let i
=0; i
<this.moves
.length
; i
++)
1175 pgn
+= ((i
/2)+1) + ".";
1176 pgn
+= this.moves
[i
].notation
[0] + " ";
1180 // "Complete moves" PGN (helping in ambiguous cases)
1181 for (let i
=0; i
<this.moves
.length
; i
++)
1184 pgn
+= ((i
/2)+1) + ".";
1185 pgn
+= this.moves
[i
].notation
[1] + " ";