Attempt to not throw exception on server socket error
[vchess.git] / public / javascripts / base_rules.js
index b604e79..860495a 100644 (file)
@@ -10,6 +10,7 @@ class PiPo //Piece+Position
        }
 }
 
+// TODO: for animation, moves should contains "moving" and "fading" maybe...
 class Move
 {
        // o: {appear, vanish, [start,] [end,]}
@@ -46,14 +47,14 @@ class ChessRules
        /////////////////
        // INITIALIZATION
 
-       // fen = "position flags epSquare movesCount"
+       // fen == "position flags"
        constructor(fen, moves)
        {
                this.moves = moves;
                // Use fen string to initialize variables, flags and board
-               this.initVariables(fen);
-               this.flags = VariantRules.GetFlags(fen);
                this.board = VariantRules.GetBoard(fen);
+               this.setFlags(fen);
+               this.initVariables(fen);
        }
 
        initVariables(fen)
@@ -65,54 +66,48 @@ class ChessRules
                const position = fenParts[0].split("/");
                for (let i=0; i<position.length; i++)
                {
-                       let j = 0;
-                       while (j < position[i].length)
+                       let k = 0; //column index on board
+                       for (let j=0; j<position[i].length; j++)
                        {
                                switch (position[i].charAt(j))
                                {
                                        case 'k':
-                                               this.kingPos['b'] = [i,j];
-                                               this.INIT_COL_KING['b'] = j;
+                                               this.kingPos['b'] = [i,k];
+                                               this.INIT_COL_KING['b'] = k;
                                                break;
                                        case 'K':
-                                               this.kingPos['w'] = [i,j];
-                                               this.INIT_COL_KING['w'] = j;
+                                               this.kingPos['w'] = [i,k];
+                                               this.INIT_COL_KING['w'] = k;
                                                break;
                                        case 'r':
                                                if (this.INIT_COL_ROOK['b'][0] < 0)
-                                                       this.INIT_COL_ROOK['b'][0] = j;
+                                                       this.INIT_COL_ROOK['b'][0] = k;
                                                else
-                                                       this.INIT_COL_ROOK['b'][1] = j;
+                                                       this.INIT_COL_ROOK['b'][1] = k;
                                                break;
                                        case 'R':
                                                if (this.INIT_COL_ROOK['w'][0] < 0)
-                                                       this.INIT_COL_ROOK['w'][0] = j;
+                                                       this.INIT_COL_ROOK['w'][0] = k;
                                                else
-                                                       this.INIT_COL_ROOK['w'][1] = j;
+                                                       this.INIT_COL_ROOK['w'][1] = k;
                                                break;
                                        default:
                                                let num = parseInt(position[i].charAt(j));
                                                if (!isNaN(num))
-                                                       j += (num-1);
+                                                       k += (num-1);
                                }
-                               j++;
+                               k++;
                        }
                }
-               let epSq = undefined;
-               if (fenParts[2] != "-")
-               {
-                       const digits = fenParts[2].split(","); //3,2 ...
-                       epSq = { x:Number.parseInt(digits[0]), y:Number.parseInt(digits[1]) };
-               }
+               const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined;
                this.epSquares = [ epSq ];
-               this.movesCount = Number.parseInt(fenParts[3]);
        }
 
        // Turn diagram fen into double array ["wb","wp","bk",...]
        static GetBoard(fen)
        {
                let rows = fen.split(" ")[0].split("/");
-               let [sizeX,sizeY] = VariantRules.size;
+               const [sizeX,sizeY] = VariantRules.size;
                let board = doubleArray(sizeX, sizeY, "");
                for (let i=0; i<rows.length; i++)
                {
@@ -130,21 +125,19 @@ class ChessRules
                return board;
        }
 
-       // Overridable: flags can change a lot
-       static GetFlags(fen)
+       // Extract (relevant) flags from fen
+       setFlags(fen)
        {
                // 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': new Array(2), 'b': new Array(2)};
+               let flags = fen.split(" ")[1]; //flags right after position
                for (let i=0; i<4; i++)
-                       flags[i < 2 ? 'w' : 'b'][i%2] = (fenFlags.charAt(i) == '1');
-               return flags;
+                       this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (flags.charAt(i) == '1');
        }
 
        ///////////////////
        // GETTERS, SETTERS
 
-       // Simple useful getters
        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); }
