New variant idea
[xogo.git] / variants / Chakart / class.js
index eab2a36..3454d8f 100644 (file)
@@ -1,7 +1,7 @@
 import ChessRules from "/base_rules.js";
-import GiveawayRules from "/variants/Giveaway/class.js";
-import { ArrayFun } from "/utils/array.js";
-import { Random } from "/utils/alea.js";
+import {ArrayFun} from "/utils/array.js";
+import {Random} from "/utils/alea.js";
+import {FenUtil} from "/utils/setupPieces.js";
 import PiPo from "/utils/PiPo.js";
 import Move from "/utils/Move.js";
 
@@ -116,7 +116,6 @@ export default class ChakartRules extends ChessRules {
       {
         'y': {
           // Virtual piece for "king remote shell captures"
-          moves: [],
           attack: [
             {
               steps: [
@@ -127,18 +126,29 @@ export default class ChakartRules extends ChessRules {
           ]
         }
       },
-      specials, bowsered, super.pieces(color, x, y));
+      specials, bowsered, super.pieces(color, x, y)
+    );
+  }
+
+  isKing(x, y, p) {
+    if (!p)
+      p = this.getPiece(x, y);
+    return ['k', 'l'].includes(p);
   }
 
-  genRandInitFen(seed) {
-    const options = Object.assign({mode: "suicide"}, this.options);
-    const gr = new GiveawayRules({options: options, genFenOnly: true});
-    const baseFen = gr.genRandInitFen(seed);
-    const fenParts = baseFen.split(" ");
-    let others = JSON.parse(fenParts[3]);
-    delete others["enpassant"];
-    others["flags"] = "1111"; //Peach + Mario flags
-    return fenParts.slice(0, 3).join(" ") + " " + JSON.stringify(others);
+  genRandInitBaseFen() {
+    const s = FenUtil.setupPieces(
+      ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
+      {
+        randomness: this.options["randomness"],
+        diffCol: ['b']
+      }
+    );
+    return {
+      fen: s.b.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" +
+           s.w.join("").toUpperCase(),
+      o: {flags: "1111"} //Peach + Mario
+    };
   }
 
   fen2board(f) {
@@ -189,31 +199,24 @@ export default class ChakartRules extends ChessRules {
     this.reserve = {}; //to be filled later
   }
 
+  canStepOver(i, j) {
+    return (
+      this.board[i][j] == "" ||
+      ['i', V.EGG, V.MUSHROOM].includes(this.getPiece(i, j))
+    );
+  }
+
   // For Toadette bonus
-  getDropMovesFrom([c, p]) {
-    if (typeof c != "string" || this.reserve[c][p] == 0)
-      return [];
-    let moves = [];
-    const start = (c == 'w' && p == 'p' ? 1 : 0);
-    const end = (c == 'b' && p == 'p' ? 7 : 8);
-    for (let i = start; i < end; i++) {
-      for (let j = 0; j < this.size.y; j++) {
-        const pieceIJ = this.getPiece(i, j);
-        const colIJ = this.getColor(i, j);
-        if (this.board[i][j] == "" || colIJ == 'a' || pieceIJ == 'i') {
-          let m = new Move({
-            start: {x: c, y: p},
-            appear: [new PiPo({x: i, y: j, c: c, p: p})],
-            vanish: []
-          });
-          // A drop move may remove a bonus (or hidden queen!)
-          if (this.board[i][j] != "")
-            m.vanish.push(new PiPo({x: i, y: j, c: colIJ, p: pieceIJ}));
-          moves.push(m);
-        }
-      }
-    }
-    return moves;
+  canDrop([c, p], [i, j]) {
+    return (
+      (
+        this.board[i][j] == "" ||
+        this.getColor(i, j) == 'a' ||
+        this.getPiece(i, j) == 'i'
+      )
+      &&
+      (p != "p" || (c == 'w' && i < this.size.x - 1) || (c == 'b' && i > 0))
+    );
   }
 
   getPotentialMovesFrom([x, y]) {
@@ -223,7 +226,7 @@ export default class ChakartRules extends ChessRules {
       moves = this.getDropMovesFrom([x, y]);
     else if (this.egg == "kingboo") {
       const color = this.turn;
-      const oppCol = C.GetOppCol(color);
+      const oppCol = C.GetOppTurn(color);
       // Only allow to swap (non-immobilized!) pieces
       for (let i=0; i<this.size.x; i++) {
         for (let j=0; j<this.size.y; j++) {
@@ -276,23 +279,16 @@ export default class ChakartRules extends ChessRules {
         case 'b':
         case 'r':
           // Explicitely listing types to avoid moving immobilized piece
-          moves = this.getPotentialMovesOf(piece, [x, y]);
+          moves = super.getPotentialMovesOf(piece, [x, y]);
           break;
       }
     }
     return moves;
   }
 
-  canStepOver(i, j) {
-    return (
-      this.board[i][j] == "" ||
-      ['i', V.EGG, V.MUSHROOM].includes(this.getPiece(i, j))
-    );
-  }
-
   getPawnMovesFrom([x, y]) {
     const color = this.turn;
-    const oppCol = C.GetOppCol(color);
+    const oppCol = C.GetOppTurn(color);
     const shiftX = (color == 'w' ? -1 : 1);
     const firstRank = (color == "w" ? this.size.x - 1 : 0);
     let moves = [];
@@ -328,7 +324,7 @@ export default class ChakartRules extends ChessRules {
         moves.push(this.getBasicMove([x, y], [x + shiftX, nextY]));
       }
     }
-    this.pawnPostProcess(moves, color, oppCol);
+    moves = super.pawnPostProcess(moves, color, oppCol);
     // Add mushroom on before-last square (+ potential segments)
     moves.forEach(m => {
       let [mx, my] = [x, y];
@@ -355,14 +351,14 @@ export default class ChakartRules extends ChessRules {
 
   getKnightMovesFrom([x, y]) {
     // Add egg on initial square:
-    return this.getPotentialMovesOf('n', [x, y]).map(m => {
+    return super.getPotentialMovesOf('n', [x, y]).map(m => {
       m.appear.push(new PiPo({p: "e", c: "a", x: x, y: y}));
       return m;
     });
   }
 
   getQueenMovesFrom(sq) {
-    const normalMoves = this.getPotentialMovesOf('q', sq);
+    const normalMoves = super.getPotentialMovesOf('q', sq);
     // If flag allows it, add 'invisible movements'
     let invisibleMoves = [];
     if (this.powerFlags[this.turn]['q']) {
@@ -384,10 +380,10 @@ export default class ChakartRules extends ChessRules {
   }
 
   getKingMovesFrom([x, y]) {
-    let moves = this.getPotentialMovesOf('k', [x, y]);
+    let moves = super.getPotentialMovesOf('k', [x, y]);
     // If flag allows it, add 'remote shell captures'
     if (this.powerFlags[this.turn]['k']) {
-      let shellCaptures = this.getPotentialMovesOf('y', [x, y]);
+      let shellCaptures = super.getPotentialMovesOf('y', [x, y]);
       shellCaptures.forEach(sc => {
         sc.shell = true; //easier play()
         sc.choice = 'z'; //to display in showChoices()
@@ -402,26 +398,7 @@ export default class ChakartRules extends ChessRules {
 
   play(move) {
     const color = this.turn;
-    const oppCol = C.GetOppCol(color);
-    if (
-      move.appear.length > 0 &&
-      move.appear[0].p == 'p' &&
-      (
-        (color == 'w' && move.end.x == 0) ||
-        (color == 'b' && move.end.x == this.size.x - 1)
-      )
-    ) {
-      // "Forgotten" promotion, which occurred after some effect
-      let moves = [move];
-      super.pawnPostProcess(moves, color, oppCol);
-      super.showChoices(moves);
-      return false;
-    }
-    this.postPlay(move, color, oppCol);
-    return true;
-  }
-
-  postPlay(move, color, oppCol) {
+    const oppCol = C.GetOppTurn(color);
     this.egg = move.egg;
     if (move.egg == "toadette") {
       this.reserve = { w: {}, b: {} };
@@ -472,7 +449,11 @@ export default class ChakartRules extends ChessRules {
             this.getColor(i, j) == oppCol
           ) {
             const pieceIJ = this.getPiece(i, j);
-            if (pieceIJ == 'i') {
+            if (
+              pieceIJ == 'i' &&
+              // Ensure that current move doesn't erase invisible queen
+              move.appear.every(a => a.x != i || a.y != j)
+            ) {
               move.vanish.push(new PiPo({x: i, y: j, c: oppCol, p: 'i'}));
               move.appear.push(new PiPo({x: i, y: j, c: oppCol, p: 'q'}));
             }
@@ -492,7 +473,27 @@ export default class ChakartRules extends ChessRules {
       this.displayBonus(move);
   }
 
+  buildMoveStack(move, r) {
+    const color = this.turn;
+    if (
+      move.appear.length > 0 &&
+      move.appear[0].p == 'p' &&
+      (
+        (color == 'w' && move.end.x == 0) ||
+        (color == 'b' && move.end.x == this.size.x - 1)
+      )
+    ) {
+      // "Forgotten" promotion, which occurred after some effect
+      let moves = super.pawnPostProcess([move], color, C.GetOppTurn(color));
+      super.showChoices(moves, r);
+    }
+    else
+      super.buildMoveStack(move, r);
+  }
+
   computeNextMove(move) {
+    if (move.koopa)
+      return null;
     // Set potential random effects, so that play() is deterministic
     // from opponent viewpoint:
     const endPiece = this.getPiece(move.end.x, move.end.y);
@@ -571,8 +572,17 @@ export default class ChakartRules extends ChessRules {
       let bagOfPieces = [];
       for (let i=0; i<this.size.x; i++) {
         for (let j=0; j<this.size.y; j++) {
-          if (this.getColor(i, j) == c && this.getPiece(i, j) != 'k')
+          const pieceIJ = this.getPiece(i, j);
+          if (
+            this.getColor(i, j) == c && pieceIJ != 'k' &&
+            (
+              // The color will change, so pawns on first rank are ineligible
+              pieceIJ != 'p' ||
+              (c == 'w' && i < this.size.x - 1) || (c == 'b' && i > 0)
+            )
+          ) {
             bagOfPieces.push([i, j]);
+          }
         }
       }
       if (bagOfPieces.length >= 1)
@@ -585,11 +595,15 @@ export default class ChakartRules extends ChessRules {
       case "luigi":
       case "waluigi":
         // Change color of friendly or enemy piece, king excepted
-        const oldColor = (move.egg == "waluigi" ? color : C.GetOppCol(color));
-        const newColor = C.GetOppCol(oldColor);
+        const oldColor = (move.egg == "waluigi" ? color : C.GetOppTurn(color));
+        const newColor = C.GetOppTurn(oldColor);
         const coords = getRandomPiece(oldColor);
         if (coords) {
           const piece = this.getPiece(coords[0], coords[1]);
+          if (coords[0] == move.start.x && coords[1] == move.start.y) {
+            // Moving piece change color: fix coords
+            coords = [move.end.x, move.end.y];
+          }
           em = new Move({
             appear: [
               new PiPo({x: coords[0], y: coords[1], c: newColor, p: piece})
@@ -622,19 +636,25 @@ export default class ChakartRules extends ChessRules {
         });
         break;
       case "koopa":
-        // Reverse move
+        // Reverse move, if possible
         em = new Move({
-          appear: [
-            new PiPo({
-              x: move.start.x, y: move.start.y, c: color, p: move.appear[0].p
-            })
-          ],
+          appear: [],
           vanish: [
             new PiPo({
               x: move.end.x, y: move.end.y, c: color, p: move.appear[0].p
             })
-          ]
+          ],
+          end: {x: move.start.x, y: move.start.y} //may be irrelevant
         });
+        em.koopa = true; //avoid applying effect
+        if (move.vanish.length == 0)
+          // After toadette+drop, just erase piece
+          break;
+        em.appear.push(
+          new PiPo({
+            x: move.start.x, y: move.start.y, c: color, p: move.appear[0].p
+          })
+        );
         if (this.board[move.start.x][move.start.y] != "") {
           // Pawn or knight let something on init square
           em.vanish.push(new PiPo({
@@ -702,12 +722,7 @@ export default class ChakartRules extends ChessRules {
   }
 
   displayBonus(move) {
-    let divBonus = document.createElement("div");
-    divBonus.classList.add("bonus-text");
-    divBonus.innerHTML = move.egg;
-    let container = document.getElementById(this.containerId);
-    container.appendChild(divBonus);
-    setTimeout(() => container.removeChild(divBonus), 2000);
+    super.displayMessage(null, move.egg, "bonus-text", 2000);
   }
 
   atLeastOneMove() {