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,]}
- // Use fen string to initialize variables, flags and board
- this.board = VariantRules.GetBoard(fen);
- this.flags = VariantRules.GetFlags(fen);
+ // Use fen string to initialize variables, flags, turn and board
+ const fenParts = fen.split(" ");
+ this.board = V.GetBoard(fenParts[0]);
+ this.setFlags(fenParts[1]); //NOTE: fenParts[1] might be undefined
+ this.setTurn(fenParts[2]); //Same note
initVariables(fen)
{
this.INIT_COL_KING = {'w':-1, 'b':-1};
this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]};
initVariables(fen)
{
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++)
{
- this.kingPos['b'] = [i,j];
- this.INIT_COL_KING['b'] = j;
+ this.kingPos['b'] = [i,k];
+ this.INIT_COL_KING['b'] = k;
- this.kingPos['w'] = [i,j];
- this.INIT_COL_KING['w'] = j;
+ this.kingPos['w'] = [i,k];
+ this.INIT_COL_KING['w'] = k;
+ k += (num-1);
+ }
+ k++;
+ }
+ }
+ this.epSquares = [ this.getEpSquare(this.lastMove || fenParts[3]) ];
+ }
+
+ // Check if FEN describe a position
+ static IsGoodFen(fen)
+ {
+ const fenParts = fen.split(" ");
+ if (fenParts.length== 0)
+ return false;
+ // 1) Check position
+ const position = fenParts[0];
+ const rows = position.split("/");
+ if (rows.length != V.size.x)
+ return false;
+ for (let row of rows)
+ {
+ let sumElts = 0;
+ for (let i=0; i<row.length; i++)
+ {
+ if (V.PIECES.includes(row[i].toLowerCase()))
+ sumElts++;
+ else
+ {
+ const num = parseInt(row[i]);
+ if (isNaN(num))
+ return false;
+ sumElts += num;
- const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined;
- this.epSquares = [ epSq ];
+ // 3) Check turn (if present)
+ if (fenParts.length >= 3)
+ {
+ if (!["w","b"].includes(fenParts[2]))
+ return false;
+ }
+ return true;
+ }
+
+ // For FEN checking
+ static IsGoodFlags(flags)
+ {
+ return !!flags.match(/^[01]{4,4}$/);
}
// Turn diagram fen into double array ["wb","wp","bk",...]
static GetBoard(fen)
{
}
// Turn diagram fen into double array ["wb","wp","bk",...]
static GetBoard(fen)
{
- let rows = fen.split(" ")[0].split("/");
- const [sizeX,sizeY] = VariantRules.size;
- let board = doubleArray(sizeX, sizeY, "");
+ const rows = fen.split(" ")[0].split("/");
+ let board = doubleArray(V.size.x, V.size.y, "");
for (let i=0; i<rows.length; i++)
{
let j = 0;
for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
{
for (let i=0; i<rows.length; i++)
{
let j = 0;
for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
{
{
// white a-castle, h-castle, black a-castle, h-castle
{
// white a-castle, h-castle, black a-castle, h-castle
- let flags = {'w': new Array(2), 'b': new Array(2)};
- let fenFlags = fen.split(" ")[1]; //flags right after position
+ this.castleFlags = {'w': [true,true], 'b': [true,true]};
+ if (!fenflags)
+ return;
- flags[i < 2 ? 'w' : 'b'][i%2] = (fenFlags.charAt(i) == '1');
- return flags;
+ this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (fenflags.charAt(i) == '1');
+ }
+
+ // Initialize turn (white or black)
+ setTurn(turnflag)
+ {
+ this.turn = turnflag || "w";
// Two next functions return 'undefined' if called on empty square
getColor(i,j) { return this.board[i][j].charAt(0); }
getPiece(i,j) { return this.board[i][j].charAt(1); }
// Color
// Two next functions return 'undefined' if called on empty square
getColor(i,j) { return this.board[i][j].charAt(0); }
getPiece(i,j) { return this.board[i][j].charAt(1); }
// Color
'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] ]
+ if (typeof moveOrSquare === "string")
+ {
+ const square = moveOrSquare;
+ if (square == "-")
+ return undefined;
+ return {
+ x: square[0].charCodeAt()-97,
+ y: V.size.x-parseInt(square[1])
+ };
+ }
+ // Argument is a move:
+ const move = moveOrSquare;
const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x];
const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x];
canTake([x1,y1], [x2,y2])
{
canTake([x1,y1], [x2,y2])
{
// Build a regular move from its initial and destination squares; tr: transformation
getBasicMove([sx,sy], [ex,ey], tr)
{
// Build a regular move from its initial and destination squares; tr: transformation
getBasicMove([sx,sy], [ex,ey], tr)
{
// Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
getSlideNJumpMoves([x,y], steps, oneStep)
{
const color = this.getColor(x,y);
// Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
getSlideNJumpMoves([x,y], steps, oneStep)
{
const color = this.getColor(x,y);
{
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 (V.OnBoard(i,j) && 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 color = this.getColor(x,y);
- var moves = [];
- var V = VariantRules;
- const [sizeX,sizeY] = VariantRules.size;
- let shift = (color == "w" ? -1 : 1);
- let startRank = (color == "w" ? sizeY-2 : 1);
- let lastRank = (color == "w" ? 0 : sizeY-1);
+ const color = this.turn;
+ let moves = [];
+ const [sizeX,sizeY] = [V.size.x,V.size.y];
+ const shift = (color == "w" ? -1 : 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]));
{
// Two squares jump
moves.push(this.getBasicMove([x,y], [x+2*shift,y]));
}
}
// Captures
{
// Two squares jump
moves.push(this.getBasicMove([x,y], [x+2*shift,y]));
}
}
// Captures
- if (y>0 && this.canTake([x,y], [x+shift,y-1]) && this.board[x+shift][y-1] != V.EMPTY)
+ if (y>0 && this.board[x+shift][y-1] != V.EMPTY
+ && this.canTake([x,y], [x+shift,y-1]))
+ {
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.board[x+shift][y+1] != V.EMPTY
+ && this.canTake([x,y], [x+shift,y+1]))
+ {
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.board[x+shift][y-1] != V.EMPTY
+ && this.canTake([x,y], [x+shift,y-1]))
+ {
+ moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:pawnColor,p:p}));
+ }
+ if (y<sizeY-1 && this.board[x+shift][y+1] != V.EMPTY
+ && this.canTake([x,y], [x+shift,y+1]))
+ {
+ moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:pawnColor,p:p}));
+ }
- let epStep = epSquare.y - y;
- var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
+ const epStep = epSquare.y - y;
+ let enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
// What are the rook moves from square x,y ?
getPotentialRookMoves(sq)
{
// What are the rook moves from square x,y ?
getPotentialRookMoves(sq)
{
}
// What are the knight moves from square x,y ?
getPotentialKnightMoves(sq)
{
}
// What are the knight moves from square x,y ?
getPotentialKnightMoves(sq)
{
}
// What are the bishop moves from square x,y ?
getPotentialBishopMoves(sq)
{
}
// What are the bishop moves from square x,y ?
getPotentialBishopMoves(sq)
{
}
// 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)
{
// Initialize with normal moves
}
// What are the king moves from square x,y ?
getPotentialKingMoves(sq)
{
// Initialize with normal moves
- 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], [V.size.y-2,V.size.y-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 = [];
+ for (let i=0; i<V.size.x; i++)
- // Next condition ... != oppCol is a little HACK to work with checkered variant
- if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
+ // Next condition "!= oppCol" = harmless hack to work with checkered variant
+ if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol)
// 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);
}
isAttackedByPawn([x,y], colors)
{
for (let c of colors)
{
let pawnShift = (c=="w" ? 1 : -1);
isAttackedByPawn([x,y], colors)
{
for (let c of colors)
{
let pawnShift = (c=="w" ? 1 : -1);
- return this.isAttackedBySlideNJump(sq, colors,
- VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
+ return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]);
isAttackedByKnight(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
isAttackedByKnight(sq, colors)
{
return this.isAttackedBySlideNJump(sq, colors,
- return this.isAttackedBySlideNJump(sq, colors,
- VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
+ return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]);
- return this.isAttackedBySlideNJump(sq, colors,
- VariantRules.QUEEN, VariantRules.steps[VariantRules.QUEEN]);
+ 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");
+ 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)
{
for (let step of steps)
{
let rx = x+step[0], ry = y+step[1];
isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
{
for (let step of steps)
{
let rx = x+step[0], ry = y+step[1];
- if (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] != VariantRules.EMPTY
- && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry)))
+ if (V.OnBoard(rx,ry) && this.getPiece(rx,ry) === piece
+ && colors.includes(this.getColor(rx,ry)))
static PlayOnBoard(board, move)
{
for (let psq of move.vanish)
static PlayOnBoard(board, move)
{
for (let psq of move.vanish)
static UndoOnBoard(board, move)
{
for (let psq of move.appear)
static UndoOnBoard(board, move)
{
for (let psq of move.appear)
- const flagIdx = move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1;
- this.flags[c][flagIdx] = false;
+ const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1);
+ this.castleFlags[c][flagIdx] = false;
- const flagIdx = move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1;
- this.flags[oppCol][flagIdx] = false;
+ const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1);
+ this.castleFlags[oppCol][flagIdx] = false;
unupdateVariables(move)
{
// (Potentially) Reset king position
const c = this.getColor(move.start.x,move.start.y);
unupdateVariables(move)
{
// (Potentially) Reset king position
const c = this.getColor(move.start.x,move.start.y);
- VariantRules.PlayOnBoard(this.board, move);
+ this.turn = this.getOppCol(this.turn);
+ V.PlayOnBoard(this.board, move);
+
+ if (!!ingame)
+ move.hash = this.getHashState();
- // 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 "1/2 (repetition)";
- }
+ const move = this.moves[i];
+ if (!this.hashStates[move.hash])
+ this.hashStates[move.hash] = 1;
+ else
+ this.hashStates[move.hash]++;
- if (this.atLeastOneMove())
- {
- // game not over
+ // Is game over ? And if yes, what is the score ?
+ checkGameOver()
+ {
+ if (this.checkRepetition())
+ return "1/2";
+
+ if (this.atLeastOneMove()) // game not over
+ static get INFINITY() {
+ return 9999; //"checkmate" (unreachable eval)
+ }
+
+ static get THRESHOLD_MATE() {
+ // At this value or above, the game is over
+ return V.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++)
+ let finish = (Math.abs(this.evalPosition()) >= V.THRESHOLD_MATE);
+ if (!finish && !this.atLeastOneMove())
- // 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 (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.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(V.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)
{
+ // Complete the usual notation, may be required for de-ambiguification
+ getLongNotation(move)
+ {
+ const startSquare =
+ String.fromCharCode(97 + move.start.y) + (V.size.x-move.start.x);
+ const finalSquare = String.fromCharCode(97 + move.end.y) + (V.size.x-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)
{
let pgn = "";
pgn += '[Site "vchess.club"]<br>';
// The score is already computed when calling this function
getPGN(mycolor, score, fenStart, mode)
{
let pgn = "";
pgn += '[Site "vchess.club"]<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>';