@@ -158,7 +151,7 @@ class ChessRules
                return L>0 ? this.moves[L-1] : null;
        }
        get turn() {
-               return this.movesCount%2==0 ? 'w' : 'b';
+               return this.moves.length%2==0 ? 'w' : 'b';
        }
 
        // Pieces codes
@@ -178,10 +171,20 @@ class ChessRules
                        '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] ]
                };
        }
 
+       // Aggregates flags into one object
+       get flags() {
+               return this.castleFlags;
+       }
+
+       // Reverse operation
+       parseFlags(flags)
+       {
+               this.castleFlags = flags;
+       }
+
        // En-passant square, if any
        getEpSquare(move)
        {
@@ -196,10 +199,10 @@ class ChessRules
                return undefined; //default
        }
 
-       // can color1 take color2?
-       canTake(color1, color2)
+       // Can thing on square1 take thing on square2
+       canTake([x1,y1], [x2,y2])
        {
-               return color1 != color2;
+               return this.getColor(x1,y1) != this.getColor(x2,y2);
        }
 
        ///////////////////
@@ -208,35 +211,33 @@ class ChessRules
        // All possible moves from selected square (assumption: color is OK)
        getPotentialMovesFrom([x,y])
        {
-               let c = this.getColor(x,y);
-               // Fill possible moves according to piece type
                switch (this.getPiece(x,y))
                {
                        case VariantRules.PAWN:
-                               return this.getPotentialPawnMoves(x,y,c);
+                               return this.getPotentialPawnMoves([x,y]);
                        case VariantRules.ROOK:
-                               return this.getPotentialRookMoves(x,y,c);
+                               return this.getPotentialRookMoves([x,y]);
                        case VariantRules.KNIGHT:
-                               return this.getPotentialKnightMoves(x,y,c);
+                               return this.getPotentialKnightMoves([x,y]);
                        case VariantRules.BISHOP:
-                               return this.getPotentialBishopMoves(x,y,c);
+                               return this.getPotentialBishopMoves([x,y]);
                        case VariantRules.QUEEN:
-                               return this.getPotentialQueenMoves(x,y,c);
+                               return this.getPotentialQueenMoves([x,y]);
                        case VariantRules.KING:
-                               return this.getPotentialKingMoves(x,y,c);
+                               return this.getPotentialKingMoves([x,y]);
                }
        }
 
        // Build a regular move from its initial and destination squares; tr: transformation
-       getBasicMove(sx, sy, ex, ey, tr)
+       getBasicMove([sx,sy], [ex,ey], tr)
        {
-               var mv = new Move({
+               let mv = new Move({
                        appear: [
                                new PiPo({
                                        x: ex,
                                        y: ey,
-                                       c: this.getColor(sx,sy),
-                                       p: !!tr ? tr : this.getPiece(sx,sy)
+                                       c: !!tr ? tr.c : this.getColor(sx,sy),
+                                       p: !!tr ? tr.p : this.getPiece(sx,sy)
                                })
                        ],
                        vanish: [
@@ -265,83 +266,88 @@ class ChessRules
        }
 
        // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
-       getSlideNJumpMoves(x, y, color, steps, oneStep)
+       getSlideNJumpMoves([x,y], steps, oneStep)
        {
-               var moves = [];
-               let [sizeX,sizeY] = VariantRules.size;
+               const color = this.getColor(x,y);
+               let moves = [];
+               const [sizeX,sizeY] = VariantRules.size;
                outerLoop:
                for (let step of steps)
                {
-                       var i = x + step[0];
-                       var j = y + step[1];
+                       let i = x + step[0];
+                       let j = y + step[1];
                        while (i>=0 && i<sizeX && j>=0 && j<sizeY
                                && this.board[i][j] == VariantRules.EMPTY)
                        {
-                               moves.push(this.getBasicMove(x, y, i, j));
+                               moves.push(this.getBasicMove([x,y], [i,j]));
                                if (oneStep !== undefined)
                                        continue outerLoop;
                                i += step[0];
                                j += step[1];
                        }
-                       if (i>=0 && i<8 && j>=0 && j<8 && this.canTake(color, this.getColor(i,j)))
-                               moves.push(this.getBasicMove(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;
        }
 
-       // What are the pawn moves from square x,y considering color "color" ?
-       getPotentialPawnMoves(x, y, color)
+       // What are the pawn moves from square x,y ?
+       getPotentialPawnMoves([x,y])
        {
-               var moves = [];
-               var V = VariantRules;
-               let [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 V = VariantRules;
+               const [sizeX,sizeY] = V.size;
+               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 (x+shift >= 0 && x+shift < sizeX && x+shift != lastRank)
                {
                        // Normal moves
                        if (this.board[x+shift][y] == V.EMPTY)
                        {
-                               moves.push(this.getBasicMove(x, y, x+shift, y));
-                               if (x==startRank && this.board[x+2*shift][y] == V.EMPTY)
+                               moves.push(this.getBasicMove([x,y], [x+shift,y]));
+                               // Next condition because variants with pawns on 1st rank allow them to jump
+                               if ([startRank,firstRank].includes(x) && this.board[x+2*shift][y] == V.EMPTY)
                                {
                                        // Two squares jump
-                                       moves.push(this.getBasicMove(x, y, x+2*shift, y));
+                                       moves.push(this.getBasicMove([x,y], [x+2*shift,y]));
                                }
                        }
                        // Captures
-                       if (y>0 && this.canTake(this.getColor(x,y), this.getColor(x+shift,y-1))
+                       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(this.getColor(x,y), this.getColor(x+shift,y+1))
+                       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]));
                        }
                }
 
                if (x+shift == lastRank)
                {
                        // Promotion
+                       const pawnColor = this.getColor(x,y); //can be different for checkered
                        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, p));
+                                       moves.push(this.getBasicMove([x,y], [x+shift,y], {c:pawnColor,p:p}));
                                // Captures
-                               if (y>0 && this.canTake(this.getColor(x,y), this.getColor(x+shift,y-1))
+                               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, p));
+                                       moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:pawnColor,p:p}));
                                }
-                               if (y<sizeY-1 && this.canTake(this.getColor(x,y), this.getColor(x+shift,y+1))
+                               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, p));
+                                       moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:pawnColor,p:p}));
                                }
                        });
                }
