Adjust comments, add a few TODOs + remove DEBUG in play/undo
[vchess.git] / public / javascripts / base_rules.js
index d4315c7..79b6a7a 100644 (file)
@@ -124,7 +124,7 @@ class ChessRules
                return board;
        }
 
-       // Overridable: flags can change a lot
+       // Extract (relevant) flags from fen
        setFlags(fen)
        {
                // white a-castle, h-castle, black a-castle, h-castle
@@ -137,7 +137,6 @@ class ChessRules
        ///////////////////
        // 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); }
@@ -199,7 +198,7 @@ class ChessRules
                return undefined; //default
        }
 
-       // can thing on square1 take thing on square2
+       // Can thing on square1 take thing on square2
        canTake([x1,y1], [x2,y2])
        {
                return this.getColor(x1,y1) != this.getColor(x2,y2);
@@ -276,7 +275,8 @@ class ChessRules
                {
                        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)
+                       while (i>=0 && i<sizeX && j>=0 && j<sizeY
+                               && this.board[i][j] == VariantRules.EMPTY)
                        {
                                moves.push(this.getBasicMove([x,y], [i,j]));
                                if (oneStep !== undefined)
@@ -284,23 +284,23 @@ class ChessRules
                                i += step[0];
                                j += step[1];
                        }
-                       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;
        }
 
-       // What are the pawn moves from square x,y considering color "color" ?
+       // What are the pawn moves from square x,y ?
        getPotentialPawnMoves([x,y])
        {
                const color = this.turn;
                let moves = [];
                const V = VariantRules;
-               const [sizeX,sizeY] = VariantRules.size;
+               const [sizeX,sizeY] = V.size;
                const shift = (color == "w" ? -1 : 1);
-               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 (x+shift >= 0 && x+shift < sizeX && x+shift != lastRank)
                {
@@ -308,7 +308,7 @@ class ChessRules
                        if (this.board[x+shift][y] == V.EMPTY)
                        {
                                moves.push(this.getBasicMove([x,y], [x+shift,y]));
-                               // Next condition because variants with pawns on 1st rank generally allow them to jump
+                               // 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
@@ -316,10 +316,16 @@ class ChessRules
                                }
                        }
                        // Captures
-                       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]));
-                       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]));
+                       }
                }
 
                if (x+shift == lastRank)
@@ -331,10 +337,16 @@ class ChessRules
                                if (this.board[x+shift][y] == V.EMPTY)
                                        moves.push(this.getBasicMove([x,y], [x+shift,y], {c:color,p:p}));
                                // Captures
-                               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], {c:color,p:p}));
-                               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], {c:color,p:p}));
+                               }
                        });
                }
 
@@ -417,7 +429,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)))))
                                {
@@ -492,9 +504,9 @@ class ChessRules
                const oppCol = this.getOppCol(color);
                let potentialMoves = [];
                const [sizeX,sizeY] = VariantRules.size;
-               for (var i=0; i<sizeX; i++)
+               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)
@@ -533,7 +545,7 @@ class ChessRules
                return false;
        }
 
-       // Check if pieces of color 'colors' are attacking square x,y
+       // Check if pieces of color in array 'colors' are attacking square x,y
        isAttacked(sq, colors)
        {
                return (this.isAttackedByPawn(sq, colors)
@@ -544,17 +556,18 @@ class ChessRules
                        || this.isAttackedByKing(sq, colors));
        }
 
