Cleaner fen generation + first draft of Apocalypse + a few fixes
[xogo.git] / variants / Chakart / class.js
index cee0242..815be74 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 PiPo from "/utils/PiPo.js";
 import Move from "/utils/Move.js";
 
@@ -20,7 +20,8 @@ export default class ChakartRules extends ChessRules {
             {label: "Asymmetric random", value: 2}
           ]
         }
-      ]
+      ],
+      styles: ["cylinder"]
     };
   }
 
@@ -63,10 +64,6 @@ export default class ChakartRules extends ChessRules {
     };
   }
 
-  static get INVISIBLE_QUEEN() {
-    return 'i';
-  }
-
   // Fictive color 'a', bomb banana mushroom egg
   static get BOMB() {
     return 'w'; //"Wario"
@@ -87,22 +84,59 @@ export default class ChakartRules extends ChessRules {
       "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) {
-    let specials = {
+    const specials = {
       'i': {"class": "invisible"}, //queen
+      '?': {"class": "mystery"}, //...initial square
       'e': {"class": "egg"},
       'm': {"class": "mushroom"},
       'd': {"class": "banana"},
-      'w': {"class": "bomb"}
+      'w': {"class": "bomb"},
+      'z': {"class": "remote-capture"}
+    };
+    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, super.pieces(color, x, y));
+    return Object.assign(
+      {
+        'y': {
+          // Virtual piece for "king remote shell captures"
+          moves: [],
+          attack: [
+            {
+              steps: [
+                [0, 1], [0, -1], [1, 0], [-1, 0],
+                [1, 1], [1, -1], [-1, 1], [-1, -1]
+              ]
+            }
+          ]
+        }
+      },
+      specials, bowsered, super.pieces(color, x, y)
+    );
   }
 
-  genRandInitFen(seed) {
-    const gr = new GiveawayRules(
-      {mode: "suicide", options: {}, genFenOnly: true});
-    // Add Peach + mario flags
-    return gr.genRandInitFen(seed).slice(0, -17) + '{"flags":"1111"}';
+  genRandInitBaseFen() {
+    const options = Object.assign({mode: "suicide"}, this.options);
+    const gr = new GiveawayRules({options: options, genFenOnly: true});
+    let res = gr.genRandInitBaseFen();
+    res.o["flags"] = "1111"; //Peach + Mario flags
+    return res;
   }
 
   fen2board(f) {
@@ -142,52 +176,46 @@ export default class ChakartRules extends ChessRules {
   }
 
   setOtherVariables(fenParsed) {
-    this.setFlags(fenParsed.flags);
-    this.reserve = {}; //to be filled later
+    super.setOtherVariables(fenParsed);
     this.egg = null;
-    this.moveStack = [];
+    // Change seed (after FEN generation!!)
+    // so that further calls differ between players:
+    Random.setSeed(Math.floor(19840 * Math.random()));
+  }
+
+  initReserves() {
+    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 = (color == '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);
-        if (
-          this.board[i][j] == "" ||
-          this.getColor(i, j) == 'a' ||
-          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] != "")
-            m.vanish.push(new PiPo({x: i, y: j, c: 'a', 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]) {
     let moves = [];
+    const piece = this.getPiece(x, y);
     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);
-      // 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);
@@ -195,9 +223,10 @@ export default class ChakartRules extends ChessRules {
           if (
             (i != x || j != y) &&
             ['w', 'b'].includes(colIJ) &&
+            !Object.keys(V.IMMOBILIZE_DECODE).includes(pieceIJ) &&
             // Next conditions = no pawn on last rank
             (
-              initPiece != 'p' ||
+              piece != 'p' ||
               (
                 (color != 'w' || i != 0) &&
                 (color != 'b' || i != this.size.x - 1)
@@ -213,8 +242,8 @@ export default class ChakartRules extends ChessRules {
             )
           ) {
             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);
           }
         }
@@ -222,7 +251,6 @@ export default class ChakartRules extends ChessRules {
     }
     else {
       // Normal case (including bonus daisy)
-      const piece = this.getPiece(x, y);
       switch (piece) {
         case 'p':
           moves = this.getPawnMovesFrom([x, y]); //apply promotions
@@ -238,165 +266,11 @@ export default class ChakartRules extends ChessRules {
           break;
         case 'b':
         case 'r':
-          // explicitely listing types to avoid moving immobilized piece
-          moves = this.getRookOrBishopMovesFrom([x, y], piece);
-          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]]);
+          // Explicitely listing types to avoid moving immobilized piece
+          moves = super.getPotentialMovesOf(piece, [x, y]);
           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;
-  }
-
-  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;
   }
 
@@ -406,86 +280,73 @@ export default class ChakartRules extends ChessRules {
     const shiftX = (color == 'w' ? -1 : 1);
     const firstRank = (color == "w" ? this.size.x - 1 : 0);
     let moves = [];
+    const frontPiece = this.getPiece(x + shiftX, y);
     if (
       this.board[x + shiftX][y] == "" ||
       this.getColor(x + shiftX, y) == 'a' ||
-      this.getPiece(x + shiftX, y) == V.INVISIBLE_QUEEN
+      frontPiece == 'i'
     ) {
       moves.push(this.getBasicMove([x, y], [x + shiftX, y]));
       if (
         [firstRank, firstRank + shiftX].includes(x) &&
+        ![V.BANANA, V.BOMB].includes(frontPiece) &&
         (
           this.board[x + 2 * shiftX][y] == "" ||
           this.getColor(x + 2 * shiftX, y) == 'a' ||
-          this.getPiece(x + 2 * shiftX, y) == V.INVISIBLE_QUEEN
+          this.getPiece(x + 2 * shiftX, y) == 'i'
         )
       ) {
         moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
       }
     }
     for (let shiftY of [-1, 1]) {
+      const nextY = this.getY(y + shiftY);
       if (
-        y + shiftY >= 0 &&
-        y + shiftY < this.size.y &&
-        this.board[x + shiftX][y + shiftY] != "" &&
+        nextY >= 0 &&
+        nextY < this.size.y &&
+        this.board[x + shiftX][nextY] != "" &&
         // Pawns cannot capture invisible queen this way!
-        this.getPiece(x + shiftX, y + shiftY) != V.INVISIBLE_QUEEN &&
-        ['a', oppCol].includes(this.getColor(x + shiftX, y + shiftY))
+        this.getPiece(x + shiftX, nextY) != 'i' &&
+        ['a', oppCol].includes(this.getColor(x + shiftX, nextY))
       ) {
-        moves.push(this.getBasicMove([x, y], [x + shiftX, y + shiftY]));
+        moves.push(this.getBasicMove([x, y], [x + shiftX, nextY]));
       }
     }
     this.pawnPostProcess(moves, color, oppCol);
-    // Add mushroom on initial square
+    // Add mushroom on before-last square (+ potential segments)
     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 [mx, my] = [x, y];
+      if (Math.abs(m.end.x - m.start.x) == 2)
+        mx = (m.start.x + m.end.x) / 2;
+      m.appear.push(new PiPo({x: mx, y: my, c: 'a', p: 'm'}));
+      if (mx != x && this.board[mx][my] != "") {
+        m.vanish.push(new PiPo({
+          x: mx,
+          y: my,
+          c: this.getColor(mx, my),
+          p: this.getPiece(mx, my)
+        }));
+      }
+      if (Math.abs(m.end.y - m.start.y) > 1) {
+        m.segments = [
+          [[x, y], [x, y]],
+          [[m.end.x, m.end.y], [m.end.x, m.end.y]]
+        ];
       }
-      return m;
     });
+    return moves;
   }
 
   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']) {
@@ -497,7 +358,7 @@ export default class ChakartRules extends ChessRules {
           m.vanish[0].c != 'a'
         ) {
           let im = JSON.parse(JSON.stringify(m));
-          im.appear[0].p = V.INVISIBLE_QUEEN;
+          im.appear[0].p = 'i';
           im.noAnimate = true;
           invisibleMoves.push(im);
         }
@@ -507,154 +368,351 @@ 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']) {
-      super.pieces()['k'].moves[0].steps.forEach(step => {
-        let [i, j] = [x + step[0], y + step[1]];
-        while (
-          this.onBoard(i, j) &&
-          (
-            this.board[i][j] == "" ||
-            this.getPiece(i, j) == V.INVISIBLE_QUEEN ||
-            (
-              this.getColor(i, j) == 'a' &&
-              [V.EGG, V.MUSHROOM].includes(this.getPiece(i, j))
-            )
-          )
-        ) {
-          i += step[0];
-          j += step[1];
-        }
-        if (this.onBoard(i, j)) {
-          const colIJ = this.getColor(i, j);
-          if (colIJ != this.turn) {
-            // May just destroy a bomb or banana:
-            let shellCapture = new Move({
-              start: {x: x, y: y},
-              end: {x: i, y: j},
-              appear: [],
-              vanish: [
-                new PiPo({x: i, y: j, c: colIJ, p: this.getPiece(i, j)})
-              ]
-            });
-            shellCapture.shell = true; //easier play()
-            moves.push(shellCapture);
-          }
-        }
+      let shellCaptures = super.getPotentialMovesOf('y', [x, y]);
+      shellCaptures.forEach(sc => {
+        sc.shell = true; //easier play()
+        sc.choice = 'z'; //to display in showChoices()
+        // Fix move (Rifle style):
+        sc.vanish.shift();
+        sc.appear.shift();
       });
+      Array.prototype.push.apply(moves, shellCaptures);
     }
     return moves;
   }
 
   play(move) {
-    this.egg = move.egg;
     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) {
+    this.egg = move.egg;
     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]);
     }
