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 // Use fen string to initialize variables, flags and board
58 this.board
= V
.GetBoard(fen
);
60 this.initVariables(fen
);
65 this.INIT_COL_KING
= {'w':-1, 'b':-1};
66 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
67 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
68 const fenParts
= fen
.split(" ");
69 const position
= fenParts
[0].split("/");
70 for (let i
=0; i
<position
.length
; i
++)
72 let k
= 0; //column index on board
73 for (let j
=0; j
<position
[i
].length
; j
++)
75 switch (position
[i
].charAt(j
))
78 this.kingPos
['b'] = [i
,k
];
79 this.INIT_COL_KING
['b'] = k
;
82 this.kingPos
['w'] = [i
,k
];
83 this.INIT_COL_KING
['w'] = k
;
86 if (this.INIT_COL_ROOK
['b'][0] < 0)
87 this.INIT_COL_ROOK
['b'][0] = k
;
89 this.INIT_COL_ROOK
['b'][1] = k
;
92 if (this.INIT_COL_ROOK
['w'][0] < 0)
93 this.INIT_COL_ROOK
['w'][0] = k
;
95 this.INIT_COL_ROOK
['w'][1] = k
;
98 let num
= parseInt(position
[i
].charAt(j
));
105 const epSq
= (this.moves
.length
> 0 ? this.getEpSquare(this.lastMove
) : undefined);
106 this.epSquares
= [ epSq
];
109 // Turn diagram fen into double array ["wb","wp","bk",...]
112 let rows
= fen
.split(" ")[0].split("/");
113 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
114 for (let i
=0; i
<rows
.length
; i
++)
117 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
119 let character
= rows
[i
][indexInRow
];
120 let num
= parseInt(character
);
122 j
+= num
; //just shift j
123 else //something at position i,j
124 board
[i
][j
++] = V
.fen2board(character
);
130 // Extract (relevant) flags from fen
133 // white a-castle, h-castle, black a-castle, h-castle
134 this.castleFlags
= {'w': new Array(2), 'b': new Array(2)};
135 let flags
= fen
.split(" ")[1]; //flags right after position
136 for (let i
=0; i
<4; i
++)
137 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (flags
.charAt(i
) == '1');
143 static get size() { return {x:8, y:8}; }
145 // Two next functions return 'undefined' if called on empty square
146 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
147 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
150 getOppCol(color
) { return (color
=="w" ? "b" : "w"); }
153 const L
= this.moves
.length
;
154 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
) == V
.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
))
221 return this.getPotentialPawnMoves([x
,y
]);
223 return this.getPotentialRookMoves([x
,y
]);
225 return this.getPotentialKnightMoves([x
,y
]);
227 return this.getPotentialBishopMoves([x
,y
]);
229 return this.getPotentialQueenMoves([x
,y
]);
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
] != V
.EMPTY
)
264 c: this.getColor(ex
,ey
),
265 p: this.getPiece(ex
,ey
)
272 // Is (x,y) on the chessboard?
275 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
278 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
279 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
281 const color
= this.getColor(x
,y
);
284 for (let step
of steps
)
288 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
290 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
291 if (oneStep
!== undefined)
296 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
297 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
302 // What are the pawn moves from square x,y ?
303 getPotentialPawnMoves([x
,y
])
305 const color
= this.turn
;
307 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
308 const shift
= (color
== "w" ? -1 : 1);
309 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
310 const startRank
= (color
== "w" ? sizeX
-2 : 1);
311 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
313 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
316 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
318 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
]));
319 // Next condition because variants with pawns on 1st rank allow them to jump
320 if ([startRank
,firstRank
].includes(x
) && this.board
[x
+2*shift
][y
] == V
.EMPTY
)
323 moves
.push(this.getBasicMove([x
,y
], [x
+2*shift
,y
]));
327 if (y
>0 && this.board
[x
+shift
][y
-1] != V
.EMPTY
328 && this.canTake([x
,y
], [x
+shift
,y
-1]))
330 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
332 if (y
<sizeY
-1 && this.board
[x
+shift
][y
+1] != V
.EMPTY
333 && this.canTake([x
,y
], [x
+shift
,y
+1]))
335 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1]));
339 if (x
+shift
== lastRank
)
342 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
343 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
344 promotionPieces
.forEach(p
=> {
346 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
347 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:pawnColor
,p:p
}));
349 if (y
>0 && this.board
[x
+shift
][y
-1] != V
.EMPTY
350 && this.canTake([x
,y
], [x
+shift
,y
-1]))
352 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:pawnColor
,p:p
}));
354 if (y
<sizeY
-1 && this.board
[x
+shift
][y
+1] != V
.EMPTY
355 && this.canTake([x
,y
], [x
+shift
,y
+1]))
357 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:pawnColor
,p:p
}));
363 const Lep
= this.epSquares
.length
;
364 const epSquare
= (Lep
>0 ? this.epSquares
[Lep
-1] : undefined);
365 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
367 const epStep
= epSquare
.y
- y
;
368 let enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
369 enpassantMove
.vanish
.push({
373 c: this.getColor(x
,y
+epStep
)
375 moves
.push(enpassantMove
);
381 // What are the rook moves from square x,y ?
382 getPotentialRookMoves(sq
)
384 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
387 // What are the knight moves from square x,y ?
388 getPotentialKnightMoves(sq
)
390 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
393 // What are the bishop moves from square x,y ?
394 getPotentialBishopMoves(sq
)
396 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
399 // What are the queen moves from square x,y ?
400 getPotentialQueenMoves(sq
)
402 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
405 // What are the king moves from square x,y ?
406 getPotentialKingMoves(sq
)
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 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
418 return []; //x isn't first rank, or king has moved (shortcut)
421 const oppCol
= this.getOppCol(c
);
424 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
426 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
428 if (!this.castleFlags
[c
][castleSide
])
430 // If this code is reached, rooks and king are on initial position
432 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
433 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
434 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
436 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
437 // NOTE: next check is enough, because of chessboard constraints
438 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
440 continue castlingCheck
;
444 // Nothing on the path to the rook?
445 step
= castleSide
== 0 ? -1 : 1;
446 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
448 if (this.board
[x
][i
] != V
.EMPTY
)
449 continue castlingCheck
;
451 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
453 // Nothing on final squares, except maybe king and castling rook?
456 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
457 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
458 finalSquares
[castleSide
][i
] != rookPos
)
460 continue castlingCheck
;
464 // If this code is reached, castle is valid
465 moves
.push( new Move({
467 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
468 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
470 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
471 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
472 end: Math
.abs(y
- rookPos
) <= 2
474 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
484 canIplay(side
, [x
,y
])
486 return ((side
=='w' && this.moves
.length
%2==0)
487 || (side
=='b' && this.moves
.length
%2==1))
488 && this.getColor(x
,y
) == side
;
491 getPossibleMovesFrom(sq
)
493 // Assuming color is right (already checked)
494 return this.filterValid( this.getPotentialMovesFrom(sq
) );
497 // TODO: promotions (into R,B,N,Q) should be filtered only once
500 if (moves
.length
== 0)
502 return moves
.filter(m
=> { return !this.underCheck(m
); });
505 // Search for all valid moves considering current turn (for engine and game end)
508 const color
= this.turn
;
509 const oppCol
= this.getOppCol(color
);
510 let potentialMoves
= [];
511 for (let i
=0; i
<V
.size
.x
; i
++)
513 for (let j
=0; j
<V
.size
.y
; j
++)
515 // Next condition "!= oppCol" = harmless hack to work with checkered variant
516 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
517 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
520 // NOTE: prefer lazy undercheck tests, letting the king being taken?
521 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
522 return this.filterValid(potentialMoves
);
525 // Stop at the first move found
528 const color
= this.turn
;
529 const oppCol
= this.getOppCol(color
);
530 for (let i
=0; i
<V
.size
.x
; i
++)
532 for (let j
=0; j
<V
.size
.y
; j
++)
534 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
536 const moves
= this.getPotentialMovesFrom([i
,j
]);
537 if (moves
.length
> 0)
539 for (let k
=0; k
<moves
.length
; k
++)
541 if (this.filterValid([moves
[k
]]).length
> 0)
551 // Check if pieces of color in array 'colors' are attacking square x,y
552 isAttacked(sq
, colors
)
554 return (this.isAttackedByPawn(sq
, colors
)
555 || this.isAttackedByRook(sq
, colors
)
556 || this.isAttackedByKnight(sq
, colors
)
557 || this.isAttackedByBishop(sq
, colors
)
558 || this.isAttackedByQueen(sq
, colors
)
559 || this.isAttackedByKing(sq
, colors
));
562 // Is square x,y attacked by 'colors' pawns ?
563 isAttackedByPawn([x
,y
], colors
)
565 for (let c
of colors
)
567 let pawnShift
= (c
=="w" ? 1 : -1);
568 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
570 for (let i
of [-1,1])
572 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
573 && this.getColor(x
+pawnShift
,y
+i
)==c
)
583 // Is square x,y attacked by 'colors' rooks ?
584 isAttackedByRook(sq
, colors
)
586 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
589 // Is square x,y attacked by 'colors' knights ?
590 isAttackedByKnight(sq
, colors
)
592 return this.isAttackedBySlideNJump(sq
, colors
,
593 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
596 // Is square x,y attacked by 'colors' bishops ?
597 isAttackedByBishop(sq
, colors
)
599 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
602 // Is square x,y attacked by 'colors' queens ?
603 isAttackedByQueen(sq
, colors
)
605 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
606 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
609 // Is square x,y attacked by 'colors' king(s) ?
610 isAttackedByKing(sq
, colors
)
612 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
613 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
616 // Generic method for non-pawn pieces ("sliding or jumping"):
617 // is x,y attacked by a piece of color in array 'colors' ?
618 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
620 for (let step
of steps
)
622 let rx
= x
+step
[0], ry
= y
+step
[1];
623 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
628 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
629 && colors
.includes(this.getColor(rx
,ry
)))
637 // Is current player under check after his move ?
640 const color
= this.turn
;
642 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
647 // On which squares is opponent under check after our move ?
648 getCheckSquares(move)
651 const color
= this.turn
; //opponent
652 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
653 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
659 // Apply a move on board
660 static PlayOnBoard(board
, move)
662 for (let psq
of move.vanish
)
663 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
664 for (let psq
of move.appear
)
665 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
667 // Un-apply the played move
668 static UndoOnBoard(board
, move)
670 for (let psq
of move.appear
)
671 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
672 for (let psq
of move.vanish
)
673 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
676 // Before move is played, update variables + flags
677 updateVariables(move)
679 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
681 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
683 // Update king position + flags
684 if (piece
== V
.KING
&& move.appear
.length
> 0)
686 this.kingPos
[c
][0] = move.appear
[0].x
;
687 this.kingPos
[c
][1] = move.appear
[0].y
;
688 this.castleFlags
[c
] = [false,false];
691 const oppCol
= this.getOppCol(c
);
692 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
693 if (move.start
.x
== firstRank
//our rook moves?
694 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
696 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
697 this.castleFlags
[c
][flagIdx
] = false;
699 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
700 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
702 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
703 this.castleFlags
[oppCol
][flagIdx
] = false;
707 // After move is undo-ed, un-update variables (flags are reset)
708 // TODO: more symmetry, by storing flags increment in move...
709 unupdateVariables(move)
711 // (Potentially) Reset king position
712 const c
= this.getColor(move.start
.x
,move.start
.y
);
713 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
714 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
717 // Hash of position+flags+turn after a move is played (to detect repetitions)
720 return hex_md5(this.getFen() + " " + this.turn
);
726 // if (!this.states) this.states = [];
727 // if (!ingame) this.states.push(JSON.stringify(this.board));
730 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
732 move.flags
= JSON
.stringify(this.flags
); //save flags (for undo)
733 this.updateVariables(move);
734 this.moves
.push(move);
735 this.epSquares
.push( this.getEpSquare(move) );
736 V
.PlayOnBoard(this.board
, move);
739 move.hash
= this.getHashState();
744 V
.UndoOnBoard(this.board
, move);
745 this.epSquares
.pop();
747 this.unupdateVariables(move);
748 this.parseFlags(JSON
.parse(move.flags
));
751 // if (JSON.stringify(this.board) != this.states[this.states.length-1])
753 // this.states.pop();
759 // Check for 3 repetitions (position + flags + turn)
762 if (!this.hashStates
)
763 this.hashStates
= {};
765 Object
.values(this.hashStates
).reduce((a
,b
) => { return a
+b
; }, 0)
766 // Update this.hashStates with last move (or all moves if continuation)
767 // NOTE: redundant storage, but faster and moderate size
768 for (let i
=startIndex
; i
<this.moves
.length
; i
++)
770 const move = this.moves
[i
];
771 if (!this.hashStates
[move.hash
])
772 this.hashStates
[move.hash
] = 1;
774 this.hashStates
[move.hash
]++;
776 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
779 // Is game over ? And if yes, what is the score ?
782 if (this.checkRepetition())
785 if (this.atLeastOneMove()) // game not over
789 return this.checkGameEnd();
792 // No moves are possible: compute score
795 const color
= this.turn
;
796 // No valid move: stalemate or checkmate?
797 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
800 return color
== "w" ? "0-1" : "1-0";
807 static get VALUES() {
818 static get INFINITY() {
819 return 9999; //"checkmate" (unreachable eval)
822 static get THRESHOLD_MATE() {
823 // At this value or above, the game is over
827 static get SEARCH_DEPTH() {
828 return 3; //2 for high branching factor, 4 for small (Loser chess)
831 // Assumption: at least one legal move
832 // NOTE: works also for extinction chess because depth is 3...
835 const maxeval
= V
.INFINITY
;
836 const color
= this.turn
;
837 // Some variants may show a bigger moves list to the human (Switching),
838 // thus the argument "computer" below (which is generally ignored)
839 let moves1
= this.getAllValidMoves("computer");
841 // Can I mate in 1 ? (for Magnetic & Extinction)
842 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
844 this.play(moves1
[i
]);
845 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
846 if (!finish
&& !this.atLeastOneMove())
848 // Try mate (for other variants)
849 const score
= this.checkGameEnd();
853 this.undo(moves1
[i
]);
858 // Rank moves using a min-max at depth 2
859 for (let i
=0; i
<moves1
.length
; i
++)
861 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
; //very low, I'm checkmated
862 this.play(moves1
[i
]);
863 let eval2
= undefined;
864 if (this.atLeastOneMove())
866 eval2
= (color
=="w" ? 1 : -1) * maxeval
; //initialized with checkmate value
868 let moves2
= this.getAllValidMoves("computer");
869 for (let j
=0; j
<moves2
.length
; j
++)
871 this.play(moves2
[j
]);
872 let evalPos
= undefined;
873 if (this.atLeastOneMove())
874 evalPos
= this.evalPosition()
877 // Work with scores for Loser variant
878 const score
= this.checkGameEnd();
879 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
881 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
883 this.undo(moves2
[j
]);
888 const score
= this.checkGameEnd();
889 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
891 if ((color
=="w" && eval2
> moves1
[i
].eval
)
892 || (color
=="b" && eval2
< moves1
[i
].eval
))
894 moves1
[i
].eval
= eval2
;
896 this.undo(moves1
[i
]);
898 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
899 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
901 let candidates
= [0]; //indices of candidates moves
902 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
904 let currentBest
= moves1
[_
.sample(candidates
, 1)];
906 // From here, depth >= 3: may take a while, so we control time
907 const timeStart
= Date
.now();
909 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
910 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.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(V
.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
= V
.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
983 // Just count material for now
984 for (let i
=0; i
<V
.size
.x
; i
++)
986 for (let j
=0; j
<V
.size
.y
; j
++)
988 if (this.board
[i
][j
] != V
.EMPTY
)
990 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
991 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1001 // Setup the initial random (assymetric) position
1002 static GenRandInitFen()
1004 let pieces
= { "w": new Array(8), "b": new Array(8) };
1005 // Shuffle pieces on first and last rank
1006 for (let c
of ["w","b"])
1008 let positions
= _
.range(8);
1010 // Get random squares for bishops
1011 let randIndex
= 2 * _
.random(3);
1012 let bishop1Pos
= positions
[randIndex
];
1013 // The second bishop must be on a square of different color
1014 let randIndex_tmp
= 2 * _
.random(3) + 1;
1015 let bishop2Pos
= positions
[randIndex_tmp
];
1016 // Remove chosen squares
1017 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
1018 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
1020 // Get random squares for knights
1021 randIndex
= _
.random(5);
1022 let knight1Pos
= positions
[randIndex
];
1023 positions
.splice(randIndex
, 1);
1024 randIndex
= _
.random(4);
1025 let knight2Pos
= positions
[randIndex
];
1026 positions
.splice(randIndex
, 1);
1028 // Get random square for queen
1029 randIndex
= _
.random(3);
1030 let queenPos
= positions
[randIndex
];
1031 positions
.splice(randIndex
, 1);
1033 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
1034 let rook1Pos
= positions
[0];
1035 let kingPos
= positions
[1];
1036 let rook2Pos
= positions
[2];
1038 // Finally put the shuffled pieces in the board array
1039 pieces
[c
][rook1Pos
] = 'r';
1040 pieces
[c
][knight1Pos
] = 'n';
1041 pieces
[c
][bishop1Pos
] = 'b';
1042 pieces
[c
][queenPos
] = 'q';
1043 pieces
[c
][kingPos
] = 'k';
1044 pieces
[c
][bishop2Pos
] = 'b';
1045 pieces
[c
][knight2Pos
] = 'n';
1046 pieces
[c
][rook2Pos
] = 'r';
1048 return pieces
["b"].join("") +
1049 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1050 pieces
["w"].join("").toUpperCase() +
1051 " 1111"; //add flags
1054 // Return current fen according to pieces+colors state
1057 return this.getBaseFen() + " " + this.getFlagsFen();
1060 // Position part of the FEN string
1064 for (let i
=0; i
<V
.size
.x
; i
++)
1067 for (let j
=0; j
<V
.size
.y
; j
++)
1069 if (this.board
[i
][j
] == V
.EMPTY
)
1075 // Add empty squares in-between
1079 fen
+= V
.board2fen(this.board
[i
][j
]);
1084 // "Flush remainder"
1087 if (i
< V
.size
.x
- 1)
1088 fen
+= "/"; //separate rows
1093 // Flags part of the FEN string
1097 // Add castling flags
1098 for (let i
of ['w','b'])
1100 for (let j
=0; j
<2; j
++)
1101 fen
+= (this.castleFlags
[i
][j
] ? '1' : '0');
1106 // Context: just before move is played, turn hasn't changed
1109 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1110 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1112 // Translate final square
1113 const finalSquare
= String
.fromCharCode(97 + move.end
.y
) + (V
.size
.x
-move.end
.x
);
1115 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1116 if (piece
== V
.PAWN
)
1120 if (move.vanish
.length
> move.appear
.length
)
1123 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1124 notation
= startColumn
+ "x" + finalSquare
;
1127 notation
= finalSquare
;
1128 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1129 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1136 return piece
.toUpperCase() +
1137 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1141 // Complete the usual notation, may be required for de-ambiguification
1142 getLongNotation(move)
1145 String
.fromCharCode(97 + move.start
.y
) + (V
.size
.x
-move.start
.x
);
1146 const finalSquare
= String
.fromCharCode(97 + move.end
.y
) + (V
.size
.x
-move.end
.x
);
1147 return startSquare
+ finalSquare
; //not encoding move. But short+long is enough
1150 // The score is already computed when calling this function
1151 getPGN(mycolor
, score
, fenStart
, mode
)
1153 const zeroPad
= x
=> { return (x
<10 ? "0" : "") + x
; };
1155 pgn
+= '[Site "vchess.club"]<br>';
1156 const d
= new Date();
1157 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1158 pgn
+= '[Variant "' + variant
+ '"]<br>';
1159 pgn
+= '[Date "' + d
.getFullYear() + '-' + (d
.getMonth()+1) +
1160 '-' + zeroPad(d
.getDate()) + '"]<br>';
1161 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1162 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1163 pgn
+= '[FenStart "' + fenStart
+ '"]<br>';
1164 pgn
+= '[Fen "' + this.getFen() + '"]<br>';
1165 pgn
+= '[Result "' + score
+ '"]<br><br>';
1168 for (let i
=0; i
<this.moves
.length
; i
++)
1171 pgn
+= ((i
/2)+1) + ".";
1172 pgn
+= this.moves
[i
].notation
[0] + " ";
1176 // "Complete moves" PGN (helping in ambiguous cases)
1177 for (let i
=0; i
<this.moves
.length
; i
++)
1180 pgn
+= ((i
/2)+1) + ".";
1181 pgn
+= this.moves
[i
].notation
[1] + " ";