Fix (a lot but maybe not all of) Chakart
authorBenjamin Auder <benjamin.auder@somewhere>
Sun, 19 Jun 2022 22:04:54 +0000 (00:04 +0200)
committerBenjamin Auder <benjamin.auder@somewhere>
Sun, 19 Jun 2022 22:04:54 +0000 (00:04 +0200)
TODO
base_rules.js
pieces/chakart_shell.svg [new file with mode: 0644]
utils/alea.js
variants/Chakart/CREDITS [new file with mode: 0644]
variants/Chakart/class.js
variants/Chakart/style.css

diff --git a/TODO b/TODO
index 0545a54..a17d5c3 100644 (file)
--- a/TODO
+++ b/TODO
@@ -1,5 +1,4 @@
-add variants : Chakart first (dark,cylinder)
-Dark Racing Kings ?
+add variants : Dark Racing Kings ?
 Checkered-Teleport ?
 
 Otage, Emergo, Pacosako : fonction "buildPiece(arg1, arg2)" returns HTML element with 2 SVG or SVG + number
 Checkered-Teleport ?
 
 Otage, Emergo, Pacosako : fonction "buildPiece(arg1, arg2)" returns HTML element with 2 SVG or SVG + number
index 080b02a..8ad0894 100644 (file)
@@ -534,6 +534,22 @@ export default class ChessRules {
     return `${this.containerId}|rnum-${color}${piece}`;
   }
 
     return `${this.containerId}|rnum-${color}${piece}`;
   }
 