-    if (this.getPiece(move.end.x, move.end.y) == V.MUSHROOM)
-      move.next = this.getMushroomEffect(move);
     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 == 'i') {
       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 (color == this.playerColor) {
+        move.appear.push(
+          new PiPo({x: move.start.x, y: move.start.y, c: color, p: '?'}));
+      }
+    }
+    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
+      for (let i=0; i<8; i++) {
+        for (let j=0; j<8; j++) {
           if (
-            this.getColor(i, j) == color &&
-            Object.keys(V.IMMOBILIZE_DECODE).includes(piece)
+            this.board[i][j] != "" &&
+            this.getColor(i, j) == oppCol
           ) {
-            this.board[i][j] = color + V.IMMOBILIZE_DECODE[piece];
+            const pieceIJ = this.getPiece(i, j);
+            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'}));
+            }
+            else if (pieceIJ == '?')
+              move.vanish.push(new PiPo({x: i, y: j, c: oppCol, p: '?'}));
           }
         }
       }
     }
-    // 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;
+    this.playOnBoard(move);
+    super.postPlay(move);
+  }
+
+  playVisual(move, r) {
+    super.playVisual(move, r);
+    if (move.egg)
+      this.displayBonus(move);
+  }
+
+  computeNextMove(move) {
+    // 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;
+    }
+    // NOTE: Chakart has also some side-effects:
+    if (
+      !move.next && move.appear.length > 0 &&
+      !move.kingboo && !move.luigiEffect
+    ) {
+      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])
+              })
+            );
+          }
         }
       }
     }
