Attempt to clarify installation instructions a little
[vchess.git] / client / src / variants / Dynamo.js
index afa9a88..528f8c1 100644 (file)
@@ -2,6 +2,7 @@ import { ChessRules, Move, PiPo } from "@/base_rules";
 import { randInt } from "@/utils/alea";
 
 export class DynamoRules extends ChessRules {
+
   // TODO? later, allow to push out pawns on a and h files
   static get HasEnpassant() {
     return false;
@@ -43,7 +44,6 @@ export class DynamoRules extends ChessRules {
       });
       this.amoves.push(move);
     }
-    this.subTurn = 1;
     // Stack "first moves" (on subTurn 1) to merge and check opposite moves
     this.firstMove = [];
   }
@@ -67,7 +67,7 @@ export class DynamoRules extends ChessRules {
       for (let part of amoveParts) {
         if (part != "-") {
           for (let psq of part.split("."))
-            if (!psq.match(/^[a-r]{3}[1-8]$/)) return false;
+            if (!psq.match(/^[a-z]{3}[1-8]$/)) return false;
         }
       }
     }
@@ -440,9 +440,10 @@ export class DynamoRules extends ChessRules {
     }
     const getPullExit = () => {
       // Piece at subTurn 1 exited: can I be pulled?
-      // Note: pawns and kings cannot suicide,
-      // so fm.vanish[0].p is neither PAWN or KING
+      // Note: kings cannot suicide, so fm.vanish[0].p is not KING.
+      // Could be PAWN though, if a pawn was pushed out of board.
       if (
+        fm.vanish[0].p != V.PAWN && //pawns cannot pull
         this.isAprioriValidExit(
           [x, y],
           [fm.start.x, fm.start.y],
@@ -564,7 +565,6 @@ export class DynamoRules extends ChessRules {
   // Does m2 un-do m1 ? (to disallow undoing actions)
   oppositeMoves(m1, m2) {
     const isEqual = (av1, av2) => {
-      // Precondition: av1 and av2 length = 2
       for (let av of av1) {
         const avInAv2 = av2.find(elt => {
           return (
@@ -578,11 +578,12 @@ export class DynamoRules extends ChessRules {
       }
       return true;
     };
+    // All appear and vanish arrays must have the same length
+    const mL = m1.appear.length;
     return (
-      m1.appear.length == 2 &&
-      m2.appear.length == 2 &&
-      m1.vanish.length == 2 &&
-      m2.vanish.length == 2 &&
+      m2.appear.length == mL &&
+      m1.vanish.length == mL &&
+      m2.vanish.length == mL &&
       isEqual(m1.appear, m2.vanish) &&
       isEqual(m1.vanish, m2.appear)
     );
@@ -598,6 +599,7 @@ export class DynamoRules extends ChessRules {
 
   filterValid(moves) {
     const color = this.turn;
+    const La = this.amoves.length;
     if (this.subTurn == 1) {
       return moves.filter(m => {
         // A move is valid either if it doesn't result in a check,
@@ -605,15 +607,21 @@ export class DynamoRules extends ChessRules {
         // (not undoing a potential move + action of the opponent)
         this.play(m);
         let res = this.underCheck(color);
-        if (res) {
-          const moves2 = this.getAllPotentialMoves();
-          for (let m2 of moves2) {
-            this.play(m2);
-            const res2 = this.underCheck(color);
-            this.undo(m2);
-            if (!res2) {
-              res = false;
-              break;
+        if (this.subTurn == 2) {
+          let isOpposite = La > 0 && this.oppositeMoves(this.amoves[La-1], m);
+          if (res || isOpposite) {
+            const moves2 = this.getAllPotentialMoves();
+            for (let m2 of moves2) {
+              this.play(m2);
+              const res2 = this.underCheck(color);
+              const amove = this.getAmove(m, m2);
+              isOpposite =
+                La > 0 && this.oppositeMoves(this.amoves[La-1], amove);
+              this.undo(m2);
+              if (!res2 && !isOpposite) {
+                res = false;
+                break;
+              }
             }
           }
         }
@@ -621,9 +629,8 @@ export class DynamoRules extends ChessRules {
         return !res;
       });
     }
-    const Lf = this.firstMove.length;
-    const La = this.amoves.length;
     if (La == 0) return super.filterValid(moves);
+    const Lf = this.firstMove.length;
     return (
       super.filterValid(
         moves.filter(m => {
@@ -682,12 +689,37 @@ export class DynamoRules extends ChessRules {
     const pawnShift = (color == "w" ? 1 : -1);
     for (let i of [-1, 1]) {
       if (
-        y + i >= 0 &&
-        y + i < V.size.y &&
+        V.OnBoard(x + pawnShift, y + i) &&
+        this.board[x + pawnShift][y + i] != V.EMPTY &&
         this.getPiece(x + pawnShift, y + i) == V.PAWN &&
         this.getColor(x + pawnShift, y + i) == color
       ) {
-        return !V.OnBoard(x - pawnShift, y - i);
+        if (!V.OnBoard(x - pawnShift, y - i)) return true;
+      }
+    }
+    return false;
+  }
+
+  static OnTheEdge(x, y) {
+    return (x == 0 || x == 7 || y == 0 || y == 7);
+  }
+
+  isAttackedByKing([x, y], color) {
+    // Attacked if I'm on the edge and the opponent king just next,
+    // but not on the edge.
+    if (V.OnTheEdge(x, y)) {
+      for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
+        const [i, j] = [x + step[0], y + step[1]];
+        if (
+          V.OnBoard(i, j) &&
+          !V.OnTheEdge(i, j) &&
+          this.board[i][j] != V.EMPTY &&
+          this.getPiece(i, j) == V.KING
+          // NOTE: since only one king of each color, and (x, y) is occupied
+          // by our king, no need to check other king's color.
+        ) {
+          return true;
+        }
       }
     }
     return false;
@@ -709,53 +741,84 @@ export class DynamoRules extends ChessRules {
     return potentialMoves;
   }
 
-  getCurrentScore() {
-    if (this.subTurn == 2)
-      // Move not over
-      return "*";
-    return super.getCurrentScore();
+  getEmptyMove() {
+    return new Move({
+      start: { x: -1, y: -1 },
+      end: { x: -1, y: -1 },
+      appear: [],
+      vanish: []
+    });
   }
 
   doClick(square) {
     // A click to promote a piece on subTurn 2 would trigger this.
     // For now it would then return [NaN, NaN] because surrounding squares
     // have no IDs in the promotion modal. TODO: improve this?
-    if (!square[0]) return null;
-    // If subTurn == 2 && square is empty && !underCheck,
+    if (isNaN(square[0])) return null;
+    // If subTurn == 2 && square is empty && !underCheck && !isOpposite,
     // then return an empty move, allowing to "pass" subTurn2
+    const La = this.amoves.length;
+    const Lf = this.firstMove.length;
     if (
       this.subTurn == 2 &&
       this.board[square[0]][square[1]] == V.EMPTY &&
-      !this.underCheck(this.turn)
+      !this.underCheck(this.turn) &&
+      (La == 0 || !this.oppositeMoves(this.amoves[La-1], this.firstMove[Lf-1]))
     ) {
-      return {
-        start: { x: -1, y: -1 },
-        end: { x: -1, y: -1 },
-        appear: [],
-        vanish: []
-      };
+      return this.getEmptyMove();
     }
     return null;
   }
 
   play(move) {
-    move.flags = JSON.stringify(this.aggregateFlags());
-    V.PlayOnBoard(this.board, move);
-    if (this.subTurn == 2) {
+    if (this.subTurn == 1 && move.vanish.length == 0) {
+      // Patch to work with old format: (TODO: remove later)
+      move.ignore = true;
+      return;
+    }
+    const color = this.turn;
+    move.subTurn = this.subTurn; //for undo
+    const gotoNext = (mv) => {
       const L = this.firstMove.length;
-      this.amoves.push(this.getAmove(this.firstMove[L-1], move));
-      this.turn = V.GetOppCol(this.turn);
+      this.amoves.push(this.getAmove(this.firstMove[L-1], mv));
+      this.turn = V.GetOppCol(color);
+      this.subTurn = 1;
       this.movesCount++;
+    };
+    move.flags = JSON.stringify(this.aggregateFlags());
+    V.PlayOnBoard(this.board, move);
+    if (this.subTurn == 2) gotoNext(move);
+    else {
+      this.subTurn = 2;
+      this.firstMove.push(move);
+      this.toNewKingPos(move);
+      if (
+        // Condition is true on empty arrays:
+        this.getAllPotentialMoves().every(m => {
+          V.PlayOnBoard(this.board, m);
+          this.toNewKingPos(m);
+          const res = this.underCheck(color);
+          V.UndoOnBoard(this.board, m);
+          this.toOldKingPos(m);
+          return res;
+        })
+      ) {
+        // No valid move at subTurn 2
+        gotoNext(this.getEmptyMove());
+      }
+      this.toOldKingPos(move);
     }
-    else this.firstMove.push(move);
-    this.subTurn = 3 - this.subTurn;
     this.postPlay(move);
   }
 
-  postPlay(move) {
-    if (move.start.x < 0) return;
+  toNewKingPos(move) {
     for (let a of move.appear)
       if (a.p == V.KING) this.kingPos[a.c] = [a.x, a.y];
+  }
+
+  postPlay(move) {
+    if (move.start.x < 0) return;
+    this.toNewKingPos(move);
     this.updateCastleFlags(move);
   }
 
@@ -771,18 +834,20 @@ export class DynamoRules extends ChessRules {
   }
 
   undo(move) {
+    if (!!move.ignore) return; //TODO: remove that later
     this.disaggregateFlags(JSON.parse(move.flags));
     V.UndoOnBoard(this.board, move);
     if (this.subTurn == 1) {
+      this.amoves.pop();
       this.turn = V.GetOppCol(this.turn);
       this.movesCount--;
     }
-    else this.firstMove.pop();
-    this.subTurn = 3 - this.subTurn;
-    this.postUndo(move);
+    if (move.subTurn == 1) this.firstMove.pop();
+    this.subTurn = move.subTurn;
+    this.toOldKingPos(move);
   }
 
-  postUndo(move) {
+  toOldKingPos(move) {
     // (Potentially) Reset king position
     for (let v of move.vanish)
       if (v.p == V.KING) this.kingPos[v.c] = [v.x, v.y];
@@ -802,26 +867,29 @@ export class DynamoRules extends ChessRules {
     };
     moves.forEach(m => {
       this.play(m);
-      m.eval = (color == "w" ? -1 : 1) * maxeval;
-      const moves2 = this.getAllValidMoves().concat([emptyMove]);
-      m.next = moves2[0];
-      moves2.forEach(m2 => {
-        this.play(m2);
-        const score = this.getCurrentScore();
-        let mvEval = 0;
-        if (score != "1/2") {
-          if (score != "*") mvEval = (score == "1-0" ? 1 : -1) * maxeval;
-          else mvEval = this.evalPosition();
-        }
-        if (
-          (color == 'w' && mvEval > m.eval) ||
-          (color == 'b' && mvEval < m.eval)
-        ) {
-          m.eval = mvEval;
-          m.next = m2;
-        }
-        this.undo(m2);
-      });
+      if (this.turn != color) m.eval = this.evalPosition();
+      else {
+        m.eval = (color == "w" ? -1 : 1) * maxeval;
+        const moves2 = this.getAllValidMoves().concat([emptyMove]);
+        m.next = moves2[0];
+        moves2.forEach(m2 => {
+          this.play(m2);
+          const score = this.getCurrentScore();
+          let mvEval = 0;
+          if (score != "1/2") {
+            if (score != "*") mvEval = (score == "1-0" ? 1 : -1) * maxeval;
+            else mvEval = this.evalPosition();
+          }
+          if (
+            (color == 'w' && mvEval > m.eval) ||
+            (color == 'b' && mvEval < m.eval)
+          ) {
+            m.eval = mvEval;
+            m.next = m2;
+          }
+          this.undo(m2);
+        });
+      }
       this.undo(m);
     });
     moves.sort((a, b) => {
@@ -831,6 +899,7 @@ export class DynamoRules extends ChessRules {
     for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
       candidates.push(i);
     const mIdx = candidates[randInt(candidates.length)];
+    if (!moves[mIdx].next) return moves[mIdx];
     const move2 = moves[mIdx].next;
     delete moves[mIdx]["next"];
     return [moves[mIdx], move2];
@@ -847,4 +916,5 @@ export class DynamoRules extends ChessRules {
       return initialSquare + "R";
     return move.appear[0].p.toUpperCase() + initialSquare + finalSquare;
   }
+
 };