Draft code reorganisation (+ fix Alice rules + stateless VariantRules object)
[vchess.git] / public / javascripts / variants / Alice.js
index d457f5f..57c7b25 100644 (file)
@@ -1,3 +1,4 @@
+// NOTE: alternative implementation, probably cleaner = use only 1 board
 class AliceRules extends ChessRules
 {
        static get ALICE_PIECES()
@@ -28,20 +29,24 @@ class AliceRules extends ChessRules
                return (Object.keys(this.ALICE_PIECES).includes(b[1]) ? "Alice/" : "") + b;
        }
 
-       initVariables(fen)
+       static get PIECES()
        {
-               super.initVariables(fen);
-               const fenParts = fen.split(" ");
-               const position = fenParts[0].split("/");
+               return ChessRules.PIECES.concat(Object.keys(V.ALICE_PIECES));
+       }
+
+       setOtherVariables(fen)
+       {
+               super.setOtherVariables(fen);
+               const rows = V.ParseFen(fen).position.split("/");
                if (this.kingPos["w"][0] < 0 || this.kingPos["b"][0] < 0)
                {
-                       // INIT_COL_XXX won't be used, so no need to set them for Alice kings
-                       for (let i=0; i<position.length; i++)
+                       // INIT_COL_XXX won't be required if Alice kings are found (means 'king moved')
+                       for (let i=0; i<rows.length; i++)
                        {
                                let k = 0; //column index on board
-                               for (let j=0; j<position[i].length; j++)
+                               for (let j=0; j<rows[i].length; j++)
                                {
-                                       switch (position[i].charAt(j))
+                                       switch (rows[i].charAt(j))
                                        {
                                                case 'l':
                                                        this.kingPos['b'] = [i,k];
@@ -50,7 +55,7 @@ class AliceRules extends ChessRules
                                                        this.kingPos['w'] = [i,k];
                                                        break;
                                                default:
-                                                       let num = parseInt(position[i].charAt(j));
+                                                       const num = parseInt(rows[i].charAt(j));
                                                        if (!isNaN(num))
                                                                k += (num-1);
                                        }
@@ -60,61 +65,74 @@ class AliceRules extends ChessRules
                }
        }
 
-       getBoardOfPiece([x,y])
+       // Return the (standard) color+piece notation at a square for a board
+       getSquareOccupation(i, j, mirrorSide)
+       {
+               const piece = this.getPiece(i,j);
+               if (mirrorSide==1 && Object.keys(V.ALICE_CODES).includes(piece))
+                       return this.board[i][j];
+               else if (mirrorSide==2 && Object.keys(V.ALICE_PIECES).includes(piece))
+                       return this.getColor(i,j) + V.ALICE_PIECES[piece];
+               return "";
+       }
+
+       // Build board of the given (mirror)side
+       getSideBoard(mirrorSide)
        {
-               const V = VariantRules;
-               // Build board where the piece is
-               const mirrorSide = (Object.keys(V.ALICE_CODES).includes(this.getPiece(x,y)) ? 1 : 2);
                // Build corresponding board from complete board
-               const [sizeX,sizeY] = V.size;
-               let sideBoard = doubleArray(sizeX, sizeY, "");
-               for (let i=0; i<sizeX; i++)
+               let sideBoard = doubleArray(V.size.x, V.size.y, "");
+               for (let i=0; i<V.size.x; i++)
                {
-                       for (let j=0; j<sizeY; j++)
-                       {
-                               const piece = this.getPiece(i,j);
-                               if (mirrorSide==1 && Object.keys(V.ALICE_CODES).includes(piece))
-                                       sideBoard[i][j] = this.board[i][j];
-                               else if (mirrorSide==2 && Object.keys(V.ALICE_PIECES).includes(piece))
-                                       sideBoard[i][j] = this.getColor(i,j) + V.ALICE_PIECES[piece];
-                       }
+                       for (let j=0; j<V.size.y; j++)
+                               sideBoard[i][j] = this.getSquareOccupation(i, j, mirrorSide);
                }
                return sideBoard;
        }
 
-       // TODO: move board building one level up (findAllMoves()) to avoid re-building at every piece...
        // NOTE: castle & enPassant https://www.chessvariants.com/other.dir/alice.html
-       // --> Should be OK as is.
-       getPotentialMovesFrom([x,y])
+       getPotentialMovesFrom([x,y], sideBoard)
        {
-               let sideBoard = this.getBoardOfPiece([x,y]);
+               const pieces = Object.keys(V.ALICE_CODES);
+               const codes = Object.keys(V.ALICE_PIECES);
+               const mirrorSide = (pieces.includes(this.getPiece(x,y)) ? 1 : 2);
+               const color = this.getColor(x,y);
 
                // Search valid moves on sideBoard
                let saveBoard = this.board;
-               this.board = sideBoard;
-               let moves = super.getPotentialMovesFrom([x,y]);
+               this.board = sideBoard || this.getSideBoard(mirrorSide);
+               let moves = super.getPotentialMovesFrom([x,y])
+                       .filter(m => {
+                               // Filter out king moves which result in under-check position on
+                               // current board (before mirror traversing)
+                               let aprioriValid = true;
+                               if (m.appear[0].p == V.KING)
+                               {
+                                       this.play(m);
+                                       if (this.underCheck(color))
+                                               aprioriValid = false;
+                                       this.undo(m);
+                               }
+                               return aprioriValid;
+                       });
                this.board = saveBoard;
 
                // Finally filter impossible moves
-               const mirrorSide = (Object.keys(VariantRules.ALICE_CODES).includes(this.getPiece(x,y)) ? 1 : 2);
-               return moves.filter(m => {
+               let res = moves.filter(m => {
                        if (m.appear.length == 2) //castle
                        {
-                               // If appear[i] not in vanish array, then must be empty square on other board
-                               m.appear.forEach(psq => {
-                                       if (this.board[psq.x][psq.y] != VariantRules.EMPTY &&
-                                               ![m.vanish[0].y,m.vanish[1].y].includes(psq.y))
-                                       {
+                               // appear[i] must be an empty square on the other board
+                               for (let psq of m.appear)
+                               {
+                                       if (this.getSquareOccupation(psq.x,psq.y,3-mirrorSide) != V.EMPTY)
                                                return false;
-                                       }
-                               });
+                               }
                        }
-                       else if (this.board[m.end.x][m.end.y] != VariantRules.EMPTY)
+                       else if (this.board[m.end.x][m.end.y] != V.EMPTY)
                        {
                                // Attempt to capture
                                const piece = this.getPiece(m.end.x,m.end.y);
-                               if ((mirrorSide==1 && Object.keys(VariantRules.ALICE_PIECES).includes(piece))
-                                       || (mirrorSide==2 && Object.keys(VariantRules.ALICE_CODES).includes(piece)))
+                               if ((mirrorSide==1 && codes.includes(piece))
+                                       || (mirrorSide==2 && pieces.includes(piece)))
                                {
                                        return false;
                                }
@@ -123,52 +141,137 @@ class AliceRules extends ChessRules
                        if (mirrorSide==1)
                        {
                                m.appear.forEach(psq => { //forEach: castling taken into account
-                                       psq.p = VariantRules.ALICE_CODES[psq.p]; //goto board2
+                                       psq.p = V.ALICE_CODES[psq.p]; //goto board2
                                });
                        }
                        else //move on board2: mark vanishing pieces as Alice
                        {
                                m.vanish.forEach(psq => {
-                                       psq.p = VariantRules.ALICE_CODES[psq.p];
+                                       psq.p = V.ALICE_CODES[psq.p];
                                });
                        }
+                       // Fix en-passant captures
+                       if (m.vanish[0].p == V.PAWN && m.vanish.length == 2
+                               && this.board[m.end.x][m.end.y] == V.EMPTY)
+                       {
+                               m.vanish[1].c = this.getOppCol(this.getColor(x,y));
+                               // In the special case of en-passant, if
+                               //  - board1 takes board2 : vanish[1] --> Alice
+                               //  - board2 takes board1 : vanish[1] --> normal
+                               let van = m.vanish[1];
+                               if (mirrorSide==1 && codes.includes(this.getPiece(van.x,van.y)))
+                                       van.p = V.ALICE_CODES[van.p];
+                               else if (mirrorSide==2 && pieces.includes(this.getPiece(van.x,van.y)))
+                                       van.p = V.ALICE_PIECES[van.p];
+                       }
                        return true;
                });
+               return res;
+       }
+
+       filterValid(moves)
+       {
+               if (moves.length == 0)
+                       return [];
+               let sideBoard = [this.getSideBoard(1), this.getSideBoard(2)];
+               const color = this.turn;
+               return moves.filter(m => {
+                       this.playSide(m, sideBoard); //no need to track flags
+                       const res = !this.underCheck(color, sideBoard);
+                       this.undoSide(m, sideBoard);
+                       return res;
+               });
        }
 
-       underCheck(move)
+       getAllValidMoves()
        {
                const color = this.turn;
-               this.play(move);
-               let sideBoard = this.getBoardOfPiece(this.kingPos[color]);
+               const oppCol = this.getOppCol(color);
+               var potentialMoves = [];
+               let sideBoard = [this.getSideBoard(1), this.getSideBoard(2)];
+               for (var i=0; i<V.size.x; i++)
+               {
+                       for (var j=0; j<V.size.y; j++)
+                       {
+                               if (this.board[i][j] != V.EMPTY && this.getColor(i,j) == color)
+                               {
+                                       const mirrorSide =
+                                               Object.keys(V.ALICE_CODES).includes(this.getPiece(i,j))
+                                                       ? 1
+                                                       : 2;
+                                       Array.prototype.push.apply(potentialMoves,
+                                               this.getPotentialMovesFrom([i,j], sideBoard[mirrorSide-1]));
+                               }
+                       }
+               }
+               return this.filterValid(potentialMoves, sideBoard);
+       }
+
+       // Play on sideboards [TODO: only one sideBoard required]
+       playSide(move, sideBoard)
+       {
+               const pieces = Object.keys(V.ALICE_CODES);
+               move.vanish.forEach(psq => {
+                       const mirrorSide = (pieces.includes(psq.p) ? 1 : 2);
+                       sideBoard[mirrorSide-1][psq.x][psq.y] = V.EMPTY;
+               });
+               move.appear.forEach(psq => {
+                       const mirrorSide = (pieces.includes(psq.p) ? 1 : 2);
+                       const piece = (mirrorSide == 1 ? psq.p : V.ALICE_PIECES[psq.p]);
+                       sideBoard[mirrorSide-1][psq.x][psq.y] = psq.c + piece;
+                       if (piece == V.KING)
+                               this.kingPos[psq.c] = [psq.x,psq.y];
+               });
+       }
+
+       // Undo on sideboards
+       undoSide(move, sideBoard)
+       {
+               const pieces = Object.keys(V.ALICE_CODES);
+               move.appear.forEach(psq => {
+                       const mirrorSide = (pieces.includes(psq.p) ? 1 : 2);
+                       sideBoard[mirrorSide-1][psq.x][psq.y] = V.EMPTY;
+               });
+               move.vanish.forEach(psq => {
+                       const mirrorSide = (pieces.includes(psq.p) ? 1 : 2);
+                       const piece = (mirrorSide == 1 ? psq.p : V.ALICE_PIECES[psq.p]);
+                       sideBoard[mirrorSide-1][psq.x][psq.y] = psq.c + piece;
+                       if (piece == V.KING)
+                               this.kingPos[psq.c] = [psq.x,psq.y];
+               });
+       }
+
+       underCheck(color, sideBoard) //sideBoard arg always provided
+       {
+               const kp = this.kingPos[color];
+               const mirrorSide = (sideBoard[0][kp[0]][kp[1]] != V.EMPTY ? 1 : 2);
                let saveBoard = this.board;
-               this.board = sideBoard;
-               let res = this.isAttacked(this.kingPos[color], this.getOppCol(color));
+               this.board = sideBoard[mirrorSide-1];
+               let res = this.isAttacked(kp, [this.getOppCol(color)]);
                this.board = saveBoard;
-               this.undo(move);
                return res;
        }
 
-       getCheckSquares(move)
+       getCheckSquares(color)
        {
-               this.play(move);
-               const color = this.turn; //opponent
-               let sideBoard = this.getBoardOfPiece(this.kingPos[color]);
+               const pieces = Object.keys(V.ALICE_CODES);
+               const kp = this.kingPos[color];
+               const mirrorSide = (pieces.includes(this.getPiece(kp[0],kp[1])) ? 1 : 2);
+               let sideBoard = this.getSideBoard(mirrorSide);
                let saveBoard = this.board;
                this.board = sideBoard;
-               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])) ]
                        : [ ];
                this.board = saveBoard;
-               this.undo(move);
                return res;
        }
 
        updateVariables(move)
        {
                super.updateVariables(move); //standard king
-               const piece = this.getPiece(move.start.x,move.start.y);
-               const c = this.getColor(move.start.x,move.start.y);
+               const piece = move.vanish[0].p;
+               const c = move.vanish[0].c;
                // "l" = Alice king
                if (piece == "l")
                {
@@ -181,14 +284,47 @@ class AliceRules extends ChessRules
        unupdateVariables(move)
        {
                super.unupdateVariables(move);
-               const c = this.getColor(move.start.x,move.start.y);
-               if (this.getPiece(move.start.x,move.start.y) == "l")
+               const c = move.vanish[0].c;
+               if (move.vanish[0].p == "l")
                        this.kingPos[c] = [move.start.x, move.start.y];
        }
 
+       checkGameEnd()
+       {
+               const pieces = Object.keys(V.ALICE_CODES);
+               const color = this.turn;
+               const kp = this.kingPos[color];
+               const mirrorSide = (pieces.includes(this.getPiece(kp[0],kp[1])) ? 1 : 2);
+               let sideBoard = this.getSideBoard(mirrorSide);
+               let saveBoard = this.board;
+               this.board = sideBoard;
+               let res = "*";
+               if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)]))
+                       res = "1/2";
+               else
+                       res = (color == "w" ? "0-1" : "1-0");
+               this.board = saveBoard;
+               return res;
+       }
+
+       static get VALUES()
+       {
+               return Object.assign(
+                       ChessRules.VALUES,
+                       {
+                               's': 1,
+                               'u': 5,
+                               'o': 3,
+                               'c': 3,
+                               't': 9,
+                               'l': 1000,
+                       }
+               );
+       }
+
        getNotation(move)
        {
-               if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING)
+               if (move.appear.length == 2 && move.appear[0].p == V.KING)
                {
                        if (move.end.y < move.start.y)
                                return "0-0-0";
@@ -196,13 +332,16 @@ class AliceRules extends ChessRules
                                return "0-0";
                }
 