-    if (!move.next && !["daisy", "toadette", "kingboo"].includes(move.egg)) {
-      this.turn = oppCol;
-      this.movesCount++;
-    }
-    if (move.egg)
-      this.displayBonus(move.egg);
-    this.nextMove = move.next;
   }
 
-  displayBonus(egg) {
-    alert(egg); //TODO: nicer display
+  isLastMove(move) {
+    return !move.next && !["daisy", "toadette", "kingboo"].includes(move.egg);
   }
 
-  filterValid(moves) {
-    return moves;
+  // 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]];
+  }
+
+  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})
+            ]
+          });
+          em.luigiEffect = true; //avoid dropping bomb/banana by mistake
+        }
+        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];
-    if ([0, 1].some(i => step[i] >= 2 && step[1-i] != 1)) {
-      // Slider, multi-squares: normalize step
-      for (let j of [0, 1])
-        step[j] = step[j] / Math.abs(step[j]) || 0;
+    if (
+      typeof move.start.x == "string" || //drop move (toadette)
+      ['b', 'r', 'q'].includes(move.vanish[0].p) //slider
+    ) {
+      return null;
     }
+    let step = [move.end.x - move.start.x, move.end.y - move.start.y];
+    if (Math.abs(step[0]) == 2 && Math.abs(step[1]) == 0)
+      // Pawn initial 2-squares move: normalize step
+      step[0] /= 2;
     const nextSquare = [move.end.x + step[0], move.end.y + step[1]];
-    const afterSquare =
-      [nextSquare[0] + step[0], nextSquare[1] + step[1]];
     let nextMove = null;
     if (
       this.onBoard(nextSquare[0], nextSquare[1]) &&
-      this.board[nextSquare[0]][nextSquare[1]] == "" &&
-      ['k', 'p', 'n'].includes(move.vanish[0].p)
+      (
+        this.board[nextSquare[0]][nextSquare[1]] == "" ||
+        this.getColor(nextSquare[0], nextSquare[1]) == 'a'
+      )
     ) {
-      // Speed up non-sliders
+      this.playOnBoard(move); //HACK for getBasicMove()
       nextMove = this.getBasicMove([move.end.x, move.end.y], nextSquare);
-    }
-    else if (
-      this.onBoard(afterSquare[0], afterSquare[1]) &&
-      this.board[nextSquare[0]][nextSquare[1]] != "" &&
-      this.getColor(nextSquare[0], nextSquare[1]) != 'a' &&
-      this.getColor(afterSquare[0], afterSquare[1]) != this.turn
-    ) {
-      nextMove = this.getBasicMove([move.end.x, move.end.y], afterSquare);
+      this.undoOnBoard(move);
     }
     return nextMove;
   }
 
-  playPlusVisual(move, r) {
-    this.moveStack.push(move);
-    this.play(move);
-    this.playVisual(move, r);
-    if (this.nextMove)
-      this.playPlusVisual(this.nextMove, r);
-    else
-      this.afterPlay(this.moveStack);
+  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;
   }
 
-  // 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)
+  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);
+  }
+
+  atLeastOneMove() {
+    return true;
+  }
+
+  filterValid(moves) {
+    return moves;
+  }
+
+  // Kingboo bonus can be animated better:
+  customAnimate(move, segments, cb) {
+    if (!move.kingboo)
+      return 0;
+    super.animateMoving(move.end, move.start, null,
+                        segments.reverse().map(s => s.reverse()), cb);
+    return 1;
+  }
 
 };