+  static AddClass_es(piece, class_es) {
+    if (!Array.isArray(class_es))
+      class_es = [class_es];
+    class_es.forEach(cl => {
+      piece.classList.add(cl);
+    });
+  }
+
+  static RemoveClass_es(piece, class_es) {
+    if (!Array.isArray(class_es))
+      class_es = [class_es];
+    class_es.forEach(cl => {
+      piece.classList.remove(cl);
+    });
+  }
+
   graphicalInit() {
     // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
     window.onresize = () => this.re_drawBoardElements();
   graphicalInit() {
     // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
     window.onresize = () => this.re_drawBoardElements();
@@ -649,7 +665,7 @@ export default class ChessRules {
           const color = this.getColor(i, j);
           const piece = this.getPiece(i, j);
           this.g_pieces[i][j] = document.createElement("piece");
           const color = this.getColor(i, j);
           const piece = this.getPiece(i, j);
           this.g_pieces[i][j] = document.createElement("piece");
-          this.g_pieces[i][j].classList.add(this.pieces()[piece]["class"]);
+          C.AddClass_es(this.g_pieces[i][j], this.pieces()[piece]["class"]);
           this.g_pieces[i][j].classList.add(C.GetColorClass(color));
           this.g_pieces[i][j].style.width = pieceWidth + "px";
           this.g_pieces[i][j].style.height = pieceWidth + "px";
           this.g_pieces[i][j].classList.add(C.GetColorClass(color));
           this.g_pieces[i][j].style.width = pieceWidth + "px";
           this.g_pieces[i][j].style.height = pieceWidth + "px";
@@ -717,8 +733,7 @@ export default class ChessRules {
         r_cell.style.height = sqResSize + "px";
         rcontainer.appendChild(r_cell);
         let piece = document.createElement("piece");
         r_cell.style.height = sqResSize + "px";
         rcontainer.appendChild(r_cell);
         let piece = document.createElement("piece");
-        const pieceSpec = this.pieces()[p];
-        piece.classList.add(pieceSpec["class"]);
+        C.AddClass_es(piece, this.pieces()[p]["class"]);
         piece.classList.add(C.GetColorClass(c));
         piece.style.width = "100%";
         piece.style.height = "100%";
         piece.classList.add(C.GetColorClass(c));
         piece.style.width = "100%";
         piece.style.height = "100%";
@@ -1017,8 +1032,8 @@ export default class ChessRules {
       choice.style.backgroundColor = "lightyellow";
       choice.onclick = () => callback(moves[i]);
       const piece = document.createElement("piece");
       choice.style.backgroundColor = "lightyellow";
       choice.onclick = () => callback(moves[i]);
       const piece = document.createElement("piece");
-      const pieceSpec = this.pieces()[moves[i].appear[0].p];
-      piece.classList.add(pieceSpec["class"]);
+      const cdisp = moves[i].choice || moves[i].appear[0].p;
+      C.AddClass_es(piece, this.pieces()[cdisp]["class"]);
       piece.classList.add(C.GetColorClass(color));
       piece.style.width = "100%";
       piece.style.height = "100%";
       piece.classList.add(C.GetColorClass(color));
       piece.style.width = "100%";
       piece.style.height = "100%";
@@ -1485,6 +1500,11 @@ export default class ChessRules {
     return false;
   }
 
     return false;
   }
 
+  canStepOver(i, j) {
+    // In some variants, objects on boards don't stop movement (Chakart)
+    return this.board[i][j] == "";
+  }
+
   // Generic method to find possible moves of "sliding or jumping" pieces
   getPotentialMovesOf(piece, [x, y]) {
     const color = this.getColor(x, y);
   // Generic method to find possible moves of "sliding or jumping" pieces
   getPotentialMovesOf(piece, [x, y]) {
     const color = this.getColor(x, y);
@@ -1513,7 +1533,7 @@ export default class ChessRules {
           let stepCounter = 0;
           while (
             this.onBoard(i, j) &&
           let stepCounter = 0;
           while (
             this.onBoard(i, j) &&
-            (this.board[i][j] == "" || (i == x && j == y))
+            (this.canStepOver(i, j) || (i == x && j == y))
           ) {
             if (
               type != "attack" &&
           ) {
             if (
               type != "attack" &&
@@ -2164,7 +2184,7 @@ export default class ChessRules {
     const pieceWidth = this.getPieceWidth(r.width);
     move.appear.forEach(a => {
       this.g_pieces[a.x][a.y] = document.createElement("piece");
     const pieceWidth = this.getPieceWidth(r.width);
     move.appear.forEach(a => {
       this.g_pieces[a.x][a.y] = document.createElement("piece");
-      this.g_pieces[a.x][a.y].classList.add(this.pieces()[a.p]["class"]);
+      C.AddClass_es(this.g_pieces[a.x][a.y], this.pieces()[a.p]["class"]);
       this.g_pieces[a.x][a.y].classList.add(C.GetColorClass(a.c));
       this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
       this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
       this.g_pieces[a.x][a.y].classList.add(C.GetColorClass(a.c));
       this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
       this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
@@ -2217,8 +2237,8 @@ export default class ChessRules {
     const pieces = this.pieces();
     if (move.drag) {
       const startCode = this.getPiece(move.start.x, move.start.y);
     const pieces = this.pieces();
     if (move.drag) {
       const startCode = this.getPiece(move.start.x, move.start.y);
-      movingPiece.classList.remove(pieces[startCode]["class"]);
-      movingPiece.classList.add(pieces[move.drag.p]["class"]);
+      C.RemoveClass_es(movingPiece, pieces[startCode]["class"]);
+      C.AddClass_es(movingPiece, pieces[move.drag.p]["class"]);
       const apparentColor = this.getColor(move.start.x, move.start.y);
       if (apparentColor != move.drag.c) {
         movingPiece.classList.remove(C.GetColorClass(apparentColor));
       const apparentColor = this.getColor(move.start.x, move.start.y);
       if (apparentColor != move.drag.c) {
         movingPiece.classList.remove(C.GetColorClass(apparentColor));
diff --git a/pieces/chakart_shell.svg b/pieces/chakart_shell.svg
new file mode 100644 (file)
index 0000000..7125eac
--- /dev/null
@@ -0,0 +1 @@
+<svg width="512px" height="512px" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path fill="#000" d="M329.125 20.5l-3.72 9.625c-7.204 18.77-32.286 34.72-63.624 34.72-31.538 0-56.586-16.223-63.624-35.22l-2.25-6.094h-8.687l-1.97.97C111.456 61.1 60.844 148.48 60.844 249.313c0 132.906 89.104 242.78 200.937 242.78 111.835 0 200.283-109.904 200.283-242.78 0-100.493-50.352-187.376-123.72-224.188l-9.218-4.625zM185.28 45.78c13.738 23.13 43.113 37.782 76.5 37.782 33.14 0 62.43-14.33 76.345-37.187 61.527 35.396 105.25 112.692 105.25 202.938 0 124.622-82.108 224.093-181.594 224.093-99.485 0-182.217-99.5-182.217-224.094 0-90.54 43.907-168.274 105.718-203.53zm-4.78 27.75c-11.36 8.202-21.867 18.068-31.28 29.376l60.374 78.844h102.311l60.375-78.875c-9.063-10.883-19.12-20.456-30-28.47-18.174 18.622-47.482 30.72-80.5 30.72-33.52 0-63.174-12.487-81.28-31.594zm-42.906 44.907c-23.987 35.515-38.47 81.505-38.47 131.782 0 2.038.047 4.068.095 6.093h53.436L196 194.75l-58.406-76.313zm246.312 0L325.5 194.75l43.344 61.563h53.47c.046-2.025.092-4.055.092-6.094 0-50.28-14.51-96.267-38.5-131.782zm-169.062 82l-44.22 62.813 44.22 62.844h91.812l44.22-62.844-44.22-62.813h-91.812zM100.344 275c4.55 47.216 21.928 89.423 47.625 120.97l48.53-63.44L156.03 275h-55.686zm265.125 0L325 332.53l48.563 63.44c25.696-31.547 43.075-73.754 47.625-120.97h-55.72zm-154.783 69.78l-50 65.314c27.524 27.363 62.274 43.687 100.063 43.687 37.79 0 72.57-16.323 100.094-43.686l-50-65.313H210.688z"/></svg>
\ No newline at end of file
index aa3aa57..751d347 100644 (file)
@@ -34,7 +34,8 @@ export const Random = {
       const rand = Random.randInt(index, arr.length);
       [ cpArr[index], cpArr[rand] ] = [ cpArr[rand], cpArr[index] ];
     }
       const rand = Random.randInt(index, arr.length);
       [ cpArr[index], cpArr[rand] ] = [ cpArr[rand], cpArr[index] ];
     }
-    return cpArr.slice(0, n);
+    const res = cpArr.slice(0, n);
+    return (n >= 2 ? res : res[0]);
   },
 
   shuffle: function(arr) {
   },
 
   shuffle: function(arr) {
diff --git a/variants/Chakart/CREDITS b/variants/Chakart/CREDITS
new file mode 100644 (file)
index 0000000..e15c948
--- /dev/null
@@ -0,0 +1,7 @@
+Images:
+
+https://fr.m.wikiversity.org/wiki/Fichier:Tango_Style_Mushroom_icon.svg
+https://commons.wikimedia.org/wiki/File:Tux_Paint_banana.svg
+https://www.onlinewebfonts.com/icon/425540
+https://www.svgrepo.com/svg/264673/easter-egg-easter
+https://www.svgrepo.com/svg/321648/turtle-shell
index cee0242..a9b1908 100644 (file)
@@ -20,7 +20,8 @@ export default class ChakartRules extends ChessRules {
             {label: "Asymmetric random", value: 2}
           ]
         }
             {label: "Asymmetric random", value: 2}
           ]
         }
-      ]
+      ],
+      styles: ["cylinder"]
     };
   }
 
     };
   }
 
@@ -87,15 +88,34 @@ export default class ChakartRules extends ChessRules {
       "luigi", "waluigi", "toadette", "chomp"];
   }
 
       "luigi", "waluigi", "toadette", "chomp"];
   }
 
+  canIplay(x, y) {
+    if (
+      this.playerColor != this.turn ||
+      Object.keys(V.IMMOBILIZE_DECODE).includes(this.getPiece(x, y))
+    ) {
+      return false;
+    }
+    return this.egg == "kingboo" || this.getColor(x, y) == this.turn;
+  }
+
   pieces(color, x, y) {
   pieces(color, x, y) {
-    let specials = {
+    const specials = {
       'i': {"class": "invisible"}, //queen
       'e': {"class": "egg"},
       'm': {"class": "mushroom"},
       'd': {"class": "banana"},
       'i': {"class": "invisible"}, //queen
       'e': {"class": "egg"},
       'm': {"class": "mushroom"},
       'd': {"class": "banana"},
-      'w': {"class": "bomb"}
+      'w': {"class": "bomb"},
+      'z': {"class": "remote-capture"}
     };
     };
-    return Object.assign(specials, super.pieces(color, x, y));
+    const bowsered = {
+      's': {"class": ["immobilized", "pawn"]},
+      'u': {"class": ["immobilized", "rook"]},
+      'o': {"class": ["immobilized", "knight"]},
+      'c': {"class": ["immobilized", "bishop"]},
+      't': {"class": ["immobilized", "queen"]},
+      'l': {"class": ["immobilized", "king"]}
+    };
+    return Object.assign({}, specials, bowsered, super.pieces(color, x, y));
   }
 
   genRandInitFen(seed) {
   }
 
   genRandInitFen(seed) {
@@ -146,6 +166,9 @@ export default class ChakartRules extends ChessRules {
     this.reserve = {}; //to be filled later
     this.egg = null;
     this.moveStack = [];
     this.reserve = {}; //to be filled later
     this.egg = null;
     this.moveStack = [];
+    // Change seed (after FEN generation!!)
+    // so that further calls differ between players:
+    Random.setSeed(Math.floor(10000 * Math.random()));
   }
 
   // For Toadette bonus
   }
 
   // For Toadette bonus
@@ -154,24 +177,24 @@ export default class ChakartRules extends ChessRules {
       return [];
     let moves = [];
     const start = (c == 'w' && p == 'p' ? 1 : 0);
       return [];
     let moves = [];
     const start = (c == 'w' && p == 'p' ? 1 : 0);
-    const end = (color == 'b' && p == 'p' ? 7 : 8);
+    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);
     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] == "" ||
         if (
           this.board[i][j] == "" ||
-          this.getColor(i, j) == 'a' ||
+          colIJ == 'a' ||
           pieceIJ == V.INVISIBLE_QUEEN
         ) {
           let m = new Move({
             start: {x: c, y: p},
           pieceIJ == V.INVISIBLE_QUEEN
         ) {
           let m = new Move({
             start: {x: c, y: p},
-            end: {x: i, y: j},
             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] != "")
             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: 'a', p: pieceIJ}));
+            m.vanish.push(new PiPo({x: i, y: j, c: colIJ, p: pieceIJ}));
           moves.push(m);
         }
       }
           moves.push(m);
         }
       }
@@ -181,13 +204,13 @@ export default class ChakartRules extends ChessRules {
 
   getPotentialMovesFrom([x, y]) {
     let moves = [];
 
   getPotentialMovesFrom([x, y]) {
     let moves = [];
+    const piece = this.getPiece(x, y);
     if (this.egg == "toadette")
       moves = this.getDropMovesFrom([x, y]);
     else if (this.egg == "kingboo") {
     if (this.egg == "toadette")
       moves = this.getDropMovesFrom([x, y]);
     else if (this.egg == "kingboo") {
-      const initPiece = this.getPiece(x, y);
-      const color = this.getColor(x, y);
+      const color = this.turn;
       const oppCol = C.GetOppCol(color);
       const oppCol = C.GetOppCol(color);
-      // Only allow to swap pieces
+      // 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++) {
           const colIJ = this.getColor(i, j);
       for (let i=0; i<this.size.x; i++) {
         for (let j=0; j<this.size.y; j++) {
           const colIJ = this.getColor(i, j);
@@ -195,9 +218,10 @@ export default class ChakartRules extends ChessRules {
           if (
             (i != x || j != y) &&
             ['w', 'b'].includes(colIJ) &&
           if (
             (i != x || j != y) &&
             ['w', 'b'].includes(colIJ) &&
+            !Object.keys(V.IMMOBILIZE_DECODE).includes(pieceIJ) &&
             // Next conditions = no pawn on last rank
             (
             // Next conditions = no pawn on last rank
             (
-              initPiece != 'p' ||
+              piece != 'p' ||
               (
                 (color != 'w' || i != 0) &&
                 (color != 'b' || i != this.size.x - 1)
               (
                 (color != 'w' || i != 0) &&
                 (color != 'b' || i != this.size.x - 1)
@@ -213,8 +237,8 @@ export default class ChakartRules extends ChessRules {
             )
           ) {
             let m = this.getBasicMove([x, y], [i, j]);
             )
           ) {
             let m = this.getBasicMove([x, y], [i, j]);
-            m.appear.push(
-              new PiPo({x: x, y: y, p: this.getPiece(i, j), c: oppCol}));
+            m.appear.push(new PiPo({x: x, y: y, p: pieceIJ, c: colIJ}));
+            m.kingboo = true; //avoid some side effects (bananas/bombs)
             moves.push(m);
           }
         }
             moves.push(m);
           }
         }
@@ -222,7 +246,6 @@ export default class ChakartRules extends ChessRules {
     }
     else {
       // Normal case (including bonus daisy)
     }
     else {
       // Normal case (including bonus daisy)
-      const piece = this.getPiece(x, y);
       switch (piece) {
         case 'p':
           moves = this.getPawnMovesFrom([x, y]); //apply promotions
       switch (piece) {
         case 'p':
           moves = this.getPawnMovesFrom([x, y]); //apply promotions
@@ -238,166 +261,18 @@ export default class ChakartRules extends ChessRules {
           break;
         case 'b':
         case 'r':
           break;
         case 'b':
         case 'r':
-          // explicitely listing types to avoid moving immobilized piece
-          moves = this.getRookOrBishopMovesFrom([x, y], piece);
+          // Explicitely listing types to avoid moving immobilized piece
+          moves = super.getPotentialMovesOf(piece, [x, y]);
           break;
       }
     }
           break;
       }
     }
-    // Set potential random effects, so that play() is deterministic
-    moves.forEach(m => {
-      switch (this.getPiece(m.end.x, m.end.y)) {
-        case V.EGG:
-          m.egg = Random.sample(V.EGG_SURPRISE);
-          m.next = this.getEggEffect(m);
-          break;
-        case V.BANANA:
-          m.next = this.getRandomSquare(
-            [m.end.x, m.end.y], [[1, 1], [1, -1], [-1, 1], [-1, -1]]);
-          break;
-        case V.BOMB:
-          m.next = this.getRandomSquare(
-            [m.end.x, m.end.y], [[1, 0], [-1, 0], [0, 1], [0, -1]]);
-          break;
-      }
-    });
     return moves;
   }
 
     return moves;
   }
 
-  getEggEffect(move) {
-    const getRandomPiece = (c) => {
-      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')
-            bagOfPieces.push([i, j]);
-        }
-      }
-      if (bagOfPieces.length >= 1)
-        return Random.sample(bagOfPieces);
-      return null;
-    };
-    const color = this.turn;
-    let em = null;
-    switch (move.egg) {
-      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 coords = getRandomPiece(oldColor);
-        if (coords) {
-          const piece = this.getPiece(coords[0], coords[1]);
-          em = new Move({
-            appear: [
-              new PiPo({x: coords[0], y: coords[1], c: newColor, p: piece})
-            ],
-            vanish: [
-              new PiPo({x: coords[0], y: coords[1], c: oldColor, p: piece})
-            ]
-          });
-        }
-        break;
-      case "bowser":
-        em = new Move({
-          appear: [
-            new PiPo({
-              x: move.end.x,
-              y: move.end.y,
-              c: color,
-              p: V.IMMOBILIZED_CODE[move.appear[0].p]
-            })
-          ],
-          vanish: [
-            new PiPo({
-              x: move.end.x,
-              y: move.end.y,
-              c: color,
-              p: move.appear[0].p
-            })
-          ]
-        });
-        break;
-      case "koopa":
-        // Reverse move
-        em = new Move({
-          appear: [
-            new PiPo({
-              x: move.start.x, y: move.start.y, c: color, p: move.appear[0].p
-            })
-          ],
-          vanish: [
-            new PiPo({
-              x: move.end.x, y: move.end.y, c: color, p: move.appear[0].p
-            })
-          ]
-        });
-        break;
-      case "chomp":
-        // Eat piece
-        em = new Move({
-          appear: [],
-          vanish: [
-            new PiPo({
-              x: move.end.x, y: move.end.y, c: color, p: move.appear[0].p
-            })
-          ],
-          end: {x: move.end.x, y: move.end.y}
-        });
-        break;
-    }
-    return em;
-  }
-
-  // Helper to set and apply banana/bomb effect
-  getRandomSquare([x, y], steps, freeSquare) {
-    let validSteps = steps.filter(s => this.onBoard(x + s[0], y + s[1]));
-    if (freeSquare) {
-      // Square to put banana/bomb cannot be occupied by a piece
-      validSteps = validSteps.filter(s => {
-        return ["", 'a'].includes(this.getColor(x + s[0], y + s[1]))
-      });
-    }
-    if (validSteps.length == 0)
-      return null;
-    const step = validSteps[Random.randInt(validSteps.length)];
-    return [x + step[0], y + step[1]];
-  }
-
-  getPotentialMovesOf(piece, [x, y]) {
-    const color = this.getColor(x, y);
-    const stepSpec = this.pieces(color, x, y)[piece];
-    let moves = [];
-    const findAddMoves = (type, stepArray) => {
-      for (let s of stepArray) {
-        outerLoop: for (let step of s.steps) {
-          let [i, j] = [x + step[0], y + step[1]];
-          let stepCounter = 1;
-          while (
-            this.onBoard(i, j) &&
-            (
-              this.board[i][j] == "" ||
-              [V.MUSHROOM, V.EGG].includes(this.getPiece(i, j))
-            )
-          ) {
-            if (type != "attack")
-              moves.push(this.getBasicMove([x, y], [i, j]));
-            if (s.range <= stepCounter++)
-              continue outerLoop;
-            [i, j] = [i + step[0], j + step[1]];
-          }
-          if (!this.onBoard(i, j))
-            continue;
-          const pieceIJ = this.getPiece(i, j);
-          if (type != "moveonly" && this.getColor(i, j) != color)
-            moves.push(this.getBasicMove([x, y], [i, j]));
-        }
-      }
-    };
-    const specialAttack = !!stepSpec.attack;
-    if (specialAttack)
-      findAddMoves("attack", stepSpec.attack);
-    findAddMoves(specialAttack ? "moveonly" : "all", stepSpec.moves);
-    return moves;
+  canStepOver(i, j) {
+    return (
+      this.board[i][j] == "" ||
+      [V.MUSHROOM, V.EGG].includes(this.getPiece(i, j)));
   }
 
   getPawnMovesFrom([x, y]) {
   }
 
   getPawnMovesFrom([x, y]) {
@@ -436,44 +311,23 @@ export default class ChakartRules extends ChessRules {
       }
     }
     this.pawnPostProcess(moves, color, oppCol);
       }
     }
     this.pawnPostProcess(moves, color, oppCol);
-    // Add mushroom on initial square
+    // Add mushroom on before-last square
     moves.forEach(m => {
     moves.forEach(m => {
-      m.appear.push(new PiPo({x: m.start.x, y: m.start.y, c: 'a', p: 'm'}));
-    });
-    return moves;
-  }
-
-  getRookOrBishopMovesFrom([x, y], type) {
-    // Add banana if possible, diagonaly
-    return this.getPotentialMovesOf(type, [x, y]).map(m => {
-      const bs =
-        this.getRandomSquare([m.end.x, m.end.y],
-          type == 'r'
-            ? [[1, 1], [1, -1], [-1, 1], [-1, -1]]
-            : [[1, 0], [-1, 0], [0, 1], [0, -1]],
-          "freeSquare");
-      if (bs) {
-        m.appear.push(
-          new PiPo({
-            x: bs[0],
-            y: bs[1],
-            c: 'a',
-            p: type == 'r' ? 'd' : 'w'
-          })
-        );
-        if (this.board[bs[0]][bs[1]] != "") {
-          m.vanish.push(
-            new PiPo({
-              x: bs[0],
-              y: bs[1],
-              c: this.getColor(bs[0], bs[1]),
-              p: this.getPiece(bs[0], bs[1])
-            })
-          );
-        }
+      let revStep = [m.start.x - m.end.x, m.start.y - m.end.y];
+      for (let i of [0, 1])
+        revStep[i] = revStep[i] / Math.abs(revStep[i]) || 0;
+      const [blx, bly] = [m.end.x + revStep[0], m.end.y + revStep[1]];
+      m.appear.push(new PiPo({x: blx, y: bly, c: 'a', p: 'm'}));
+      if (blx != x && this.board[blx][bly] != "") {
+        m.vanish.push(new PiPo({
+          x: blx,
+          y: bly,
+          c: this.getColor(blx, bly),
+          p: this.getPiece(blx, bly)
+        }));
       }
       }
-      return m;
     });
     });
+    return moves;
   }
 
   getKnightMovesFrom([x, y]) {
   }
 
   getKnightMovesFrom([x, y]) {
@@ -539,6 +393,7 @@ export default class ChakartRules extends ChessRules {
               ]
             });
             shellCapture.shell = true; //easier play()
               ]
             });
             shellCapture.shell = true; //easier play()
+            shellCapture.choice = 'z'; //to display in showChoices()
             moves.push(shellCapture);
           }
         }
             moves.push(shellCapture);
           }
         }
