26c744777c1b4a4b77f311363e372ce2dd63a3bb
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 // Overridable: flags can change a lot
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 // Simple useful getters
141 static get size() { return [8,8]; }
142 // Two next functions return 'undefined' if called on empty square
143 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
144 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
147 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
150 const L
= this.moves
.length
;
151 return L
>0 ? this.moves
[L
-1] : null;
154 return this.moves
.length
%2==0 ? 'w' : 'b';
158 static get PAWN() { return 'p'; }
159 static get ROOK() { return 'r'; }
160 static get KNIGHT() { return 'n'; }
161 static get BISHOP() { return 'b'; }
162 static get QUEEN() { return 'q'; }
163 static get KING() { return 'k'; }
166 static get EMPTY() { return ''; }
168 // Some pieces movements
171 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
172 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
173 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
177 // Aggregates flags into one object
179 return this.castleFlags
;
185 this.castleFlags
= flags
;
188 // En-passant square, if any
191 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
192 if (this.getPiece(sx
,sy
) == VariantRules
.PAWN
&& Math
.abs(sx
- ex
) == 2)
199 return undefined; //default
202 // can thing on square1 take thing on square2
203 canTake([x1
,y1
], [x2
,y2
])
205 return this.getColor(x1
,y1
) != this.getColor(x2
,y2
);
211 // All possible moves from selected square (assumption: color is OK)
212 getPotentialMovesFrom([x
,y
])
214 switch (this.getPiece(x
,y
))
216 case VariantRules
.PAWN:
217 return this.getPotentialPawnMoves([x
,y
]);
218 case VariantRules
.ROOK:
219 return this.getPotentialRookMoves([x
,y
]);
220 case VariantRules
.KNIGHT:
221 return this.getPotentialKnightMoves([x
,y
]);
222 case VariantRules
.BISHOP:
223 return this.getPotentialBishopMoves([x
,y
]);
224 case VariantRules
.QUEEN:
225 return this.getPotentialQueenMoves([x
,y
]);
226 case VariantRules
.KING:
227 return this.getPotentialKingMoves([x
,y
]);
231 // Build a regular move from its initial and destination squares; tr: transformation
232 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
239 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
240 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
247 c: this.getColor(sx
,sy
),
248 p: this.getPiece(sx
,sy
)
253 // The opponent piece disappears if we take it
254 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
260 c: this.getColor(ex
,ey
),
261 p: this.getPiece(ex
,ey
)
268 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
269 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
271 const color
= this.getColor(x
,y
);
273 const [sizeX
,sizeY
] = VariantRules
.size
;
275 for (let step
of steps
)
279 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
&& this.board
[i
][j
] == VariantRules
.EMPTY
)
281 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
282 if (oneStep
!== undefined)
287 if (i
>=0 && i
<8 && j
>=0 && j
<8 && 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 considering color "color" ?
294 getPotentialPawnMoves([x
,y
])
296 const color
= this.turn
;
298 const V
= VariantRules
;
299 const [sizeX
,sizeY
] = VariantRules
.size
;
300 const shift
= (color
== "w" ? -1 : 1);
301 const firstRank
= (color
== 'w' ? sizeY
-1 : 0);
302 const startRank
= (color
== "w" ? sizeY
-2 : 1);
303 const lastRank
= (color
== "w" ? 0 : sizeY
-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 generally 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]) && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
320 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
321 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1]) && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
322 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1]));
325 if (x
+shift
== lastRank
)
328 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
329 promotionPieces
.forEach(p
=> {
331 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
332 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:color
,p:p
}));
334 if (y
>0 && this.canTake([x
,y
], [x
+shift
,y
-1]) && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
335 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:color
,p:p
}));
336 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1]) && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
337 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:color
,p:p
}));
342 const Lep
= this.epSquares
.length
;
343 const epSquare
= Lep
>0 ? this.epSquares
[Lep
-1] : undefined;
344 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
346 let epStep
= epSquare
.y
- y
;
347 var enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
348 enpassantMove
.vanish
.push({
352 c: this.getColor(x
,y
+epStep
)
354 moves
.push(enpassantMove
);
360 // What are the rook moves from square x,y ?
361 getPotentialRookMoves(sq
)
363 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.ROOK
]);
366 // What are the knight moves from square x,y ?
367 getPotentialKnightMoves(sq
)
369 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
372 // What are the bishop moves from square x,y ?
373 getPotentialBishopMoves(sq
)
375 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.BISHOP
]);
378 // What are the queen moves from square x,y ?
379 getPotentialQueenMoves(sq
)
381 const V
= VariantRules
;
382 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
385 // What are the king moves from square x,y ?
386 getPotentialKingMoves(sq
)
388 const V
= VariantRules
;
389 // Initialize with normal moves
390 let moves
= this.getSlideNJumpMoves(sq
,
391 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
392 return moves
.concat(this.getCastleMoves(sq
));
395 getCastleMoves([x
,y
])
397 const c
= this.getColor(x
,y
);
398 const [sizeX
,sizeY
] = VariantRules
.size
;
399 if (x
!= (c
=="w" ? sizeX
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
400 return []; //x isn't first rank, or king has moved (shortcut)
402 const V
= VariantRules
;
405 const oppCol
= this.getOppCol(c
);
408 const finalSquares
= [ [2,3], [sizeY
-2,sizeY
-3] ]; //king, then rook
410 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
412 if (!this.castleFlags
[c
][castleSide
])
414 // If this code is reached, rooks and king are on initial position
416 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
417 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
418 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
420 if (this.isAttacked([x
,i
], oppCol
) || (this.board
[x
][i
] != V
.EMPTY
&&
421 // NOTE: next check is enough, because of chessboard constraints
422 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
424 continue castlingCheck
;
428 // Nothing on the path to the rook?
429 step
= castleSide
== 0 ? -1 : 1;
430 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
432 if (this.board
[x
][i
] != V
.EMPTY
)
433 continue castlingCheck
;
435 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
437 // Nothing on final squares, except maybe king and castling rook?
440 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
441 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
442 finalSquares
[castleSide
][i
] != rookPos
)
444 continue castlingCheck
;
448 // If this code is reached, castle is valid
449 moves
.push( new Move({
451 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
452 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
454 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
455 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
456 end: Math
.abs(y
- rookPos
) <= 2
458 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
468 canIplay(side
, [x
,y
])
470 return ((side
=='w' && this.moves
.length
%2==0) || (side
=='b' && this.moves
.length
%2==1))
471 && this.getColor(x
,y
) == side
;
474 getPossibleMovesFrom(sq
)
476 // Assuming color is right (already checked)
477 return this.filterValid( this.getPotentialMovesFrom(sq
) );
480 // TODO: once a promotion is filtered, the others results are same: useless computations
483 if (moves
.length
== 0)
485 return moves
.filter(m
=> { return !this.underCheck(m
); });
488 // Search for all valid moves considering current turn (for engine and game end)
491 const color
= this.turn
;
492 const oppCol
= this.getOppCol(color
);
493 let potentialMoves
= [];
494 const [sizeX
,sizeY
] = VariantRules
.size
;
495 for (var i
=0; i
<sizeX
; i
++)
497 for (var j
=0; j
<sizeY
; j
++)
499 // Next condition ... != oppCol is a little HACK to work with checkered variant
500 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
501 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
504 // NOTE: prefer lazy undercheck tests, letting the king being taken?
505 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
506 return this.filterValid(potentialMoves
);
509 // Stop at the first move found
512 const color
= this.turn
;
513 const oppCol
= this.getOppCol(color
);
514 const [sizeX
,sizeY
] = VariantRules
.size
;
515 for (let i
=0; i
<sizeX
; i
++)
517 for (let j
=0; j
<sizeY
; j
++)
519 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
521 const moves
= this.getPotentialMovesFrom([i
,j
]);
522 if (moves
.length
> 0)
524 for (let k
=0; k
<moves
.length
; k
++)
526 if (this.filterValid([moves
[k
]]).length
> 0)
536 // Check if pieces of color 'colors' are attacking square x,y
537 isAttacked(sq
, colors
)
539 return (this.isAttackedByPawn(sq
, colors
)
540 || this.isAttackedByRook(sq
, colors
)
541 || this.isAttackedByKnight(sq
, colors
)
542 || this.isAttackedByBishop(sq
, colors
)
543 || this.isAttackedByQueen(sq
, colors
)
544 || this.isAttackedByKing(sq
, colors
));
547 // Is square x,y attacked by pawns of color c ?
548 isAttackedByPawn([x
,y
], colors
)
550 for (let c
of colors
)
552 let pawnShift
= (c
=="w" ? 1 : -1);
553 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
555 for (let i
of [-1,1])
557 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
558 && this.getColor(x
+pawnShift
,y
+i
)==c
)
568 // Is square x,y attacked by rooks of color c ?
569 isAttackedByRook(sq
, colors
)
571 return this.isAttackedBySlideNJump(sq
, colors
,
572 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
575 // Is square x,y attacked by knights of color c ?
576 isAttackedByKnight(sq
, colors
)
578 return this.isAttackedBySlideNJump(sq
, colors
,
579 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
582 // Is square x,y attacked by bishops of color c ?
583 isAttackedByBishop(sq
, colors
)
585 return this.isAttackedBySlideNJump(sq
, colors
,
586 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
589 // Is square x,y attacked by queens of color c ?
590 isAttackedByQueen(sq
, colors
)
592 const V
= VariantRules
;
593 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
594 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
597 // Is square x,y attacked by king of color c ?
598 isAttackedByKing(sq
, colors
)
600 const V
= VariantRules
;
601 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
602 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
605 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
606 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
608 for (let step
of steps
)
610 let rx
= x
+step
[0], ry
= y
+step
[1];
611 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
617 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
618 && this.getPiece(rx
,ry
) == piece
&& colors
.includes(this.getColor(rx
,ry
)))
626 // Is color c under check after move ?
629 const color
= this.turn
;
631 let res
= this.isAttacked(this.kingPos
[color
], this.getOppCol(color
));
636 // On which squares is color c under check (after move) ?
637 getCheckSquares(move)
640 const color
= this.turn
; //opponent
641 let res
= this.isAttacked(this.kingPos
[color
], this.getOppCol(color
))
642 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
648 // Apply a move on board
649 static PlayOnBoard(board
, move)
651 for (let psq
of move.vanish
)
652 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
653 for (let psq
of move.appear
)
654 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
656 // Un-apply the played move
657 static UndoOnBoard(board
, move)
659 for (let psq
of move.appear
)
660 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
661 for (let psq
of move.vanish
)
662 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
665 // Before move is played, update variables + flags
666 updateVariables(move)
668 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
669 const c
= this.getColor(move.start
.x
,move.start
.y
);
670 const [sizeX
,sizeY
] = VariantRules
.size
;
671 const firstRank
= (c
== "w" ? sizeX
-1 : 0);
673 // Update king position + flags
674 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
676 this.kingPos
[c
][0] = move.appear
[0].x
;
677 this.kingPos
[c
][1] = move.appear
[0].y
;
678 this.castleFlags
[c
] = [false,false];
681 const oppCol
= this.getOppCol(c
);
682 const oppFirstRank
= (sizeX
-1) - firstRank
;
683 if (move.start
.x
== firstRank
//our rook moves?
684 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
686 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
687 this.castleFlags
[c
][flagIdx
] = false;
689 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
690 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
692 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
693 this.castleFlags
[oppCol
][flagIdx
] = false;
697 unupdateVariables(move)
699 // (Potentially) Reset king position
700 const c
= this.getColor(move.start
.x
,move.start
.y
);
701 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
702 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
708 // if (!this.states) this.states = [];
709 // if (!ingame) this.states.push(JSON.stringify(this.board));
712 move.notation
= this.getNotation(move);
714 move.flags
= JSON
.stringify(this.flags
); //save flags (for undo)
715 this.updateVariables(move);
716 this.moves
.push(move);
717 this.epSquares
.push( this.getEpSquare(move) );
718 VariantRules
.PlayOnBoard(this.board
, move);
723 VariantRules
.UndoOnBoard(this.board
, move);
724 this.epSquares
.pop();
726 this.unupdateVariables(move);
727 this.parseFlags(JSON
.parse(move.flags
));
730 // let state = this.states.pop();
731 // if (JSON.stringify(this.board) != state)
740 // Check for 3 repetitions
741 if (this.moves
.length
>= 8)
743 // NOTE: crude detection, only moves repetition
744 const L
= this.moves
.length
;
745 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
746 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
747 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
748 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
758 if (this.checkRepetition())
761 if (this.atLeastOneMove()) // game not over
765 return this.checkGameEnd();
768 // No moves are possible: compute score
771 const color
= this.turn
;
772 // No valid move: stalemate or checkmate?
773 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
776 return color
== "w" ? "0-1" : "1-0";
783 static get VALUES() {
794 static get INFINITY() {
795 return 9999; //"checkmate" (unreachable eval)
798 static get THRESHOLD_MATE() {
799 // At this value or above, the game is over
800 return VariantRules
.INFINITY
;
803 static get SEARCH_DEPTH() {
804 return 3; //2 for high branching factor, 4 for small (Loser chess)
807 // Assumption: at least one legal move
808 getComputerMove(moves1
) //moves1 might be precomputed (Magnetic chess)
810 this.shouldReturn
= false;
811 const maxeval
= VariantRules
.INFINITY
;
812 const color
= this.turn
;
814 moves1
= this.getAllValidMoves();
816 // Rank moves using a min-max at depth 2
817 for (let i
=0; i
<moves1
.length
; i
++)
819 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
; //very low, I'm checkmated
820 let eval2
= (color
=="w" ? 1 : -1) * maxeval
; //initialized with checkmate value
821 this.play(moves1
[i
]);
823 let moves2
= this.getAllValidMoves();
824 // If no possible moves AND underCheck, eval2 is correct.
825 // If !underCheck, eval2 is 0 (stalemate).
826 if (moves2
.length
== 0 && this.checkGameEnd() == "1/2")
828 for (let j
=0; j
<moves2
.length
; j
++)
830 this.play(moves2
[j
]);
831 let evalPos
= this.evalPosition();
832 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
834 this.undo(moves2
[j
]);
836 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
837 moves1
[i
].eval
= eval2
;
838 this.undo(moves1
[i
]);
840 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
842 let candidates
= [0]; //indices of candidates moves
843 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
845 let currentBest
= moves1
[_
.sample(candidates
, 1)];
847 // Skip depth 3 if we found a checkmate (or if we are checkmated in 1...)
848 if (VariantRules
.SEARCH_DEPTH
>= 3
849 && Math
.abs(moves1
[0].eval
) < VariantRules
.THRESHOLD_MATE
)
851 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
852 for (let i
=0; i
<moves1
.length
; i
++)
854 if (this.shouldReturn
)
855 return currentBest
; //depth-2, minimum
856 this.play(moves1
[i
]);
857 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
858 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
859 this.alphabeta(VariantRules
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
860 this.undo(moves1
[i
]);
862 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
868 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
870 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
871 return moves1
[_
.sample(candidates
, 1)];
874 alphabeta(depth
, alpha
, beta
)
876 const maxeval
= VariantRules
.INFINITY
;
877 const color
= this.turn
;
878 if (!this.atLeastOneMove())
880 switch (this.checkGameEnd())
882 case "1/2": return 0;
883 default: return color
=="w" ? -maxeval : maxeval
;
887 return this.evalPosition();
888 const moves
= this.getAllValidMoves();
889 let v
= color
=="w" ? -maxeval : maxeval
;
892 for (let i
=0; i
<moves
.length
; i
++)
895 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
897 alpha
= Math
.max(alpha
, v
);
904 for (let i
=0; i
<moves
.length
; i
++)
907 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
909 beta
= Math
.min(beta
, v
);
911 break; //alpha cutoff
919 const [sizeX
,sizeY
] = VariantRules
.size
;
921 //Just count material for now
922 for (let i
=0; i
<sizeX
; i
++)
924 for (let j
=0; j
<sizeY
; j
++)
926 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
928 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
929 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
940 static GenRandInitFen()
942 let pieces
= [new Array(8), new Array(8)];
943 // Shuffle pieces on first and last rank
944 for (let c
= 0; c
<= 1; c
++)
946 let positions
= _
.range(8);
948 // Get random squares for bishops
949 let randIndex
= 2 * _
.random(3);
950 let bishop1Pos
= positions
[randIndex
];
951 // The second bishop must be on a square of different color
952 let randIndex_tmp
= 2 * _
.random(3) + 1;
953 let bishop2Pos
= positions
[randIndex_tmp
];
954 // Remove chosen squares
955 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
956 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
958 // Get random squares for knights
959 randIndex
= _
.random(5);
960 let knight1Pos
= positions
[randIndex
];
961 positions
.splice(randIndex
, 1);
962 randIndex
= _
.random(4);
963 let knight2Pos
= positions
[randIndex
];
964 positions
.splice(randIndex
, 1);
966 // Get random square for queen
967 randIndex
= _
.random(3);
968 let queenPos
= positions
[randIndex
];
969 positions
.splice(randIndex
, 1);
971 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
972 let rook1Pos
= positions
[0];
973 let kingPos
= positions
[1];
974 let rook2Pos
= positions
[2];
976 // Finally put the shuffled pieces in the board array
977 pieces
[c
][rook1Pos
] = 'r';
978 pieces
[c
][knight1Pos
] = 'n';
979 pieces
[c
][bishop1Pos
] = 'b';
980 pieces
[c
][queenPos
] = 'q';
981 pieces
[c
][kingPos
] = 'k';
982 pieces
[c
][bishop2Pos
] = 'b';
983 pieces
[c
][knight2Pos
] = 'n';
984 pieces
[c
][rook2Pos
] = 'r';
986 let fen
= pieces
[0].join("") +
987 "/pppppppp/8/8/8/8/PPPPPPPP/" +
988 pieces
[1].join("").toUpperCase() +
993 // Return current fen according to pieces+colors state
996 return this.getBaseFen() + " " + this.getFlagsFen();
1002 let [sizeX
,sizeY
] = VariantRules
.size
;
1003 for (let i
=0; i
<sizeX
; i
++)
1006 for (let j
=0; j
<sizeY
; j
++)
1008 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
1014 // Add empty squares in-between
1018 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
1023 // "Flush remainder"
1027 fen
+= "/"; //separate rows
1036 // Add castling flags
1037 for (let i
of ['w','b'])
1039 for (let j
=0; j
<2; j
++)
1040 fen
+= this.castleFlags
[i
][j
] ? '1' : '0';
1045 // Context: just before move is played, turn hasn't changed
1048 if (move.appear
.length
== 2 && move.appear
[0].p
== VariantRules
.KING
)
1051 if (move.end
.y
< move.start
.y
)
1057 // Translate final square
1059 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1061 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1062 if (piece
== VariantRules
.PAWN
)
1066 if (move.vanish
.length
> move.appear
.length
)
1069 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1070 notation
= startColumn
+ "x" + finalSquare
;
1073 notation
= finalSquare
;
1074 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1075 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1082 return piece
.toUpperCase() +
1083 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1087 // The score is already computed when calling this function
1088 getPGN(mycolor
, score
, fenStart
, mode
)
1091 pgn
+= '[Site "vchess.club"]<br>';
1092 const d
= new Date();
1093 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1094 pgn
+= '[Variant "' + variant
+ '"]<br>';
1095 pgn
+= '[Date "' + d
.getFullYear() + '-' + (d
.getMonth()+1) + '-' + d
.getDate() + '"]<br>';
1096 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1097 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1098 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1099 pgn
+= '[Result "' + score
+ '"]<br><br>';
1101 for (let i
=0; i
<this.moves
.length
; i
++)
1104 pgn
+= ((i
/2)+1) + ".";
1105 pgn
+= this.moves
[i
].notation
+ " ";