@@ -352,7 +358,7 @@ class ChessRules
                if (!!epSquare && epSquare.x == x+shift && Math.abs(epSquare.y - y) == 1)
                {
                        let epStep = epSquare.y - y;
-                       var enpassantMove = this.getBasicMove(x, y, x+shift, y+epStep);
+                       var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
                        enpassantMove.vanish.push({
                                x: x,
                                y: y+epStep,
@@ -366,46 +372,45 @@ class ChessRules
        }
 
        // What are the rook moves from square x,y ?
-       getPotentialRookMoves(x, y, color)
+       getPotentialRookMoves(sq)
        {
-               return this.getSlideNJumpMoves(
-                       x, y, color, VariantRules.steps[VariantRules.ROOK]);
+               return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.ROOK]);
        }
 
        // What are the knight moves from square x,y ?
-       getPotentialKnightMoves(x, y, color)
+       getPotentialKnightMoves(sq)
        {
-               return this.getSlideNJumpMoves(
-                       x, y, color, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
+               return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
        }
 
        // What are the bishop moves from square x,y ?
-       getPotentialBishopMoves(x, y, color)
+       getPotentialBishopMoves(sq)
        {
-               return this.getSlideNJumpMoves(
-                       x, y, color, VariantRules.steps[VariantRules.BISHOP]);
+               return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.BISHOP]);
        }
 
        // What are the queen moves from square x,y ?
