扫雷随机生成地雷算法不正确

Minesweeper randomly generating mines algorithm incorrect

我知道,我知道。这已经被问过很多次了。我不是在寻找算法。我认为我的算法工作不正常。

这是我使用的算法:

public void onFirstMove (int moveX, int moveY) {
    setFirstMove (false);
    Random r = new Random ();

    for (int i = 0 ; i < 10 ; i++) {
        int x;
        int y;
        do {
            x = r.nextInt (9);
            y = r.nextInt (9);
        } while (tileMatrix[x][y].hasMine () &&
                moveX == x && moveY == y);

        tileMatrix[x][y].setMine ();
    }

    timer.startTimer ();
}

我把它放在onFirstMove 方法中,因为我不想让玩家在第一次移动时就输了。正如你所看到的,我让它一直试图找到 x 和 y 坐标,而它与第一步的位置相同。

while (tileMatrix[x][y].hasMine () &&
                moveX == x && moveY == y);

现在它有 2 个已知错误:

  1. 它有时会生成 9 个地雷而不是 10 个。我知道这一点是因为当我失败时,它会显示所有地雷所在的位置。

  2. 有时在第一步的位置产生地雷

错误出现在您的 while 条件中。应该是:

while (tileMatrix[x][y].hasMine () ||    // OR not AND
                (moveX == x && moveY == y));

我同意 xashru 的回答(1+)。我自己,我会使用一个列表,将除第一个移动方块之外的所有方块添加到列表中,将其洗牌,然后 select 前 N 个方块(N 是地雷的数量,并设置地雷。例如,类似于:

public void onFirstMove (int moveX, int moveY) {
    setFirstMove (false);

    // assuming your tiles are of type Tile
    List<Tile> tileList = new ArrayList<>();
    for (int x = 0; x < MAX_X; x++) {
        for (int y = 0; y < MAX_Y; y++) {
            if (x != moveX || x != moveY) {
                // add all tile's except the first move
                tileList.add(tileMatrix[x][y]);
            }
        }
    }

    // randomize the collection
    java.util.Collections.shuffle(tileList);

    // set MAX_MINES tiles to have mines
    for (int i = 0; i < MAX_MINES; i++) {
        tileList.get(0).setMine();
    }
    timer.startTimer();
}

更多扫雷"fun",请查看我的代码并回答this MineSweeper Question