制作一个 java 2048 游戏,滑动时它经过循环的次数超过应有的次数,并命中 tests/alters 个已经改变的数字

Making a java 2048 game, upon sliding it goes through the loop more times than it should and hits tests/alters numbers already altered

所以我有一个可靠的滑动功能,问题是(这很难解释!)它遍历了所有可能性,包括二维数组中已经添加在一起的空间:假设有一个设置this: 4,4,8,2 ---向右滑动一次后,结果如下:,_,16,2。然而在实际游戏中,向右滑动一次后,它应该是这样的:___,8,2.

基本上,我该如何解决这个问题?你不需要告诉我代码,这是我的期末项目,但我想得到一些关于为什么会这样的解释。

我试图从右到左遍历数组,但这导致数字甚至没有移动。

   processUserChoice(String i) {
    if (i.equals("d")) {
     while ((slideRight())) {
      moveRight();
     }
    }
    printBoard();
   }

   public boolean slideRight() {
    for (int i = 0; i < board.length; i++) {
     for (int j = 0; j < board[i].length - 1; j++) {
      if (board[i][j + 1] == 0 && board[i][j] != 0) {
       return true;
      } else if (board[i][j + 1] == board[i][j] && board[i][j] != 0) {
       return true;
      }
     }
    }
    return false;
   }
   public void moveRight() {
    for (int i = 0; i < board.length; i++) {
     for (int j = 0; j < board[i].length - 1; j++) {
      if (board[i][j + 1] == 0 && board[i][j] != 0) {
       board[i][j + 1] = board[i][j];
       board[i][j] = 0;
      } else if (board[i][j + 1] == board[i][j] && board[i][j] != 0) {
       board[i][j + 1] = board[i][j + 1] + board[i][j];
       board[i][j] = 0;
      }
     }
    }
    //checkLose();
   }

向右滑动一次后,它应该是这样的:“___,8,2”(来自前面的示例)。

我以前做过类似的事情。我会以与您现在几乎相同的方式来做,但是添加一个布尔数组来检查图块是否发生碰撞,并且只合并没有发生碰撞的图块。

class Tile {
    public int value;
    public Boolean collided;

    public Tile(int value) {
        this.value = value;
        collided = false;
    }

    public Tile attemptMerge(Tile target) {
        if (target.value == value) {
            Tile t = new Tile(value * 2);
            t.collided = true;
            return t;
        } else {
            return null;
        }
    }

    public void reset() {
        value = 0;
        collided = false;
    }
}

主更新循环中的某处:

void slideRight() {
    for (int row = 0; row < 4; row++) {
        for (int column = 3; column >= 0; column--) {
            Tile current = board[row][column];

            if (current.value == 0) continue;

            for (int slot = column + 1; slot < 3; slot++) {
                Tile target = board[row][slot];

                if (target.value == 0) {
                    target.value = current.value;
                    current = target;
                    board[row][slot - 1].reset();
                } else if (target.value == current.value) {
                    Tile product = target.merge(current);

                    if (!target.collided && !current.collided) {
                        current = product;
                        board[row][slot - 1].reset();
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }
}

我相信按照这些思路应该可以奏效。逻辑有问题请见谅