-       getPotentialQueenMoves(x, y, color)
+       getPotentialQueenMoves(sq)
        {
-               return this.getSlideNJumpMoves(
-                       x, y, color, VariantRules.steps[VariantRules.QUEEN]);
+               const V = VariantRules;
+               return this.getSlideNJumpMoves(sq, V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
        }
 
        // What are the king moves from square x,y ?
-       getPotentialKingMoves(x, y, c)
+       getPotentialKingMoves(sq)
        {
+               const V = VariantRules;
                // Initialize with normal moves
-               var moves = this.getSlideNJumpMoves(x, y, c,
-                       VariantRules.steps[VariantRules.QUEEN], "oneStep");
-
-               return moves.concat(this.getCastleMoves(x,y,c));
+               let moves = this.getSlideNJumpMoves(sq,
+                       V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
+               return moves.concat(this.getCastleMoves(sq));
        }
 
-       getCastleMoves(x,y,c)
+       getCastleMoves([x,y])
        {
-               if (x != (c=="w" ? 7 : 0) || y != this.INIT_COL_KING[c])
+               const c = this.getColor(x,y);
+               const [sizeX,sizeY] = VariantRules.size;
+               if (x != (c=="w" ? sizeX-1 : 0) || y != this.INIT_COL_KING[c])
                        return []; //x isn't first rank, or king has moved (shortcut)
 
                const V = VariantRules;
@@ -414,11 +419,11 @@ class ChessRules
                const oppCol = this.getOppCol(c);
                let moves = [];
                let i = 0;
-               const finalSquares = [ [2,3], [6,5] ]; //king, then rook
+               const finalSquares = [ [2,3], [sizeY-2,sizeY-3] ]; //king, then rook
                castlingCheck:
                for (let castleSide=0; castleSide < 2; castleSide++) //large, then small
                {
-                       if (!this.flags[c][castleSide])
+                       if (!this.castleFlags[c][castleSide])
                                continue;
                        // If this code is reached, rooks and king are on initial position
 
@@ -426,7 +431,7 @@ class ChessRules
                        let step = finalSquares[castleSide][0] < y ? -1 : 1;
                        for (i=y; i!=finalSquares[castleSide][0]; i+=step)
                        {
-                               if (this.isAttacked([x,i], oppCol) || (this.board[x][i] != V.EMPTY &&
+                               if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY &&
                                        // NOTE: next check is enough, because of chessboard constraints
                                        (this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
                                {
@@ -474,11 +479,10 @@ class ChessRules
        ///////////////////
        // MOVES VALIDATION
 
-       canIplay(color, sq)
+       canIplay(side, [x,y])
        {
-               return ((color=='w' && this.movesCount%2==0)
-                               || (color=='b' && this.movesCount%2==1))
-                       && this.getColor(sq[0], sq[1]) == color;
+               return ((side=='w' && this.moves.length%2==0) || (side=='b' && this.moves.length%2==1))
+                       && this.getColor(x,y) == side;
        }
 
        getPossibleMovesFrom(sq)
@@ -492,21 +496,19 @@ class ChessRules
        {
                if (moves.length == 0)
                        return [];
-               let color = this.getColor( moves[0].start.x, moves[0].start.y );
-               return moves.filter(m => {
-                       return !this.underCheck(m, color);
-               });
+               return moves.filter(m => { return !this.underCheck(m); });
        }
 
        // Search for all valid moves considering current turn (for engine and game end)
-       getAllValidMoves(color)
+       getAllValidMoves()
        {
+               const color = this.turn;
                const oppCol = this.getOppCol(color);
-               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++)
                {
-                       for (var j=0; j<sizeY; j++)
+                       for (let j=0; j<sizeY; j++)
                        {
                                // Next condition ... != oppCol is a little HACK to work with checkered variant
                                if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
@@ -517,24 +519,25 @@ class ChessRules
                // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
                return this.filterValid(potentialMoves);
        }
-       
+
        // Stop at the first move found
-       atLeastOneMove(color)
+       atLeastOneMove()
        {
+               const color = this.turn;
                const oppCol = this.getOppCol(color);
-               let [sizeX,sizeY] = VariantRules.size;
-               for (var i=0; i<sizeX; i++)
+               const [sizeX,sizeY] = VariantRules.size;
+               for (let i=0; i<sizeX; i++)
                {
-                       for (var j=0; j<sizeY; j++)
+                       for (let j=0; j<sizeY; j++)
                        {
                                if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
                                {
                                        const moves = this.getPotentialMovesFrom([i,j]);
                                        if (moves.length > 0)
                                        {
-                                               for (let i=0; i<moves.length; i++)
+                                               for (let k=0; k<moves.length; k++)
                                                {
-                                                       if (this.filterValid([moves[i]]).length > 0)
+                                                       if (this.filterValid([moves[k]]).length > 0)
                                                                return true;
                                                }
                                        }
@@ -544,84 +547,93 @@ class ChessRules
                return false;
        }
 
-       // Check if pieces of color 'color' are attacking square x,y
-       isAttacked(sq, color)
+       // Check if pieces of color in array 'colors' are attacking square x,y
+       isAttacked(sq, colors)
        {
-               return (this.isAttackedByPawn(sq, color)
-                       || this.isAttackedByRook(sq, color)
-                       || this.isAttackedByKnight(sq, color)
-                       || this.isAttackedByBishop(sq, color)
-                       || this.isAttackedByQueen(sq, color)
-                       || this.isAttackedByKing(sq, color));
+               return (this.isAttackedByPawn(sq, colors)
+                       || this.isAttackedByRook(sq, colors)
+                       || this.isAttackedByKnight(sq, colors)
+                       || this.isAttackedByBishop(sq, colors)
+                       || this.isAttackedByQueen(sq, colors)
+                       || this.isAttackedByKing(sq, colors));
        }
 
-       // Is square x,y attacked by pawns of color c ?
-       isAttackedByPawn([x,y], c)
+       // Is square x,y attacked by 'colors' pawns ?
+       isAttackedByPawn([x,y], colors)
        {
-               let pawnShift = (c=="w" ? 1 : -1);
-               if (x+pawnShift>=0 && x+pawnShift<8)
+               const [sizeX,sizeY] = VariantRules.size;
+               for (let c of colors)
                {
-                       for (let i of [-1,1])
+                       let pawnShift = (c=="w" ? 1 : -1);
+                       if (x+pawnShift>=0 && x+pawnShift<sizeX)
                        {
-                               if (y+i>=0 && y+i<8 && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
-                                       && this.getColor(x+pawnShift,y+i)==c)
+                               for (let i of [-1,1])
                                {
-                                       return true;
+                                       if (y+i>=0 && y+i<sizeY && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
+                                               && this.getColor(x+pawnShift,y+i)==c)
+                                       {
+                                               return true;
+                                       }
                                }
                        }
                }
                return false;
        }
 
-       // Is square x,y attacked by rooks of color c ?
-       isAttackedByRook(sq, color)
+       // Is square x,y attacked by 'colors' rooks ?
+       isAttackedByRook(sq, colors)
        {
-               return this.isAttackedBySlideNJump(sq, color,
+               return this.isAttackedBySlideNJump(sq, colors,
                        VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
        }
 
-       // Is square x,y attacked by knights of color c ?
-       isAttackedByKnight(sq, color)
+       // Is square x,y attacked by 'colors' knights ?
+       isAttackedByKnight(sq, colors)
        {
-               return this.isAttackedBySlideNJump(sq, color,
+               return this.isAttackedBySlideNJump(sq, colors,
                        VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
        }
 
-       // Is square x,y attacked by bishops of color c ?
-       isAttackedByBishop(sq, color)
+       // Is square x,y attacked by 'colors' bishops ?
+       isAttackedByBishop(sq, colors)
        {
-               return this.isAttackedBySlideNJump(sq, color,
+               return this.isAttackedBySlideNJump(sq, colors,
                        VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
        }
 
-       // Is square x,y attacked by queens of color c ?
-       isAttackedByQueen(sq, color)
+       // Is square x,y attacked by 'colors' queens ?
+       isAttackedByQueen(sq, colors)
        {
-               return this.isAttackedBySlideNJump(sq, color,
-                       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]));
        }
 
-       // Is square x,y attacked by king of color c ?
-       isAttackedByKing(sq, color)
+       // Is square x,y attacked by 'colors' king(s) ?
+       isAttackedByKing(sq, colors)
        {
-               return this.isAttackedBySlideNJump(sq, color,
-                       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 ?
-       isAttackedBySlideNJump([x,y], c,piece,steps,oneStep)
+       // 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)
        {
+               const [sizeX,sizeY] = VariantRules.size;
                for (let step of steps)
                {
                        let rx = x+step[0], ry = y+step[1];
-                       while (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] == VariantRules.EMPTY
-                               && !oneStep)
+                       while (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
+                               && this.board[rx][ry] == VariantRules.EMPTY && !oneStep)
                        {
                                rx += step[0];
                                ry += step[1];
                        }
-                       if (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] != VariantRules.EMPTY
-                               && this.getPiece(rx,ry) == piece && this.getColor(rx,ry) == c)
+                       if (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
+                               && this.board[rx][ry] != VariantRules.EMPTY
+                               && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry)))
                        {
                                return true;
                        }
@@ -629,21 +641,23 @@ class ChessRules
                return false;
        }
 
-       // Is color c under check after move ?
-       underCheck(move, c)
+       // Is current player under check after his move ?
+       underCheck(move)
        {
+               const color = this.turn;
                this.play(move);
-               let res = this.isAttacked(this.kingPos[c], this.getOppCol(c));
+               let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)]);
                this.undo(move);
                return res;
        }
 
-       // On which squares is color c under check (after move) ?
-       getCheckSquares(move, c)
+       // On which squares is opponent under check after our move ?
+       getCheckSquares(move)
        {
                this.play(move);
-               let res = this.isAttacked(this.kingPos[c], this.getOppCol(c))
-                       ? [ JSON.parse(JSON.stringify(this.kingPos[c])) ] //need to duplicate!
+               const color = this.turn; //opponent
+               let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
+                       ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate!
                        : [ ];
                this.undo(move);
                return res;
@@ -666,105 +680,108 @@ class ChessRules
                        board[psq.x][psq.y] = psq.c + psq.p;
        }
 
-       // Before move is played:
+       // Before move is played, update variables + flags
        updateVariables(move)
        {
                const piece = this.getPiece(move.start.x,move.start.y);
                const c = this.getColor(move.start.x,move.start.y);
-               const firstRank = (c == "w" ? 7 : 0);
+               const [sizeX,sizeY] = VariantRules.size;
+               const firstRank = (c == "w" ? sizeX-1 : 0);
 
                // Update king position + flags
                if (piece == VariantRules.KING && move.appear.length > 0)
                {
                        this.kingPos[c][0] = move.appear[0].x;
                        this.kingPos[c][1] = move.appear[0].y;
-                       this.flags[c] = [false,false];
+                       this.castleFlags[c] = [false,false];
                        return;
                }
                const oppCol = this.getOppCol(c);
-               const oppFirstRank = 7 - firstRank;
+               const oppFirstRank = (sizeX-1) - firstRank;
                if (move.start.x == firstRank //our rook moves?
                        && this.INIT_COL_ROOK[c].includes(move.start.y))
                {
-                       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;
                }
                else if (move.end.x == oppFirstRank //we took opponent rook?
-                       && this.INIT_COL_ROOK[c].includes(move.end.y))
+                       && this.INIT_COL_ROOK[oppCol].includes(move.end.y))
                {
-                       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;
                }
        }
 
-       play(move, ingame)
+       // After move is undo-ed, un-update variables (flags are reset)
+       // TODO: more symmetry, by storing flags increment in move...
+       unupdateVariables(move)
        {
-               // Save flags (for undo)
-               move.flags = JSON.stringify(this.flags); //TODO: less costly
-               this.updateVariables(move);
+               // (Potentially) Reset king position
+               const c = this.getColor(move.start.x,move.start.y);
+               if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING)
+                       this.kingPos[c] = [move.start.x, move.start.y];
+       }
 
+       play(move, ingame)
+       {
                if (!!ingame)
-               {
-                       move.notation = this.getNotation(move);
-                       this.moves.push(move);
-               }
+                       move.notation = [this.getNotation(move), this.getLongNotation(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);
-               this.movesCount++;
        }
 
-       undo(move, ingame)
+       undo(move)
        {
                VariantRules.UndoOnBoard(this.board, move);
                this.epSquares.pop();
-               this.movesCount--;
-
-               if (!!ingame)
-                       this.moves.pop();
-
-               // Update king position, and reset stored/computed flags
-               const c = this.getColor(move.start.x,move.start.y);
-               if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING)
-                       this.kingPos[c] = [move.start.x, move.start.y];
-
-               this.flags = JSON.parse(move.flags);
+               this.moves.pop();
+               this.unupdateVariables(move);
+               this.parseFlags(JSON.parse(move.flags));
        }
 
        //////////////
        // END OF GAME
 
-       checkGameOver(color)
+       // Basic check for 3 repetitions (in the last moves only)
+       checkRepetition()
        {
-               // Check for 3 repetitions
                if (this.moves.length >= 8)
                {
-                       // 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)";
+                               return true;
                        }
                }
+               return false;
+       }
 
-               if (this.atLeastOneMove(color))
-               {
-                       // 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
                        return "*";
-               }
 
                // Game over
-               return this.checkGameEnd(color);
+               return this.checkGameEnd();
        }
 
-       // Useful stand-alone for engine
-       checkGameEnd(color)
+       // No moves are possible: compute score
+       checkGameEnd()
        {
+               const color = this.turn;
                // No valid move: stalemate or checkmate?
-               if (!this.isAttacked(this.kingPos[color], this.getOppCol(color)))
+               if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)]))
                        return "1/2";
                // OK, checkmate
                return color == "w" ? "0-1" : "1-0";
@@ -785,77 +802,136 @@ class ChessRules
                };
        }
 
+       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)
+       }
+
        // Assumption: at least one legal move
-       getComputerMove(color)
+       // NOTE: works also for extinction chess because depth is 3...
+       getComputerMove()
        {
-               const oppCol = this.getOppCol(color);
+               this.shouldReturn = false;
+               const maxeval = VariantRules.INFINITY;
+               const color = this.turn;
+               // Some variants may show a bigger moves list to the human (Switching),
+               // thus the argument "computer" below (which is generally ignored)
+               let moves1 = this.getAllValidMoves("computer");
+
+               // Can I mate in 1 ? (for Magnetic & Extinction)
+               for (let i of _.shuffle(_.range(moves1.length)))
+               {
+                       this.play(moves1[i]);
+                       const finish = (Math.abs(this.evalPosition()) >= VariantRules.THRESHOLD_MATE);
+                       this.undo(moves1[i]);
+                       if (finish)
+                               return moves1[i];
+               }
 
                // Rank moves using a min-max at depth 2
-               let moves1 = this.getAllValidMoves(color);
-
                for (let i=0; i<moves1.length; i++)
                {
-                       moves1[i].eval = (color=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
-                       let eval2 = (color=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
+                       moves1[i].eval = (color=="w" ? -1 : 1) * maxeval; //very low, I'm checkmated
                        this.play(moves1[i]);
-                       // Second half-move:
-                       let moves2 = this.getAllValidMoves(oppCol);
-                       // If no possible moves AND underCheck, eval2 is correct.
-                       // If !underCheck, eval2 is 0 (stalemate).
-                       if (moves2.length == 0 && this.checkGameEnd(oppCol) == "1/2")
-                               eval2 = 0;
-                       for (let j=0; j<moves2.length; j++)
+                       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
                        {
-                               this.play(moves2[j]);
-                               let evalPos = this.evalPosition();
-                               if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
-                                       eval2 = evalPos;
-                               this.undo(moves2[j]);
+                               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;
                        this.undo(moves1[i]);
                }
                moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
-
-               // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
-               for (let i=0; i<moves1.length; i++)
-               {
-                       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(oppCol, color, 2, -1000, 1000);
-                       this.undo(moves1[i]);
-               }
-               moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
+               //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
 
                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)];
 
+               // 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 (this.shouldReturn)
+                                       return currentBest; //depth-2, minimum
+                               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;
                //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
+
+               candidates = [0];
+               for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
+                       candidates.push(j);
                return moves1[_.sample(candidates, 1)];
        }
 
-       alphabeta(color, oppCol, depth, alpha, beta)
+       alphabeta(depth, alpha, beta)
   {
-               const moves = this.getAllValidMoves(color);
-               if (moves.length == 0)
+               const maxeval = VariantRules.INFINITY;
+               const color = this.turn;
+               if (!this.atLeastOneMove())
                {
-                       switch (this.checkGameEnd(color))
+                       switch (this.checkGameEnd())
                        {
-                               case "1/2": return 0;
-                               default: return color=="w" ? -1000 : 1000;
+                               case "1/2":
+                                       return 0;
+                               default:
+                                       const score = this.checkGameEnd();
+                                       return (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
                        }
                }
                if (depth == 0)
       return this.evalPosition();
-    let v = color=="w" ? -1000 : 1000;
+               const moves = this.getAllValidMoves("computer");
+    let v = color=="w" ? -maxeval : maxeval;
                if (color == "w")
                {
                        for (let i=0; i<moves.length; i++)
       {
                                this.play(moves[i]);
-                               v = Math.max(v, this.alphabeta(oppCol, color, depth-1, alpha, beta));
+                               v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
                                this.undo(moves[i]);
                                alpha = Math.max(alpha, v);
                                if (alpha >= beta)
@@ -867,7 +943,7 @@ class ChessRules
                        for (let i=0; i<moves.length; i++)
                        {
                                this.play(moves[i]);
-                               v = Math.min(v, this.alphabeta(oppCol, color, depth-1, alpha, beta));
+                               v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
                                this.undo(moves[i]);
                                beta = Math.min(beta, v);
                                if (alpha >= beta)
@@ -881,7 +957,7 @@ class ChessRules
        {
                const [sizeX,sizeY] = VariantRules.size;
                let evaluation = 0;
-               //Just count material for now
+               // Just count material for now
                for (let i=0; i<sizeX; i++)
                {
                        for (let j=0; j<sizeY; j++)
@@ -899,7 +975,7 @@ class ChessRules
        ////////////
        // FEN utils
 
-       // Overridable..
+       // Setup the initial random (assymetric) position
        static GenRandInitFen()
        {
                let pieces = [new Array(8), new Array(8)];
@@ -949,21 +1025,17 @@ class ChessRules
                let fen = pieces[0].join("") +
                        "/pppppppp/8/8/8/8/PPPPPPPP/" +
                        pieces[1].join("").toUpperCase() +
-                       " 1111 - 0"; //flags + enPassant + movesCount
+                       " 1111"; //add flags
                return fen;
        }
 
        // Return current fen according to pieces+colors state
        getFen()
        {
-               const L = this.epSquares.length;
-               const epSq = this.epSquares[L-1]===undefined
-                       ? "-"
-                       : this.epSquares[L-1].x+","+this.epSquares[L-1].y;
-               return this.getBaseFen() + " " + this.getFlagsFen()
-                       + " " + epSq + " " + this.movesCount;
+               return this.getBaseFen() + " " + this.getFlagsFen();
        }
 
+       // Position part of the FEN string
        getBaseFen()
        {
                let fen = "";
@@ -997,7 +1069,7 @@ class ChessRules
                return fen;
        }
 
-       // Overridable..
+       // Flags part of the FEN string
        getFlagsFen()
        {
                let fen = "";
@@ -1005,7 +1077,7 @@ class ChessRules
                for (let i of ['w','b'])
                {
                        for (let j=0; j<2; j++)
-                               fen += this.flags[i][j] ? '1' : '0';
+                               fen += (this.castleFlags[i][j] ? '1' : '0');
                }
                return fen;
        }
@@ -1013,28 +1085,22 @@ class ChessRules
        // Context: just before move is played, turn hasn't changed
        getNotation(move)
        {
-               if (move.appear.length == 2)
-               {
-                       // 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");
 
                // Translate final square
-               let finalSquare =
+               const finalSquare =
                        String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
 
-               let piece = this.getPiece(move.start.x, move.start.y);
+               const piece = this.getPiece(move.start.x, move.start.y);
                if (piece == VariantRules.PAWN)
                {
                        // Pawn move
                        let notation = "";
-                       if (move.vanish.length > 1)
+                       if (move.vanish.length > move.appear.length)
                        {
                                // Capture
-                               let startColumn = String.fromCharCode(97 + move.start.y);
+                               const startColumn = String.fromCharCode(97 + move.start.y);
                                notation = startColumn + "x" + finalSquare;
                        }
                        else //no capture
@@ -1047,30 +1113,54 @@ class ChessRules
                else
                {
                        // Piece movement
-                       return piece.toUpperCase() + (move.vanish.length > 1 ? "x" : "") + finalSquare;
+                       return piece.toUpperCase() +
+                               (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
                }
        }
 
+       // 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)
+       getPGN(mycolor, score, fenStart, mode)
        {
+               const zeroPad = x => { return (x<10 ? "0" : "") + x; };
                let pgn = "";
                pgn += '[Site "vchess.club"]<br>';
                const d = new Date();
-               pgn += '[Date "' + d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() + '"]<br>';
-               pgn += '[White "' + (mycolor=='w'?'Myself':'Anonymous') + '"]<br>';
-               pgn += '[Black "' + (mycolor=='b'?'Myself':'Anonymous') + '"]<br>';
-               pgn += '[Fen "' + fenStart + '"]<br>';
+               const opponent = mode=="human" ? "Anonymous" : "Computer";
+               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 += '[FenStart "' + fenStart + '"]<br>';
+               pgn += '[Fen "' + this.getFen() + '"]<br>';
                pgn += '[Result "' + score + '"]<br><br>';
 
+               // Standard PGN
+               for (let i=0; i<this.moves.length; i++)
+               {
+                       if (i % 2 == 0)
+                               pgn += ((i/2)+1) + ".";
+                       pgn += this.moves[i].notation[0] + " ";
+               }
+               pgn += "<br><br>";
+
+               // "Complete moves" PGN (helping in ambiguous cases)
                for (let i=0; i<this.moves.length; i++)
                {
                        if (i % 2 == 0)
                                pgn += ((i/2)+1) + ".";
-                       pgn += this.moves[i].notation + " ";
+                       pgn += this.moves[i].notation[1] + " ";
                }
 
-               pgn += score;
                return pgn;
        }
 }