79b6a7a3ce468e6f23e64dd798317ff29eb2aaad
1 class PiPo
//Piece+Position
3 // o: {piece[p], color[c], posX[x], posY[y]}
15 // o: {appear, vanish, [start,] [end,]}
16 // appear,vanish = arrays of PiPo
17 // start,end = coordinates to apply to trigger move visually (think castle)
20 this.appear
= o
.appear
;
21 this.vanish
= o
.vanish
;
22 this.start
= !!o
.start
? o
.start : {x:o
.vanish
[0].x
, y:o
.vanish
[0].y
};
23 this.end
= !!o
.end
? o
.end : {x:o
.appear
[0].x
, y:o
.appear
[0].y
};
27 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
33 return b
; //usual pieces in pieces/ folder
35 // Turn "wb" into "B" (for FEN)
38 return b
[0]=='w' ? b
[1].toUpperCase() : b
[1];
40 // Turn "p" into "bp" (for board)
43 return f
.charCodeAt()<=90 ? "w"+f
.toLowerCase() : "b"+f
;
49 // fen == "position flags"
50 constructor(fen
, moves
)
53 // Use fen string to initialize variables, flags and board
54 this.board
= VariantRules
.GetBoard(fen
);
56 this.initVariables(fen
);
61 this.INIT_COL_KING
= {'w':-1, 'b':-1};
62 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
63 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //respective squares of white and black king
64 const fenParts
= fen
.split(" ");
65 const position
= fenParts
[0].split("/");
66 for (let i
=0; i
<position
.length
; i
++)
68 let k
= 0; //column index on board
69 for (let j
=0; j
<position
[i
].length
; j
++)
71 switch (position
[i
].charAt(j
))
74 this.kingPos
['b'] = [i
,k
];
75 this.INIT_COL_KING
['b'] = k
;
78 this.kingPos
['w'] = [i
,k
];
79 this.INIT_COL_KING
['w'] = k
;
82 if (this.INIT_COL_ROOK
['b'][0] < 0)
83 this.INIT_COL_ROOK
['b'][0] = k
;
85 this.INIT_COL_ROOK
['b'][1] = k
;
88 if (this.INIT_COL_ROOK
['w'][0] < 0)
89 this.INIT_COL_ROOK
['w'][0] = k
;
91 this.INIT_COL_ROOK
['w'][1] = k
;
94 let num
= parseInt(position
[i
].charAt(j
));
101 const epSq
= this.moves
.length
> 0 ? this.getEpSquare(this.lastMove
) : undefined;
102 this.epSquares
= [ epSq
];
105 // Turn diagram fen into double array ["wb","wp","bk",...]
108 let rows
= fen
.split(" ")[0].split("/");
109 const [sizeX
,sizeY
] = VariantRules
.size
;
110 let board
= doubleArray(sizeX
, sizeY
, "");
111 for (let i
=0; i
<rows
.length
; i
++)
114 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
116 let character
= rows
[i
][indexInRow
];
117 let num
= parseInt(character
);
119 j
+= num
; //just shift j
120 else //something at position i,j
121 board
[i
][j
++] = VariantRules
.fen2board(character
);
127 // Extract (relevant) flags from fen
130 // white a-castle, h-castle, black a-castle, h-castle
131 this.castleFlags
= {'w': new Array(2), 'b': new Array(2)};
132 let flags
= fen
.split(" ")[1]; //flags right after position
133 for (let i
=0; i
<4; i
++)
134 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (flags
.charAt(i
) == '1');
140 static get size() { return [8,8]; }
141 // Two next functions return 'undefined' if called on empty square
142 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
143 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
146 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
149 const L
= this.moves
.length
;
150 return L
>0 ? this.moves
[L
-1] : null;
153 return this.moves
.length
%2==0 ? 'w' : 'b';
157 static get PAWN() { return 'p'; }
158 static get ROOK() { return 'r'; }
159 static get KNIGHT() { return 'n'; }
160 static get BISHOP() { return 'b'; }
161 static get QUEEN() { return 'q'; }
162 static get KING() { return 'k'; }
165 static get EMPTY() { return ''; }
167 // Some pieces movements
170 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
171 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
172 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
176 // Aggregates flags into one object
178 return this.castleFlags
;
184 this.castleFlags
= flags
;
187 // En-passant square, if any
190 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
191 if (this.getPiece(sx
,sy
) == VariantRules
.PAWN
&& Math
.abs(sx
- ex
) == 2)
198 return undefined; //default
201 // Can thing on square1 take thing on square2
202 canTake([x1
,y1
], [x2
,y2
])
204 return this.getColor(x1
,y1
) != this.getColor(x2
,y2
);
210 // All possible moves from selected square (assumption: color is OK)
211 getPotentialMovesFrom([x
,y
])
213 switch (this.getPiece(x
,y
))
215 case VariantRules
.PAWN:
216 return this.getPotentialPawnMoves([x
,y
]);
217 case VariantRules
.ROOK:
218 return this.getPotentialRookMoves([x
,y
]);
219 case VariantRules
.KNIGHT:
220 return this.getPotentialKnightMoves([x
,y
]);
221 case VariantRules
.BISHOP:
222 return this.getPotentialBishopMoves([x
,y
]);
223 case VariantRules
.QUEEN:
224 return this.getPotentialQueenMoves([x
,y
]);
225 case VariantRules
.KING:
226 return this.getPotentialKingMoves([x
,y
]);
230 // Build a regular move from its initial and destination squares; tr: transformation
231 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
238 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
239 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
246 c: this.getColor(sx
,sy
),
247 p: this.getPiece(sx
,sy
)
252 // The opponent piece disappears if we take it
253 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
259 c: this.getColor(ex
,ey
),
260 p: this.getPiece(ex
,ey
)
267 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
268 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
270 const color
= this.getColor(x
,y
);
272 const [sizeX
,sizeY
] = VariantRules
.size
;
274 for (let step
of steps
)
278 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
279 && this.board
[i
][j
] == VariantRules
.EMPTY
)
281 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
282 if (oneStep
!== undefined)
287 if (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
&& this.canTake([x
,y
], [i
,j
]))
288 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
293 // What are the pawn moves from square x,y ?
294 getPotentialPawnMoves([x
,y
])
296 const color
= this.turn
;
298 const V
= VariantRules
;
299 const [sizeX
,sizeY
] = V
.size
;
300 const shift
= (color
== "w" ? -1 : 1);
301 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
302 const startRank
= (color
== "w" ? sizeX
-2 : 1);
303 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
305 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
308 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
310 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
]));
311 // Next condition because variants with pawns on 1st rank allow them to jump
312 if ([startRank
,firstRank
].includes(x
) && this.board
[x
+2*shift
][y
] == V
.EMPTY
)
315 moves
.push(this.getBasicMove([x
,y
], [x
+2*shift
,y
]));
319 if (y
>0 && this.canTake([x
,y
], [x
+shift
,y
-1])
320 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
322 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
324 if (y
<sizeY
-1 && 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]));
331 if (x
+shift
== lastRank
)
334 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
335 promotionPieces
.forEach(p
=> {
337 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
338 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:color
,p:p
}));
340 if (y
>0 && this.canTake([x
,y
], [x
+shift
,y
-1])
341 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
343 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:color
,p:p
}));
345 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1])
346 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
348 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:color
,p:p
}));
354 const Lep
= this.epSquares
.length
;
355 const epSquare
= Lep
>0 ? this.epSquares
[Lep
-1] : undefined;
356 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
358 let epStep
= epSquare
.y
- y
;
359 var enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
360 enpassantMove
.vanish
.push({
364 c: this.getColor(x
,y
+epStep
)
366 moves
.push(enpassantMove
);
372 // What are the rook moves from square x,y ?
373 getPotentialRookMoves(sq
)
375 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.ROOK
]);
378 // What are the knight moves from square x,y ?
379 getPotentialKnightMoves(sq
)
381 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
384 // What are the bishop moves from square x,y ?
385 getPotentialBishopMoves(sq
)
387 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.BISHOP
]);
390 // What are the queen moves from square x,y ?
391 getPotentialQueenMoves(sq
)
393 const V
= VariantRules
;
394 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
397 // What are the king moves from square x,y ?
398 getPotentialKingMoves(sq
)
400 const V
= VariantRules
;
401 // Initialize with normal moves
402 let moves
= this.getSlideNJumpMoves(sq
,
403 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
404 return moves
.concat(this.getCastleMoves(sq
));
407 getCastleMoves([x
,y
])
409 const c
= this.getColor(x
,y
);
410 const [sizeX
,sizeY
] = VariantRules
.size
;
411 if (x
!= (c
=="w" ? sizeX
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
412 return []; //x isn't first rank, or king has moved (shortcut)
414 const V
= VariantRules
;
417 const oppCol
= this.getOppCol(c
);
420 const finalSquares
= [ [2,3], [sizeY
-2,sizeY
-3] ]; //king, then rook
422 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
424 if (!this.castleFlags
[c
][castleSide
])
426 // If this code is reached, rooks and king are on initial position
428 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
429 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
430 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
432 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
433 // NOTE: next check is enough, because of chessboard constraints
434 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
436 continue castlingCheck
;
440 // Nothing on the path to the rook?
441 step
= castleSide
== 0 ? -1 : 1;
442 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
444 if (this.board
[x
][i
] != V
.EMPTY
)
445 continue castlingCheck
;
447 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
449 // Nothing on final squares, except maybe king and castling rook?
452 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
453 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
454 finalSquares
[castleSide
][i
] != rookPos
)
456 continue castlingCheck
;
460 // If this code is reached, castle is valid
461 moves
.push( new Move({
463 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
464 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
466 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
467 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
468 end: Math
.abs(y
- rookPos
) <= 2
470 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
480 canIplay(side
, [x
,y
])
482 return ((side
=='w' && this.moves
.length
%2==0) || (side
=='b' && this.moves
.length
%2==1))
483 && this.getColor(x
,y
) == side
;
486 getPossibleMovesFrom(sq
)
488 // Assuming color is right (already checked)
489 return this.filterValid( this.getPotentialMovesFrom(sq
) );
492 // TODO: once a promotion is filtered, the others results are same: useless computations
495 if (moves
.length
== 0)
497 return moves
.filter(m
=> { return !this.underCheck(m
); });
500 // Search for all valid moves considering current turn (for engine and game end)
503 const color
= this.turn
;
504 const oppCol
= this.getOppCol(color
);
505 let potentialMoves
= [];
506 const [sizeX
,sizeY
] = VariantRules
.size
;
507 for (let i
=0; i
<sizeX
; i
++)
509 for (let j
=0; j
<sizeY
; j
++)
511 // Next condition ... != oppCol is a little HACK to work with checkered variant
512 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
513 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
516 // NOTE: prefer lazy undercheck tests, letting the king being taken?
517 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
518 return this.filterValid(potentialMoves
);
521 // Stop at the first move found
524 const color
= this.turn
;
525 const oppCol
= this.getOppCol(color
);
526 const [sizeX
,sizeY
] = VariantRules
.size
;
527 for (let i
=0; i
<sizeX
; i
++)
529 for (let j
=0; j
<sizeY
; j
++)
531 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
533 const moves
= this.getPotentialMovesFrom([i
,j
]);
534 if (moves
.length
> 0)
536 for (let k
=0; k
<moves
.length
; k
++)
538 if (this.filterValid([moves
[k
]]).length
> 0)
548 // Check if pieces of color in array 'colors' are attacking square x,y
549 isAttacked(sq
, colors
)
551 return (this.isAttackedByPawn(sq
, colors
)
552 || this.isAttackedByRook(sq
, colors
)
553 || this.isAttackedByKnight(sq
, colors
)
554 || this.isAttackedByBishop(sq
, colors
)
555 || this.isAttackedByQueen(sq
, colors
)
556 || this.isAttackedByKing(sq
, colors
));
559 // Is square x,y attacked by 'colors' pawns ?
560 isAttackedByPawn([x
,y
], colors
)
562 const [sizeX
,sizeY
] = VariantRules
.size
;
563 for (let c
of colors
)
565 let pawnShift
= (c
=="w" ? 1 : -1);
566 if (x
+pawnShift
>=0 && x
+pawnShift
<sizeX
)
568 for (let i
of [-1,1])
570 if (y
+i
>=0 && y
+i
<sizeY
&& this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
571 && this.getColor(x
+pawnShift
,y
+i
)==c
)
581 // Is square x,y attacked by 'colors' rooks ?
582 isAttackedByRook(sq
, colors
)
584 return this.isAttackedBySlideNJump(sq
, colors
,
585 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
588 // Is square x,y attacked by 'colors' knights ?
589 isAttackedByKnight(sq
, colors
)
591 return this.isAttackedBySlideNJump(sq
, colors
,
592 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
595 // Is square x,y attacked by 'colors' bishops ?
596 isAttackedByBishop(sq
, colors
)
598 return this.isAttackedBySlideNJump(sq
, colors
,
599 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
602 // Is square x,y attacked by 'colors' queens ?
603 isAttackedByQueen(sq
, colors
)
605 const V
= VariantRules
;
606 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
607 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
610 // Is square x,y attacked by 'colors' king(s) ?
611 isAttackedByKing(sq
, colors
)
613 const V
= VariantRules
;
614 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
615 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
618 // Generic method for non-pawn pieces ("sliding or jumping"):
619 // is x,y attacked by a piece of color in array 'colors' ?
620 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
622 const [sizeX
,sizeY
] = VariantRules
.size
;
623 for (let step
of steps
)
625 let rx
= x
+step
[0], ry
= y
+step
[1];
626 while (rx
>=0 && rx
<sizeX
&& ry
>=0 && ry
<sizeY
627 && this.board
[rx
][ry
] == VariantRules
.EMPTY
&& !oneStep
)
632 if (rx
>=0 && rx
<sizeX
&& ry
>=0 && ry
<sizeY
633 && this.board
[rx
][ry
] != VariantRules
.EMPTY
634 && this.getPiece(rx
,ry
) == piece
&& colors
.includes(this.getColor(rx
,ry
)))
642 // Is current player under check after his move ?
645 const color
= this.turn
;
647 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
652 // On which squares is opponent under check after our move ?
653 getCheckSquares(move)
656 const color
= this.turn
; //opponent
657 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
658 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
664 // Apply a move on board
665 static PlayOnBoard(board
, move)
667 for (let psq
of move.vanish
)
668 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
669 for (let psq
of move.appear
)
670 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
672 // Un-apply the played move
673 static UndoOnBoard(board
, move)
675 for (let psq
of move.appear
)
676 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
677 for (let psq
of move.vanish
)
678 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
681 // Before move is played, update variables + flags
682 updateVariables(move)
684 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
685 const c
= this.getColor(move.start
.x
,move.start
.y
);
686 const [sizeX
,sizeY
] = VariantRules
.size
;
687 const firstRank
= (c
== "w" ? sizeX
-1 : 0);
689 // Update king position + flags
690 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
692 this.kingPos
[c
][0] = move.appear
[0].x
;
693 this.kingPos
[c
][1] = move.appear
[0].y
;
694 this.castleFlags
[c
] = [false,false];
697 const oppCol
= this.getOppCol(c
);
698 const oppFirstRank
= (sizeX
-1) - firstRank
;
699 if (move.start
.x
== firstRank
//our rook moves?
700 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
702 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
703 this.castleFlags
[c
][flagIdx
] = false;
705 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
706 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
708 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
709 this.castleFlags
[oppCol
][flagIdx
] = false;
713 // After move is undo-ed, un-update variables (flags are reset)
714 // TODO: more symmetry, by storing flags increment in move...
715 unupdateVariables(move)
717 // (Potentially) Reset king position
718 const c
= this.getColor(move.start
.x
,move.start
.y
);
719 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
720 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
726 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
728 move.flags
= JSON
.stringify(this.flags
); //save flags (for undo)
729 this.updateVariables(move);
730 this.moves
.push(move);
731 this.epSquares
.push( this.getEpSquare(move) );
732 VariantRules
.PlayOnBoard(this.board
, move);
737 VariantRules
.UndoOnBoard(this.board
, move);
738 this.epSquares
.pop();
740 this.unupdateVariables(move);
741 this.parseFlags(JSON
.parse(move.flags
));
747 // Basic check for 3 repetitions (in the last moves only)
750 if (this.moves
.length
>= 8)
752 const L
= this.moves
.length
;
753 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
754 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
755 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
756 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
764 // Is game over ? And if yes, what is the score ?
767 if (this.checkRepetition())
770 if (this.atLeastOneMove()) // game not over
774 return this.checkGameEnd();
777 // No moves are possible: compute score
780 const color
= this.turn
;
781 // No valid move: stalemate or checkmate?
782 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
785 return color
== "w" ? "0-1" : "1-0";
792 static get VALUES() {
803 static get INFINITY() {
804 return 9999; //"checkmate" (unreachable eval)
807 static get THRESHOLD_MATE() {
808 // At this value or above, the game is over
809 return VariantRules
.INFINITY
;
812 static get SEARCH_DEPTH() {
813 return 3; //2 for high branching factor, 4 for small (Loser chess)
816 // Assumption: at least one legal move
817 // NOTE: works also for extinction chess because depth is 3...
820 this.shouldReturn
= false;
821 const maxeval
= VariantRules
.INFINITY
;
822 const color
= this.turn
;
823 let moves1
= this.getAllValidMoves();
825 // Can I mate in 1 ? (for Magnetic & Extinction)
826 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
828 this.play(moves1
[i
]);
829 const finish
= (Math
.abs(this.evalPosition()) >= VariantRules
.THRESHOLD_MATE
);
830 this.undo(moves1
[i
]);
835 // Rank moves using a min-max at depth 2
836 for (let i
=0; i
<moves1
.length
; i
++)
838 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
; //very low, I'm checkmated
839 let eval2
= (color
=="w" ? 1 : -1) * maxeval
; //initialized with checkmate value
840 this.play(moves1
[i
]);
842 let moves2
= this.getAllValidMoves();
843 // If no possible moves AND underCheck, eval2 is correct.
844 // If !underCheck, eval2 is 0 (stalemate).
845 if (moves2
.length
== 0 && this.checkGameEnd() == "1/2")
847 for (let j
=0; j
<moves2
.length
; j
++)
849 this.play(moves2
[j
]);
850 let evalPos
= this.evalPosition();
851 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
853 this.undo(moves2
[j
]);
855 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
856 moves1
[i
].eval
= eval2
;
857 this.undo(moves1
[i
]);
859 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
861 let candidates
= [0]; //indices of candidates moves
862 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
864 let currentBest
= moves1
[_
.sample(candidates
, 1)];
866 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
867 if (VariantRules
.SEARCH_DEPTH
>= 3
868 && Math
.abs(moves1
[0].eval
) < VariantRules
.THRESHOLD_MATE
)
870 for (let i
=0; i
<moves1
.length
; i
++)
872 if (this.shouldReturn
)
873 return currentBest
; //depth-2, minimum
874 this.play(moves1
[i
]);
875 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
876 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
877 this.alphabeta(VariantRules
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
878 this.undo(moves1
[i
]);
880 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
886 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
888 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
889 return moves1
[_
.sample(candidates
, 1)];
892 // TODO: some optimisations, understand why CH get mated in 2
893 alphabeta(depth
, alpha
, beta
)
895 const maxeval
= VariantRules
.INFINITY
;
896 const color
= this.turn
;
897 if (!this.atLeastOneMove())
899 switch (this.checkGameEnd())
901 case "1/2": return 0;
902 default: return color
=="w" ? -maxeval : maxeval
;
906 return this.evalPosition();
907 const moves
= this.getAllValidMoves();
908 let v
= color
=="w" ? -maxeval : maxeval
;
911 for (let i
=0; i
<moves
.length
; i
++)
914 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
916 alpha
= Math
.max(alpha
, v
);
923 for (let i
=0; i
<moves
.length
; i
++)
926 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
928 beta
= Math
.min(beta
, v
);
930 break; //alpha cutoff
938 const [sizeX
,sizeY
] = VariantRules
.size
;
940 // Just count material for now
941 for (let i
=0; i
<sizeX
; i
++)
943 for (let j
=0; j
<sizeY
; j
++)
945 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
947 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
948 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
958 // Setup the initial random (assymetric) position
959 static GenRandInitFen()
961 let pieces
= [new Array(8), new Array(8)];
962 // Shuffle pieces on first and last rank
963 for (let c
= 0; c
<= 1; c
++)
965 let positions
= _
.range(8);
967 // Get random squares for bishops
968 let randIndex
= 2 * _
.random(3);
969 let bishop1Pos
= positions
[randIndex
];
970 // The second bishop must be on a square of different color
971 let randIndex_tmp
= 2 * _
.random(3) + 1;
972 let bishop2Pos
= positions
[randIndex_tmp
];
973 // Remove chosen squares
974 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
975 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
977 // Get random squares for knights
978 randIndex
= _
.random(5);
979 let knight1Pos
= positions
[randIndex
];
980 positions
.splice(randIndex
, 1);
981 randIndex
= _
.random(4);
982 let knight2Pos
= positions
[randIndex
];
983 positions
.splice(randIndex
, 1);
985 // Get random square for queen
986 randIndex
= _
.random(3);
987 let queenPos
= positions
[randIndex
];
988 positions
.splice(randIndex
, 1);
990 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
991 let rook1Pos
= positions
[0];
992 let kingPos
= positions
[1];
993 let rook2Pos
= positions
[2];
995 // Finally put the shuffled pieces in the board array
996 pieces
[c
][rook1Pos
] = 'r';
997 pieces
[c
][knight1Pos
] = 'n';
998 pieces
[c
][bishop1Pos
] = 'b';
999 pieces
[c
][queenPos
] = 'q';
1000 pieces
[c
][kingPos
] = 'k';
1001 pieces
[c
][bishop2Pos
] = 'b';
1002 pieces
[c
][knight2Pos
] = 'n';
1003 pieces
[c
][rook2Pos
] = 'r';
1005 let fen
= pieces
[0].join("") +
1006 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1007 pieces
[1].join("").toUpperCase() +
1008 " 1111"; //add flags
1012 // Return current fen according to pieces+colors state
1015 return this.getBaseFen() + " " + this.getFlagsFen();
1018 // Position part of the FEN string
1022 let [sizeX
,sizeY
] = VariantRules
.size
;
1023 for (let i
=0; i
<sizeX
; i
++)
1026 for (let j
=0; j
<sizeY
; j
++)
1028 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
1034 // Add empty squares in-between
1038 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
1043 // "Flush remainder"
1047 fen
+= "/"; //separate rows
1052 // Flags part of the FEN string
1056 // Add castling flags
1057 for (let i
of ['w','b'])
1059 for (let j
=0; j
<2; j
++)
1060 fen
+= this.castleFlags
[i
][j
] ? '1' : '0';
1065 // Context: just before move is played, turn hasn't changed
1068 if (move.appear
.length
== 2 && move.appear
[0].p
== VariantRules
.KING
)
1071 if (move.end
.y
< move.start
.y
)
1077 // Translate final square
1079 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1081 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1082 if (piece
== VariantRules
.PAWN
)
1086 if (move.vanish
.length
> move.appear
.length
)
1089 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1090 notation
= startColumn
+ "x" + finalSquare
;
1093 notation
= finalSquare
;
1094 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1095 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1102 return piece
.toUpperCase() +
1103 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1107 // Complete the usual notation, may be required for de-ambiguification
1108 getLongNotation(move)
1111 String
.fromCharCode(97 + move.start
.y
) + (VariantRules
.size
[0]-move.start
.x
);
1113 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1114 return startSquare
+ finalSquare
; //not encoding move. But short+long is enough
1117 // The score is already computed when calling this function
1118 getPGN(mycolor
, score
, fenStart
, mode
)
1121 pgn
+= '[Site "vchess.club"]<br>';
1122 const d
= new Date();
1123 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1124 pgn
+= '[Variant "' + variant
+ '"]<br>';
1125 pgn
+= '[Date "' + d
.getFullYear() + '-' + (d
.getMonth()+1) + '-' + d
.getDate() + '"]<br>';
1126 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1127 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1128 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1129 pgn
+= '[Result "' + score
+ '"]<br><br>';
1132 for (let i
=0; i
<this.moves
.length
; i
++)
1135 pgn
+= ((i
/2)+1) + ".";
1136 pgn
+= this.moves
[i
].notation
[0] + " ";
1138 pgn
+= score
+ "<br><br>";
1140 // "Complete moves" PGN (helping in ambiguous cases)
1141 for (let i
=0; i
<this.moves
.length
; i
++)
1144 pgn
+= ((i
/2)+1) + ".";
1145 pgn
+= this.moves
[i
].notation
[1] + " ";