class PiPo //Piece+Position
{
// o: {piece[p], color[c], posX[x], posY[y]}
class PiPo //Piece+Position
{
// o: {piece[p], color[c], posX[x], posY[y]}
class Move
{
// o: {appear, vanish, [start,] [end,]}
class Move
{
// o: {appear, vanish, [start,] [end,]}
{
this.INIT_COL_KING = {'w':-1, 'b':-1};
this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]};
{
this.INIT_COL_KING = {'w':-1, 'b':-1};
this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]};
- this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //respective squares of white and black king
+ this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
const fenParts = fen.split(" ");
const position = fenParts[0].split("/");
for (let i=0; i<position.length; i++)
const fenParts = fen.split(" ");
const position = fenParts[0].split("/");
for (let i=0; i<position.length; i++)
setFlags(fen)
{
// white a-castle, h-castle, black a-castle, h-castle
setFlags(fen)
{
// white a-castle, h-castle, black a-castle, h-castle
static get size() { return [8,8]; }
// Two next functions return 'undefined' if called on empty square
getColor(i,j) { return this.board[i][j].charAt(0); }
static get size() { return [8,8]; }
// Two next functions return 'undefined' if called on empty square
getColor(i,j) { return this.board[i][j].charAt(0); }
'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
- 'q': [ [-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1] ]
canTake([x1,y1], [x2,y2])
{
return this.getColor(x1,y1) != this.getColor(x2,y2);
canTake([x1,y1], [x2,y2])
{
return this.getColor(x1,y1) != this.getColor(x2,y2);
{
moves.push(this.getBasicMove([x,y], [i,j]));
if (oneStep !== undefined)
{
moves.push(this.getBasicMove([x,y], [i,j]));
if (oneStep !== undefined)
- if (i>=0 && i<8 && j>=0 && j<8 && this.canTake([x,y], [i,j]))
+ if (i>=0 && i<sizeX && j>=0 && j<sizeY && this.canTake([x,y], [i,j]))
moves.push(this.getBasicMove([x,y], [i,j]));
}
return moves;
}
moves.push(this.getBasicMove([x,y], [i,j]));
}
return moves;
}
- const firstRank = (color == 'w' ? sizeY-1 : 0);
- const startRank = (color == "w" ? sizeY-2 : 1);
- const lastRank = (color == "w" ? 0 : sizeY-1);
+ const firstRank = (color == 'w' ? sizeX-1 : 0);
+ const startRank = (color == "w" ? sizeX-2 : 1);
+ const lastRank = (color == "w" ? 0 : sizeX-1);
if (this.board[x+shift][y] == V.EMPTY)
{
moves.push(this.getBasicMove([x,y], [x+shift,y]));
if (this.board[x+shift][y] == V.EMPTY)
{
moves.push(this.getBasicMove([x,y], [x+shift,y]));
- if (y>0 && this.canTake([x,y], [x+shift,y-1]) && this.board[x+shift][y-1] != V.EMPTY)
+ if (y>0 && this.canTake([x,y], [x+shift,y-1])
+ && this.board[x+shift][y-1] != V.EMPTY)
+ {
moves.push(this.getBasicMove([x,y], [x+shift,y-1]));
moves.push(this.getBasicMove([x,y], [x+shift,y-1]));
- if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1]) && this.board[x+shift][y+1] != V.EMPTY)
+ }
+ if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
+ && this.board[x+shift][y+1] != V.EMPTY)
+ {
moves.push(this.getBasicMove([x,y], [x+shift,y+1]));
moves.push(this.getBasicMove([x,y], [x+shift,y+1]));
let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN];
promotionPieces.forEach(p => {
// Normal move
if (this.board[x+shift][y] == V.EMPTY)
let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN];
promotionPieces.forEach(p => {
// Normal move
if (this.board[x+shift][y] == V.EMPTY)
- moves.push(this.getBasicMove([x,y], [x+shift,y], {c:color,p:p}));
+ moves.push(this.getBasicMove([x,y], [x+shift,y], {c:pawnColor,p:p}));
- if (y>0 && this.canTake([x,y], [x+shift,y-1]) && this.board[x+shift][y-1] != V.EMPTY)
- moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:color,p:p}));
- if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1]) && this.board[x+shift][y+1] != V.EMPTY)
- moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:color,p:p}));
+ if (y>0 && this.canTake([x,y], [x+shift,y-1])
+ && this.board[x+shift][y-1] != V.EMPTY)
+ {
+ moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:pawnColor,p:p}));
+ }
+ if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
+ && this.board[x+shift][y+1] != V.EMPTY)
+ {
+ moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:pawnColor,p:p}));
+ }
// What are the knight moves from square x,y ?
getPotentialKnightMoves(sq)
{
// What are the knight moves from square x,y ?
getPotentialKnightMoves(sq)
{
- return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
+ return this.getSlideNJumpMoves(
+ sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
// What are the queen moves from square x,y ?
getPotentialQueenMoves(sq)
{
// What are the queen moves from square x,y ?
getPotentialQueenMoves(sq)
{
}
// What are the king moves from square x,y ?
getPotentialKingMoves(sq)
{
}
// What are the king moves from square x,y ?
getPotentialKingMoves(sq)
{
- let moves = this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.QUEEN], "oneStep");
+ let moves = this.getSlideNJumpMoves(sq,
+ V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
return moves.concat(this.getCastleMoves(sq));
}
getCastleMoves([x,y])
{
const c = this.getColor(x,y);
return moves.concat(this.getCastleMoves(sq));
}
getCastleMoves([x,y])
{
const c = this.getColor(x,y);
- const finalSquares = [ [2,3], [6,5] ]; //king, then rook
+ const finalSquares = [ [2,3], [sizeY-2,sizeY-3] ]; //king, then rook
let step = finalSquares[castleSide][0] < y ? -1 : 1;
for (i=y; i!=finalSquares[castleSide][0]; i+=step)
{
let step = finalSquares[castleSide][0] < y ? -1 : 1;
for (i=y; i!=finalSquares[castleSide][0]; i+=step)
{
// NOTE: next check is enough, because of chessboard constraints
(this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
{
// NOTE: next check is enough, because of chessboard constraints
(this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
{
- var potentialMoves = [];
- let [sizeX,sizeY] = VariantRules.size;
- for (var i=0; i<sizeX; i++)
+ let potentialMoves = [];
+ const [sizeX,sizeY] = VariantRules.size;
+ for (let i=0; i<sizeX; i++)
if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j]));
}
if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j]));
}
// No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
return this.filterValid(potentialMoves);
}
// No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
return this.filterValid(potentialMoves);
}
- let [sizeX,sizeY] = VariantRules.size;
- for (var i=0; i<sizeX; i++)
+ const [sizeX,sizeY] = VariantRules.size;
+ for (let i=0; i<sizeX; i++)
{
if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
{
const moves = this.getPotentialMovesFrom([i,j]);
if (moves.length > 0)
{
{
if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
{
const moves = this.getPotentialMovesFrom([i,j]);
if (moves.length > 0)
{
isAttackedByRook(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
}
isAttackedByRook(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
}
isAttackedByKnight(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
}
isAttackedByKnight(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
}
isAttackedByBishop(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
}
isAttackedByBishop(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
}
- return this.isAttackedBySlideNJump(sq, colors,
- VariantRules.QUEEN, VariantRules.steps[VariantRules.QUEEN]);
+ const V = VariantRules;
+ return this.isAttackedBySlideNJump(sq, colors, V.QUEEN,
+ V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
- return this.isAttackedBySlideNJump(sq, colors,
- VariantRules.KING, VariantRules.steps[VariantRules.QUEEN], "oneStep");
+ const V = VariantRules;
+ return this.isAttackedBySlideNJump(sq, colors, V.KING,
+ V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
- // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
+ // Generic method for non-pawn pieces ("sliding or jumping"):
+ // is x,y attacked by a piece of color in array 'colors' ?
isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
{
isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
{
{
const piece = this.getPiece(move.start.x,move.start.y);
const c = this.getColor(move.start.x,move.start.y);
{
const piece = this.getPiece(move.start.x,move.start.y);
const c = this.getColor(move.start.x,move.start.y);
move.flags = JSON.stringify(this.flags); //save flags (for undo)
this.updateVariables(move);
this.moves.push(move);
this.epSquares.push( this.getEpSquare(move) );
VariantRules.PlayOnBoard(this.board, move);
move.flags = JSON.stringify(this.flags); //save flags (for undo)
this.updateVariables(move);
this.moves.push(move);
this.epSquares.push( this.getEpSquare(move) );
VariantRules.PlayOnBoard(this.board, move);
- // Check for 3 repetitions
- if (this.moves.length >= 8)
+ if (!this.hashStates)
+ this.hashStates = {};
+ const startIndex =
+ Object.values(this.hashStates).reduce((a,b) => { return a+b; }, 0)
+ // Update this.hashStates with last move (or all moves if continuation)
+ // NOTE: redundant storage, but faster and moderate size
+ for (let i=startIndex; i<this.moves.length; i++)
- // NOTE: crude detection, only moves repetition
- const L = this.moves.length;
- if (_.isEqual(this.moves[L-1], this.moves[L-5]) &&
- _.isEqual(this.moves[L-2], this.moves[L-6]) &&
- _.isEqual(this.moves[L-3], this.moves[L-7]) &&
- _.isEqual(this.moves[L-4], this.moves[L-8]))
- {
- return true;
- }
+ const move = this.moves[i];
+ if (!this.hashStates[move.hash])
+ this.hashStates[move.hash] = 1;
+ else
+ this.hashStates[move.hash]++;
+ static get INFINITY() {
+ return 9999; //"checkmate" (unreachable eval)
+ }
+
+ static get THRESHOLD_MATE() {
+ // At this value or above, the game is over
+ return VariantRules.INFINITY;
+ }
+
+ static get SEARCH_DEPTH() {
+ return 3; //2 for high branching factor, 4 for small (Loser chess)
+ }
+
- // Rank moves using a min-max at depth 2
- let moves1 = this.getAllValidMoves();
-
- for (let i=0; i<moves1.length; i++)
+ // Can I mate in 1 ? (for Magnetic & Extinction)
+ for (let i of _.shuffle(_.range(moves1.length)))
- // Second half-move:
- let moves2 = this.getAllValidMoves();
- // If no possible moves AND underCheck, eval2 is correct.
- // If !underCheck, eval2 is 0 (stalemate).
- if (moves2.length == 0 && this.checkGameEnd() == "1/2")
- eval2 = 0;
- for (let j=0; j<moves2.length; j++)
- {
- this.play(moves2[j]);
- let evalPos = this.evalPosition();
- if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
- eval2 = evalPos;
- this.undo(moves2[j]);
- }
- if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval))
- moves1[i].eval = eval2;
+ const finish = (Math.abs(this.evalPosition()) >= VariantRules.THRESHOLD_MATE);
- // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
- moves1[i].eval = 0.1*moves1[i].eval + this.alphabeta(2, -1000, 1000);
+ let eval2 = undefined;
+ if (this.atLeastOneMove())
+ {
+ eval2 = (color=="w" ? 1 : -1) * maxeval; //initialized with checkmate value
+ // Second half-move:
+ let moves2 = this.getAllValidMoves("computer");
+ for (let j=0; j<moves2.length; j++)
+ {
+ this.play(moves2[j]);
+ let evalPos = undefined;
+ if (this.atLeastOneMove())
+ evalPos = this.evalPosition()
+ else
+ {
+ // Work with scores for Loser variant
+ const score = this.checkGameEnd();
+ evalPos = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
+ }
+ if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
+ eval2 = evalPos;
+ this.undo(moves2[j]);
+ }
+ }
+ else
+ {
+ const score = this.checkGameEnd();
+ eval2 = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
+ }
+ if ((color=="w" && eval2 > moves1[i].eval)
+ || (color=="b" && eval2 < moves1[i].eval))
+ {
+ moves1[i].eval = eval2;
+ }
let candidates = [0]; //indices of candidates moves
for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
candidates.push(j);
let candidates = [0]; //indices of candidates moves
for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
candidates.push(j);
+ let currentBest = moves1[_.sample(candidates, 1)];
+
+ // From here, depth >= 3: may take a while, so we control time
+ const timeStart = Date.now();
+ // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
+ if (VariantRules.SEARCH_DEPTH >= 3
+ && Math.abs(moves1[0].eval) < VariantRules.THRESHOLD_MATE)
+ {
+ for (let i=0; i<moves1.length; i++)
+ {
+ if (Date.now()-timeStart >= 5000) //more than 5 seconds
+ return currentBest; //depth 2 at least
+ this.play(moves1[i]);
+ // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
+ moves1[i].eval = 0.1*moves1[i].eval +
+ this.alphabeta(VariantRules.SEARCH_DEPTH-1, -maxeval, maxeval);
+ this.undo(moves1[i]);
+ }
+ moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
+ }
+ else
+ return currentBest;
return moves1[_.sample(candidates, 1)];
}
alphabeta(depth, alpha, beta)
{
return moves1[_.sample(candidates, 1)];
}
alphabeta(depth, alpha, beta)
{
- if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING)
- {
- // Castle
- if (move.end.y < move.start.y)
- return "0-0-0";
- else
- return "0-0";
- }
+ if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING) //castle
+ return (move.end.y < move.start.y ? "0-0-0" : "0-0");
+ // Complete the usual notation, may be required for de-ambiguification
+ getLongNotation(move)
+ {
+ const startSquare =
+ String.fromCharCode(97 + move.start.y) + (VariantRules.size[0]-move.start.x);
+ const finalSquare =
+ String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
+ return startSquare + finalSquare; //not encoding move. But short+long is enough
+ }
+
// The score is already computed when calling this function
getPGN(mycolor, score, fenStart, mode)
{
// The score is already computed when calling this function
getPGN(mycolor, score, fenStart, mode)
{
- pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate() + '"]<br>';
+ pgn += '[Variant "' + variant + '"]<br>';
+ pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) +
+ '-' + zeroPad(d.getDate()) + '"]<br>';
pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';