@@ -548,49 +403,114 @@ export default class ChakartRules extends ChessRules {
   }
 
   play(move) {
   }
 
   play(move) {
+    if (!move.nextComputed) {
+      // Set potential random effects, so that play() is deterministic
+      // from opponent viewpoint:
+      const endPiece = this.getPiece(move.end.x, move.end.y);
+      switch (endPiece) {
+        case V.EGG:
+          move.egg = Random.sample(V.EGG_SURPRISE);
+          move.next = this.getEggEffect(move);
+          break;
+        case V.MUSHROOM:
+          move.next = this.getMushroomEffect(move);
+          break;
+        case V.BANANA:
+        case V.BOMB:
+          move.next = this.getBombBananaEffect(move, endPiece);
+          break;
+      }
+      if (!move.next && move.appear.length > 0 && !move.kingboo) {
+        const movingPiece = move.appear[0].p;
+        if (['b', 'r'].includes(movingPiece)) {
+          // Drop a banana or bomb:
+          const bs =
+            this.getRandomSquare([move.end.x, move.end.y],
+              movingPiece == 'r'
+                ? [[1, 1], [1, -1], [-1, 1], [-1, -1]]
+                : [[1, 0], [-1, 0], [0, 1], [0, -1]],
+              "freeSquare");
+          if (bs) {
+            move.appear.push(
+              new PiPo({
+                x: bs[0],
+                y: bs[1],
+                c: 'a',
+                p: movingPiece == 'r' ? 'd' : 'w'
+              })
+            );
+            if (this.board[bs[0]][bs[1]] != "") {
+              move.vanish.push(
+                new PiPo({
+                  x: bs[0],
+                  y: bs[1],
+                  c: this.getColor(bs[0], bs[1]),
+                  p: this.getPiece(bs[0], bs[1])
+                })
+              );
+            }
+          }
+        }
+      }
+      move.nextComputed = true;
+    }
     this.egg = move.egg;
     const color = this.turn;
     this.egg = move.egg;
     const color = this.turn;
+    const oppCol = C.GetOppCol(color);
     if (move.egg == "toadette") {
       this.reserve = { w: {}, b: {} };
       // Randomly select a piece in pawnPromotions
     if (move.egg == "toadette") {
       this.reserve = { w: {}, b: {} };
       // Randomly select a piece in pawnPromotions
-      this.reserve[color][Random.sample(this.pawnPromotions)] = 1;
+      if (!move.toadette)
+        move.toadette = Random.sample(this.pawnPromotions);
+      this.reserve[color][move.toadette] = 1;
       this.re_drawReserve([color]);
     }
     else if (Object.keys(this.reserve).length > 0) {
       this.reserve = {};
       this.re_drawReserve([color]);
     }
       this.re_drawReserve([color]);
     }
     else if (Object.keys(this.reserve).length > 0) {
       this.reserve = {};
       this.re_drawReserve([color]);
     }
-    if (this.getPiece(move.end.x, move.end.y) == V.MUSHROOM)
-      move.next = this.getMushroomEffect(move);
     if (move.shell)
       this.powerFlags[color]['k'] = false;
     if (move.shell)
       this.powerFlags[color]['k'] = false;
-    else if (move.appear.length > 0 && move.appear[0].p == V.INVISIBLE_QUEEN)
+    else if (move.appear.length > 0 && move.appear[0].p == V.INVISIBLE_QUEEN) {
       this.powerFlags[move.appear[0].c]['q'] = false;
       this.powerFlags[move.appear[0].c]['q'] = false;
-    this.playOnBoard(move);
-    // Look for an immobilized piece of my color: it can now move
-    for (let i=0; i<8; i++) {
-      for (let j=0; j<8; j++) {
-        if ((i != move.end.x || j != move.end.y) && this.board[i][j] != "") {
-          const piece = this.getPiece(i, j);
-          if (
-            this.getColor(i, j) == color &&
-            Object.keys(V.IMMOBILIZE_DECODE).includes(piece)
-          ) {
-            this.board[i][j] = color + V.IMMOBILIZE_DECODE[piece];
+      if (color != this.playerColor)
+        alert("Invisible queen!");
+    }
+    if (color == this.playerColor) {
+      // Look for an immobilized piece of my color: it can now move
+      for (let i=0; i<8; i++) {
+        for (let j=0; j<8; j++) {
+          if ((i != move.end.x || j != move.end.y) && this.board[i][j] != "") {
+            const piece = this.getPiece(i, j);
+            if (
+              this.getColor(i, j) == color &&
+              Object.keys(V.IMMOBILIZE_DECODE).includes(piece)
+            ) {
+              move.vanish.push(new PiPo({
+                x: i, y: j, c: color, p: piece
+              }));
+              move.appear.push(new PiPo({
+                x: i, y: j, c: color, p: V.IMMOBILIZE_DECODE[piece]
+              }));
+            }
           }
         }
       }
           }
         }
       }
-    }
-    // Also make opponent invisible queen visible again, if any
-    const oppCol = C.GetOppCol(color);
-    for (let i=0; i<8; i++) {
-      for (let j=0; j<8; j++) {
-        if (
-          this.board[i][j] != "" &&
-          this.getColor(i, j) == oppCol &&
-          this.getPiece(i, j) == V.INVISIBLE_QUEEN
-        ) {
-          this.board[i][j] = oppCol + V.QUEEN;
+      // Also make opponent invisible queen visible again, if any
+      for (let i=0; i<8; i++) {
+        for (let j=0; j<8; j++) {
+          if (
+            this.board[i][j] != "" &&
+            this.getColor(i, j) == oppCol &&
+            this.getPiece(i, j) == V.INVISIBLE_QUEEN
+          ) {
+            move.vanish.push(new PiPo({
+              x: i, y: j, c: oppCol, p: V.INVISIBLE_QUEEN
+            }));
+            move.appear.push(new PiPo({
+              x: i, y: j, c: oppCol, p: 'q'
+            }));
+          }
         }
       }
     }
         }
       }
     }
@@ -600,20 +520,124 @@ export default class ChakartRules extends ChessRules {
     }
     if (move.egg)
       this.displayBonus(move.egg);
     }
     if (move.egg)
       this.displayBonus(move.egg);