-               const finalSquare =
-                       String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
+               const finalSquare = V.CoordsToSquare(move.end);
                const piece = this.getPiece(move.start.x, move.start.y);
 
+               const captureMark = (move.vanish.length > move.appear.length ? "x" : "");
+               let pawnMark = "";
+               if (["p","s"].includes(piece) && captureMark.length == 1)
+                       pawnMark = V.CoordToColumn(move.start.y); //start column
+
                // Piece or pawn movement
-               let notation = piece.toUpperCase() +
-                       (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
+               let notation = piece.toUpperCase() + pawnMark + captureMark + finalSquare;
                if (['s','p'].includes(piece) && !['s','p'].includes(move.appear[0].p))
                {
                        // Promotion
@@ -210,19 +349,6 @@ class AliceRules extends ChessRules
                }
                return notation;
        }
-
-       checkGameEnd()
-       {
-               const color = this.turn;
-               let sideBoard = this.getBoardOfPiece(this.kingPos[color]);
-               let saveBoard = this.board;
-               this.board = sideBoard;
-               let res = "*";
-               if (!this.isAttacked(this.kingPos[color], this.getOppCol(color)))
-                       res = "1/2";
-               else
-                       res = (color == "w" ? "0-1" : "1-0");
-               this.board = saveBoard;
-               return res;
-       }
 }
+
+const VariantRules = AliceRules;