-       // Is square x,y attacked by pawns of color c ?
+       // Is square x,y attacked by 'colors' pawns ?
        isAttackedByPawn([x,y], colors)
        {
+               const [sizeX,sizeY] = VariantRules.size;
                for (let c of colors)
                {
                        let pawnShift = (c=="w" ? 1 : -1);
-                       if (x+pawnShift>=0 && x+pawnShift<8)
+                       if (x+pawnShift>=0 && x+pawnShift<sizeX)
                        {
                                for (let i of [-1,1])
                                {
-                                       if (y+i>=0 && y+i<8 && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
+                                       if (y+i>=0 && y+i<sizeY && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
                                                && this.getColor(x+pawnShift,y+i)==c)
                                        {
                                                return true;
@@ -565,28 +578,28 @@ class ChessRules
                return false;
        }
 
-       // Is square x,y attacked by rooks of color c ?
+       // Is square x,y attacked by 'colors' rooks ?
        isAttackedByRook(sq, colors)
        {
                return this.isAttackedBySlideNJump(sq, colors,
                        VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
        }
 
-       // Is square x,y attacked by knights of color c ?
+       // Is square x,y attacked by 'colors' knights ?
        isAttackedByKnight(sq, colors)
        {
                return this.isAttackedBySlideNJump(sq, colors,
                        VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
        }
 
-       // Is square x,y attacked by bishops of color c ?
+       // Is square x,y attacked by 'colors' bishops ?
        isAttackedByBishop(sq, colors)
        {
                return this.isAttackedBySlideNJump(sq, colors,
                        VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
        }
 
-       // Is square x,y attacked by queens of color c ?
+       // Is square x,y attacked by 'colors' queens ?
        isAttackedByQueen(sq, colors)
        {
                const V = VariantRules;
@@ -594,7 +607,7 @@ class ChessRules
                        V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
        }
 
-       // Is square x,y attacked by king of color c ?
+       // Is square x,y attacked by 'colors' king(s) ?
        isAttackedByKing(sq, colors)
        {
                const V = VariantRules;
@@ -602,19 +615,22 @@ class ChessRules
                        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)
        {
+               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
+                       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;
@@ -623,22 +639,22 @@ class ChessRules
                return false;
        }
 
-       // Is color c under check after move ?
+       // Is current player under check after his move ?
        underCheck(move)
        {
                const color = this.turn;
                this.play(move);
-               let res = this.isAttacked(this.kingPos[color], this.getOppCol(color));
+               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) ?
+       // On which squares is opponent under check after our move ?
        getCheckSquares(move)
        {
                this.play(move);
                const color = this.turn; //opponent
-               let res = this.isAttacked(this.kingPos[color], this.getOppCol(color))
+               let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
                        ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate!
                        : [ ];
                this.undo(move);
@@ -694,6 +710,8 @@ class ChessRules
                }
        }
 
+       // After move is undo-ed, un-update variables (flags are reset)
+       // TODO: more symmetry, by storing flags increment in move...
        unupdateVariables(move)
        {
                // (Potentially) Reset king position
@@ -704,12 +722,8 @@ class ChessRules
 
        play(move, ingame)
        {
-               // DEBUG:
-//             if (!this.states) this.states = [];
-//             if (!ingame) this.states.push(JSON.stringify(this.board));
-
                if (!!ingame)
-                       move.notation = this.getNotation(move);
+                       move.notation = [this.getNotation(move), this.getLongNotation(move)];
 
                move.flags = JSON.stringify(this.flags); //save flags (for undo)
                this.updateVariables(move);
@@ -725,22 +739,16 @@ class ChessRules
                this.moves.pop();
                this.unupdateVariables(move);
                this.parseFlags(JSON.parse(move.flags));
-
-               // DEBUG:
-//             let state = this.states.pop();
-//             if (JSON.stringify(this.board) != state)
-//                     debugger;
        }
 
        //////////////
        // END OF GAME
 
+       // 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]) &&
@@ -753,6 +761,7 @@ class ChessRules
                return false;
        }
 
+       // Is game over ? And if yes, what is the score ?
        checkGameOver()
        {
                if (this.checkRepetition())
@@ -770,7 +779,7 @@ class ChessRules
        {
                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";
@@ -800,13 +809,28 @@ class ChessRules
                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(moves1) //moves1 might be precomputed (Magnetic chess)
+       // NOTE: works also for extinction chess because depth is 3...
+       getComputerMove()
        {
+               this.shouldReturn = false;
                const maxeval = VariantRules.INFINITY;
                const color = this.turn;
-               if (!moves1)
-                       moves1 = this.getAllValidMoves();
+               let moves1 = this.getAllValidMoves();
+
+               // 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
                for (let i=0; i<moves1.length; i++)
@@ -834,27 +858,38 @@ class ChessRules
                }
                moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
 
-               // Skip depth 3 if we found a checkmate (or if we are checkmated in 1...)
-               if (Math.abs(moves1[0].eval) < VariantRules.THRESHOLD_MATE)
+               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)
                {
-                       // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
                        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(2, -maxeval, maxeval);
+                               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;
 
-               let candidates = [0]; //indices of candidates moves
+               candidates = [0];
                for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
                        candidates.push(j);
 //             console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
                return moves1[_.sample(candidates, 1)];
        }
 
+       // TODO: some optimisations, understand why CH get mated in 2
        alphabeta(depth, alpha, beta)
   {
                const maxeval = VariantRules.INFINITY;
@@ -902,7 +937,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++)
@@ -920,7 +955,7 @@ class ChessRules
        ////////////
        // FEN utils
 
-       // Overridable..
+       // Setup the initial random (assymetric) position
        static GenRandInitFen()
        {
                let pieces = [new Array(8), new Array(8)];
@@ -980,6 +1015,7 @@ class ChessRules
                return this.getBaseFen() + " " + this.getFlagsFen();
        }
 
+       // Position part of the FEN string
        getBaseFen()
        {
                let fen = "";
@@ -1013,7 +1049,7 @@ class ChessRules
                return fen;
        }
 
-       // Overridable..
+       // Flags part of the FEN string
        getFlagsFen()
        {
                let fen = "";
@@ -1068,6 +1104,16 @@ class ChessRules
                }
        }
 
+       // 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)
        {
@@ -1082,14 +1128,24 @@ class ChessRules
                pgn += '[Fen "' + fenStart + '"]<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 + " ";
+                       pgn += this.moves[i].notation[0] + " ";
                }
+               pgn += score + "<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[1] + " ";
+               }
                pgn += score;
+
                return pgn;
        }
 }