+    this.playOnBoard(move);
     this.nextMove = move.next;
   }
 
     this.nextMove = move.next;
   }
 
-  displayBonus(egg) {
-    alert(egg); //TODO: nicer display
+  // Helper to set and apply banana/bomb effect
+  getRandomSquare([x, y], steps, freeSquare) {
+    let validSteps = steps.filter(s => this.onBoard(x + s[0], y + s[1]));
+    if (freeSquare) {
+      // Square to put banana/bomb cannot be occupied by a piece
+      validSteps = validSteps.filter(s => {
+        return ["", 'a'].includes(this.getColor(x + s[0], y + s[1]))
+      });
+    }
+    if (validSteps.length == 0)
+      return null;
+    const step = validSteps[Random.randInt(validSteps.length)];
+    return [x + step[0], y + step[1]];
   }
 
   }
 
-  filterValid(moves) {
-    return moves;
+  getEggEffect(move) {
+    const getRandomPiece = (c) => {
+      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')
+            bagOfPieces.push([i, j]);
+        }
+      }
+      if (bagOfPieces.length >= 1)
+        return Random.sample(bagOfPieces);
+      return null;
+    };
+    const color = this.turn;
+    let em = null;
+    switch (move.egg) {
+      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 coords = getRandomPiece(oldColor);
+        if (coords) {
+          const piece = this.getPiece(coords[0], coords[1]);
+          em = new Move({
+            appear: [
+              new PiPo({x: coords[0], y: coords[1], c: newColor, p: piece})
+            ],
+            vanish: [
+              new PiPo({x: coords[0], y: coords[1], c: oldColor, p: piece})
+            ]
+          });
+        }
+        break;
+      case "bowser":
+        em = new Move({
+          appear: [
+            new PiPo({
+              x: move.end.x,
+              y: move.end.y,
+              c: color,
+              p: V.IMMOBILIZE_CODE[move.appear[0].p]
+            })
+          ],
+          vanish: [
+            new PiPo({
+              x: move.end.x,
+              y: move.end.y,
+              c: color,
+              p: move.appear[0].p
+            })
+          ]
+        });
+        break;
+      case "koopa":
+        // Reverse move
+        em = new Move({
+          appear: [
+            new PiPo({
+              x: move.start.x, y: move.start.y, c: color, p: move.appear[0].p
+            })
+          ],
+          vanish: [
+            new PiPo({
+              x: move.end.x, y: move.end.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({
+            x: move.start.x,
+            y: move.start.y,
+            c: 'a',
+            p: this.getPiece(move.start.x, move.start.y)
+          }));
+        }
+        break;
+      case "chomp":
+        // Eat piece
+        em = new Move({
+          appear: [],
+          vanish: [
+            new PiPo({
+              x: move.end.x, y: move.end.y, c: color, p: move.appear[0].p
+            })
+          ],
+          end: {x: move.end.x, y: move.end.y}
+        });
+        break;
+    }
+    if (em && move.egg != "koopa")
+      em.noAnimate = true; //static move
+    return em;
   }
 
   getMushroomEffect(move) {
     let step = [move.end.x - move.start.x, move.end.y - move.start.y];
   }
 
   getMushroomEffect(move) {
     let step = [move.end.x - move.start.x, move.end.y - move.start.y];
-    if ([0, 1].some(i => step[i] >= 2 && step[1-i] != 1)) {
+    if ([0, 1].some(i => Math.abs(step[i]) >= 2 && Math.abs(step[1-i]) != 1)) {
       // Slider, multi-squares: normalize step
       for (let j of [0, 1])
         step[j] = step[j] / Math.abs(step[j]) || 0;
       // Slider, multi-squares: normalize step
       for (let j of [0, 1])
         step[j] = step[j] / Math.abs(step[j]) || 0;
@@ -622,10 +646,11 @@ export default class ChakartRules extends ChessRules {
     const afterSquare =
       [nextSquare[0] + step[0], nextSquare[1] + step[1]];
     let nextMove = null;
     const afterSquare =
       [nextSquare[0] + step[0], nextSquare[1] + step[1]];
     let nextMove = null;
+    this.playOnBoard(move); //HACK for getBasicMove() below
     if (
       this.onBoard(nextSquare[0], nextSquare[1]) &&
     if (
       this.onBoard(nextSquare[0], nextSquare[1]) &&
-      this.board[nextSquare[0]][nextSquare[1]] == "" &&
-      ['k', 'p', 'n'].includes(move.vanish[0].p)
+      ['k', 'p', 'n'].includes(move.vanish[0].p) &&
+      !['w', 'b'].includes(this.getColor(nextSquare[0], nextSquare[1]))
     ) {
       // Speed up non-sliders
       nextMove = this.getBasicMove([move.end.x, move.end.y], nextSquare);
     ) {
       // Speed up non-sliders
       nextMove = this.getBasicMove([move.end.x, move.end.y], nextSquare);
@@ -638,23 +663,49 @@ export default class ChakartRules extends ChessRules {
     ) {
       nextMove = this.getBasicMove([move.end.x, move.end.y], afterSquare);
     }
     ) {
       nextMove = this.getBasicMove([move.end.x, move.end.y], afterSquare);
     }
+    this.undoOnBoard(move);
     return nextMove;
   }
 
     return nextMove;
   }
 
+  getBombBananaEffect(move, item) {
+    const steps = item == V.BANANA
+      ? [[1, 0], [-1, 0], [0, 1], [0, -1]]
+      : [[1, 1], [1, -1], [-1, 1], [-1, -1]];
+    const nextSquare = this.getRandomSquare([move.end.x, move.end.y], steps);
+    this.playOnBoard(move); //HACK for getBasicMove()
+    const res = this.getBasicMove([move.end.x, move.end.y], nextSquare);
+    this.undoOnBoard(move);
+    return res;
+  }
+
+  displayBonus(egg) {
+    alert(egg); //TODO: nicer display
+  }
+
+  atLeastOneMove() {
+    return true;
+  }
+
+  filterValid(moves) {
+    return moves;
+  }
+
   playPlusVisual(move, r) {
     this.moveStack.push(move);
   playPlusVisual(move, r) {
     this.moveStack.push(move);
-    this.play(move);
-    this.playVisual(move, r);
-    if (this.nextMove)
-      this.playPlusVisual(this.nextMove, r);
+    const nextLines = () => {
+      this.play(move);
+      this.playVisual(move, r);
+      if (this.nextMove)
+        this.playPlusVisual(this.nextMove, r);
+      else {
+        this.afterPlay(this.moveStack);
+        this.moveStack = [];
+      }
+    };
+    if (this.moveStack.length == 1)
+      nextLines();
     else
     else
-      this.afterPlay(this.moveStack);
+      this.animate(move, nextLines);
   }
 
   }
 
-  // TODO: set some special moves (effects) as noAnimate
-  // TODO: put bomb/banana only at final location of a move ? Seems more logical
-  // + fix bishop takes mushroom and jump
-  // Also improve showChoices for invisible queen + king shell
-  // + fix turn issues after multimove (like bishop put bomb)
-
 };
 };
index b60a821..65a44fb 100644 (file)
@@ -1,7 +1,7 @@
 @import url("/base_pieces.css");
 
 piece.egg {
 @import url("/base_pieces.css");
 
 piece.egg {
-  background-image: url('/pieces/chakart_egg');
+  background-image: url('/pieces/chakart_egg.svg');
 }
 
 piece.mushroom {
 }
 
 piece.mushroom {
@@ -23,9 +23,11 @@ piece.black.invisible {
   background-image: url('/pieces/empty.svg');
 }
 
   background-image: url('/pieces/empty.svg');
 }
 
-piece.white.immobilized {
-  background-color: yellow;
+piece.immobilized {
+  background-color: lightgreen;
+  opacity: 0.6;
 }
 }
-piece.black.immobilized {
-  background-color: red;
+
+piece.remote-capture {
+  background-image: url('/pieces/chakart_shell.svg');
 }
 }