Fix (a lot but maybe not all of) Chakart
[xogo.git] / variants / Chakart / class.js
index 04c0864..a9b1908 100644 (file)
@@ -1,11 +1,11 @@
-import ChessRules from "/base_rules";
-import GiveawayRules from "/variants/Giveaway";
+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 PiPo from "/utils/PiPo.js";
 import Move from "/utils/Move.js";
 
-export class ChakartRules extends ChessRules {
+export default class ChakartRules extends ChessRules {
 
   static get Options() {
     return {
@@ -20,7 +20,8 @@ export class ChakartRules extends ChessRules {
             {label: "Asymmetric random", value: 2}
           ]
         }
-      ]
+      ],
+      styles: ["cylinder"]
     };
   }
 
@@ -34,6 +35,12 @@ export class ChakartRules extends ChessRules {
   get hasEnpassant() {
     return false;
   }
+  get hasReserve() {
+    return true;
+  }
+  get hasReserveFen() {
+    return false;
+  }
 
   static get IMMOBILIZE_CODE() {
     return {
@@ -75,13 +82,47 @@ export class ChakartRules extends ChessRules {
     return 'm';
   }
 
+  static get EGG_SURPRISE() {
+    return [
+      "kingboo", "bowser", "daisy", "koopa",
+      "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) {
+    const specials = {
+      'i': {"class": "invisible"}, //queen
+      'e': {"class": "egg"},
+      'm': {"class": "mushroom"},
+      'd': {"class": "banana"},
+      '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, bowsered, super.pieces(color, x, y));
+  }
+
   genRandInitFen(seed) {
-    const gr = new GiveawayRules({mode: "suicide"}, true);
-    return (
-      gr.genRandInitFen(seed).slice(0, -1) +
-      // Add Peach + Mario flags + capture counts
-      '{"flags":"1111", "ccount":"000000000000"}'
-    );
+    const gr = new GiveawayRules(
+      {mode: "suicide", options: {}, genFenOnly: true});
+    // Add Peach + mario flags
+    return gr.genRandInitFen(seed).slice(0, -17) + '{"flags":"1111"}';
   }
 
   fen2board(f) {
@@ -114,34 +155,20 @@ export class ChakartRules extends ChessRules {
     this.powerFlags = flags;
   }
 
-  getFen() {
-    return super.getFen() + " " + this.getCapturedFen();
-  }
-
   getFlagsFen() {
     return ['w', 'b'].map(c => {
       return ['k', 'q'].map(p => this.powerFlags[c][p] ? "1" : "0").join("");
     }).join("");
   }
 
-  getCapturedFen() {
-    const res = ['w', 'b'].map(c => {
-      Object.values(this.captured[c])
-    });
-    return res[0].concat(res[1]).join("");
-  }
-
   setOtherVariables(fenParsed) {
-    super.setOtherVariables(fenParsed);
-    // Initialize captured pieces' counts from FEN
-    const allCapts = fenParsed.captured.split("").map(x => parseInt(x, 10));
-    const pieces = ['p', 'r', 'n', 'b', 'q', 'k'];
-    this.captured = {
-      w: Array.toObject(pieces, allCapts.slice(0, 6)),
-      b: Array.toObject(pieces, allCapts.slice(6, 12))
-    };
-    this.reserve = { w: {}, b: {} }; //to be replaced by this.captured
+    this.setFlags(fenParsed.flags);
+    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
@@ -150,24 +177,24 @@ export class ChakartRules extends ChessRules {
       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);
+        const colIJ = this.getColor(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},
-            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}));
+            m.vanish.push(new PiPo({x: i, y: j, c: colIJ, p: pieceIJ}));
           moves.push(m);
         }
       }
@@ -175,63 +202,79 @@ export class ChakartRules extends ChessRules {
     return moves;
   }
 
-// TODO: rethink from here:
-
-// allow pawns 
-  // queen invisible move, king shell: special functions
-
-// prevent pawns from capturing invisible queen (post)
-// post-process: 
-
-//events : playPlusVisual after mouse up, playReceived (include animation) on opp move
-// ==> if move.cont (banana...) self re-call playPlusVisual (rec ?)
-
-  // Moving something. Potential effects resolved after playing
-  getPotentialMovesFrom([x, y], bonus) {
+  getPotentialMovesFrom([x, y]) {
     let moves = [];
-    if (bonus == "toadette")
-      return this.getDropMovesFrom([x, y]);
-    else if (bonus == "kingboo") {
-      const initPiece = this.getPiece(x, y);
-      const color = this.getColor(x, y);
+    const piece = this.getPiece(x, y);
+    if (this.egg == "toadette")
+      moves = this.getDropMovesFrom([x, y]);
+    else if (this.egg == "kingboo") {
+      const color = this.turn;
       const oppCol = C.GetOppCol(color);
-      // Only allow to swap pieces (TODO: restrict for pawns)
+      // 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++) {
-          if ((i != x || j != y) && this.board[i][j] != "") {
-            const pstart = new PiPo({x: x, y: y, p: initPiece, c: color});
-            const pend =
+          const colIJ = this.getColor(i, j);
+          const pieceIJ = this.getPiece(i, j);
+          if (
+            (i != x || j != y) &&
+            ['w', 'b'].includes(colIJ) &&
+            !Object.keys(V.IMMOBILIZE_DECODE).includes(pieceIJ) &&
+            // Next conditions = no pawn on last rank
+            (
+              piece != 'p' ||
+              (
+                (color != 'w' || i != 0) &&
+                (color != 'b' || i != this.size.x - 1)
+              )
+            )
+            &&
+            (
+              pieceIJ != 'p' ||
+              (
+                (colIJ != 'w' || x != 0) &&
+                (colIJ != 'b' || x != this.size.x - 1)
+              )
+            )
+          ) {
             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);
           }
         }
       }
-      return moves;
     }
-    // Normal case (including bonus daisy)
-    switch (this.getPiece(x, y)) {
-      case 'p':
-        moves = this.getPawnMovesFrom([x, y]); //apply promotions
-        // TODO: add mushroom on init square
-        break;
-      case 'q':
-        moves = this.getQueenMovesFrom([x, y]);
-        break;
-      case 'k',
-        moves = this.getKingMovesFrom([x, y]);
-        break;
-      case 'n':
-        moves = super.getPotentialMovesFrom([x, y]);
-        // TODO: add egg on init square
-        break;
-      default:
-        moves = super.getPotentialMovesFrom([x, y]);
+    else {
+      // Normal case (including bonus daisy)
+      switch (piece) {
+        case 'p':
+          moves = this.getPawnMovesFrom([x, y]); //apply promotions
+          break;
+        case 'q':
+          moves = this.getQueenMovesFrom([x, y]);
+          break;
+        case 'k':
+          moves = this.getKingMovesFrom([x, y]);
+          break;
+        case 'n':
+          moves = this.getKnightMovesFrom([x, y]);
+          break;
+        case 'b':
+        case 'r':
+          // Explicitely listing types to avoid moving immobilized piece
+          moves = super.getPotentialMovesOf(piece, [x, y]);
+          break;
+      }
     }
     return moves;
   }
 
+  canStepOver(i, j) {
+    return (
+      this.board[i][j] == "" ||
+      [V.MUSHROOM, V.EGG].includes(this.getPiece(i, j)));
+  }
+
   getPawnMovesFrom([x, y]) {
     const color = this.turn;
     const oppCol = C.GetOppCol(color);
@@ -243,40 +286,63 @@ export class ChakartRules extends ChessRules {
       this.getColor(x + shiftX, y) == 'a' ||
       this.getPiece(x + shiftX, y) == V.INVISIBLE_QUEEN
     ) {
-
-      // TODO:
-      this.addPawnMoves([x, y], [x + shiftX, y], moves);
+      moves.push(this.getBasicMove([x, y], [x + shiftX, y]));
       if (
         [firstRank, firstRank + shiftX].includes(x) &&
         (
-          this.board[x + 2 * shiftX][y] == V.EMPTY ||
+          this.board[x + 2 * shiftX][y] == "" ||
           this.getColor(x + 2 * shiftX, y) == 'a' ||
           this.getPiece(x + 2 * shiftX, y) == V.INVISIBLE_QUEEN
         )
       ) {
-        moves.push(this.getBasicMove({ x: x, y: y }, [x + 2 * shiftX, y]));
+        moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
       }
     }
     for (let shiftY of [-1, 1]) {
       if (
         y + shiftY >= 0 &&
-        y + shiftY < sizeY &&
-        this.board[x + shiftX][y + shiftY] != V.EMPTY &&
+        y + shiftY < this.size.y &&
+        this.board[x + shiftX][y + shiftY] != "" &&
         // 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.addPawnMoves([x, y], [x + shiftX, y + shiftY], moves);
+        moves.push(this.getBasicMove([x, y], [x + shiftX, y + shiftY]));
       }
     }
+    this.pawnPostProcess(moves, color, oppCol);
+    // Add mushroom on before-last square
+    moves.forEach(m => {
+      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 moves;
   }
 
+  getKnightMovesFrom([x, y]) {
+    // Add egg on initial square:
+    return this.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 = super.getPotentialQueenMoves(sq);
+    const normalMoves = this.getPotentialMovesOf('q', sq);
     // If flag allows it, add 'invisible movements'
     let invisibleMoves = [];
-    if (this.powerFlags[this.turn][V.QUEEN]) {
+    if (this.powerFlags[this.turn]['q']) {
       normalMoves.forEach(m => {
         if (
           m.appear.length == 1 &&
@@ -286,7 +352,7 @@ export class ChakartRules extends ChessRules {
         ) {
           let im = JSON.parse(JSON.stringify(m));
           im.appear[0].p = V.INVISIBLE_QUEEN;
-          im.end.noHighlight = true;
+          im.noAnimate = true;
           invisibleMoves.push(im);
         }
       });
@@ -295,16 +361,15 @@ export class ChakartRules extends ChessRules {
   }
 
   getKingMovesFrom([x, y]) {
-    let moves = super.getPotentialKingMoves([x, y]);
-    const color = this.turn;
+    let moves = this.getPotentialMovesOf('k', [x, y]);
     // If flag allows it, add 'remote shell captures'
-    if (this.powerFlags[this.turn][V.KING]) {
-      V.steps[V.ROOK].concat(V.steps[V.BISHOP]).forEach(step => {
+    if (this.powerFlags[this.turn]['k']) {
+      super.pieces()['k'].moves[0].steps.forEach(step => {
         let [i, j] = [x + step[0], y + step[1]];
         while (
-          V.OnBoard(i, j) &&
+          this.onBoard(i, j) &&
           (
-            this.board[i][j] == V.EMPTY ||
+            this.board[i][j] == "" ||
             this.getPiece(i, j) == V.INVISIBLE_QUEEN ||
             (
               this.getColor(i, j) == 'a' &&
@@ -315,22 +380,21 @@ export class ChakartRules extends ChessRules {
           i += step[0];
           j += step[1];
         }
-        if (V.OnBoard(i, j)) {
+        if (this.onBoard(i, j)) {
           const colIJ = this.getColor(i, j);
-          if (colIJ != color) {
+          if (colIJ != this.turn) {
             // May just destroy a bomb or banana:
-            moves.push(
-              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)
-                  })
-                ]
-              })
-            );
+            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()
+            shellCapture.choice = 'z'; //to display in showChoices()
+            moves.push(shellCapture);
           }
         }
       });
@@ -338,151 +402,310 @@ export class ChakartRules extends ChessRules {
     return moves;
   }
 
-  // TODO: can merge prePlay into play() ==> no need to distinguish
-/// if any of my pieces was immobilized, it's not anymore.
-  //if play set a piece immobilized, then mark it
-  prePlay(move) {
-    if (move.effect == "toadette")
-      this.reserve = this.captured;
-    else
-      this.reserve = { w: {}, b: {} };;
+  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;
-    if (
-      move.vanish.length == 2 &&
-      move.vanish[1].c != 'a' &&
-      move.appear.length == 1 //avoid king Boo!
-    ) {
-      // Capture: update this.captured
-      let capturedPiece = move.vanish[1].p;
-      if (capturedPiece == V.INVISIBLE_QUEEN)
-        capturedPiece = V.QUEEN;
-      else if (Object.keys(V.IMMOBILIZE_DECODE).includes(capturedPiece))
-        capturedPiece = V.IMMOBILIZE_DECODE[capturedPiece];
-      this.captured[move.vanish[1].c][capturedPiece]++;
+    const oppCol = C.GetOppCol(color);
+    if (move.egg == "toadette") {
+      this.reserve = { w: {}, b: {} };
+      // Randomly select a piece in pawnPromotions
+      if (!move.toadette)
+        move.toadette = Random.sample(this.pawnPromotions);
+      this.reserve[color][move.toadette] = 1;
+      this.re_drawReserve([color]);
     }
-    else if (move.vanish.length == 0) {
-      if (move.appear.length == 0 || move.appear[0].c == 'a') return;
-      // A piece is back on board
-      this.captured[move.appear[0].c][move.appear[0].p]--;
+    else if (Object.keys(this.reserve).length > 0) {
+      this.reserve = {};
+      this.re_drawReserve([color]);
     }
-    if (move.appear.length == 0) {
-      // Three cases: king "shell capture", Chomp or Koopa
-      if (this.getPiece(move.start.x, move.start.y) == V.KING)
-        // King remote capture:
-        this.powerFlags[color][V.KING] = false;
-      else if (move.end.effect == "chomp")
-        this.captured[color][move.vanish[0].p]++;
+    if (move.shell)
+      this.powerFlags[color]['k'] = false;
+    else if (move.appear.length > 0 && move.appear[0].p == V.INVISIBLE_QUEEN) {
+      this.powerFlags[move.appear[0].c]['q'] = false;
+      if (color != this.playerColor)
+        alert("Invisible queen!");
     }
-    else if (move.appear[0].p == V.INVISIBLE_QUEEN)
-      this.powerFlags[move.appear[0].c][V.QUEEN] = false;
-    if (this.subTurn == 2) return;
-    if (
-      move.turn[1] == 1 &&
-      move.appear.length == 0 ||
-      !(Object.keys(V.IMMOBILIZE_DECODE).includes(move.appear[0].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 (this.board[i][j] != V.EMPTY) {
+          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];
-              move.wasImmobilized = [i, j];
+              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 = V.GetOppCol(color);
-    for (let i=0; i<8; i++) {
-      for (let j=0; j<8; j++) {
-        if (
-          this.board[i][j] != V.EMPTY &&
-          this.getColor(i, j) == oppCol &&
-          this.getPiece(i, j) == V.INVISIBLE_QUEEN
-        ) {
-          this.board[i][j] = oppCol + V.QUEEN;
-          move.wasInvisible = [i, j];
+      // 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'
+            }));
+          }
         }
       }
     }
-  }
-
-  play(move) {
-    this.prePlay(move);
-    this.playOnBoard(move);
-    if (["kingboo", "toadette", "daisy"].includes(move.effect)) {
-      this.effect = move.effect;
-      this.subTurn = 2;
-    }
-    else {
-      this.turn = C.GetOppCol(this.turn);
+    if (!move.next && !["daisy", "toadette", "kingboo"].includes(move.egg)) {
+      this.turn = oppCol;
       this.movesCount++;
-      this.subTurn = 1;
     }
+    if (move.egg)
+      this.displayBonus(move.egg);
+    this.playOnBoard(move);
+    this.nextMove = move.next;
   }
 
-  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]];
   }
 
-  // idée : on joue le coup, puis son effet est déterminé, puis la suite (si suite)
-  // est jouée automatiquement ou demande action utilisateur, etc jusqu'à coup terminal.
-  tryMoveFollowup(move, cb) {
-    if (this.getColor(move.end.x, move.end.y) == 'a') {
-      // effect, or bonus/malus
-      const endType = this.getPiece(m.end.x, m.end.y);
-      switch (endType) {
-        case V.EGG:
-          this.applyRandomBonus(move, cb);
-          break;
-        case V.BANANA:
-        case V.BOMB: {
-          const dest =
-            this.getRandomSquare([m.end.x, m.end.y],
-              endType == V.BANANA
-                ? [[1, 1], [1, -1], [-1, 1], [-1, -1]]
-                : [[1, 0], [-1, 0], [0, 1], [0, -1]]);
-          const nextMove = this.getBasicMove([move.end.x, move.end.y], dest);
-          cb(nextMove);
-          break;
+  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]);
         }
-        case V.MUSHROOM:
-          // aller dans direction, saut par dessus pièce adverse
-          // ou amie (tjours), new step si roi caval pion
-          break;
       }
+      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];
+    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;
+    }
+    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;
+    this.playOnBoard(move); //HACK for getBasicMove() below
+    if (
+      this.onBoard(nextSquare[0], nextSquare[1]) &&
+      ['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);
     }
+    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;
   }
 
-  applyRandomBonnus(move, cb) {
-    // TODO: determine bonus/malus, and then 
+  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;
   }
 
-  // Helper to apply banana/bomb effect
-  getRandomSquare([x, y], steps) {
-    const validSteps = steps.filter(s => this.onBoard(x + s[0], y + s[1]));
-    const step = validSteps[Random.randInt(validSteps.length)];
-    return [x + step[0], y + step[1]];
+  displayBonus(egg) {
+    alert(egg); //TODO: nicer display
+  }
+
+  atLeastOneMove() {
+    return true;
   }
-// TODO: turn change indicator ?!
+
+  filterValid(moves) {
+    return moves;
+  }
+
   playPlusVisual(move, r) {
     this.moveStack.push(move);
-    this.play(move);
-    this.playVisual(move, r);
-    if (move.bonus)
-      alert(move.bonus); //TODO: nicer display
-    this.tryMoveFollowup(move, (nextMove) => {
-      if (nextMove)
-        this.playPlusVisual(nextMove, r);
-      else
+    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
+      this.animate(move, nextLines);
   }
 
 };