繁体   English   中英

扫雷递归,stackoverflow

[英]Minesweeper recursion, stackoverflow

因此,我一直在为minesweeper编写一些Java代码。 我正在尝试获取空单元格以递归方式显示它们旁边的重合单元格。 这是执行此操作的功能。

“单元格”是我用于游戏中单元格的按钮。

private void showCells(int x, int y) {

    //checks out of bounds
    if (x >= SIZE || y >= SIZE || x <= 0 || y <= 0) {
        return;
    }

    //function to look at each surrounding cell and see if it is a mine, 
    //has nMines as a global variable to keep track of the number of mines
    findMines(x, y);

    //if there are mines around the cell that was selected
    if (nMines > 0) {

        //set the text of that cell to the number of mines around it
        cell[x][y].setText(String.valueOf(nMines));

        //if cell is not already disabled, disable it
        if (!cell[x][y].isDisabled()) {
            cell[x][y].setDisable(true);
        }
    } else {

        //if there are no mines, recursively show the surrounding mines
        showCells(x + 1, y);
        showCells(x - 1, y);
        showCells(x, y + 1);
        showCells(x, y - 1);
    }

    //resets the mine count for the next search
    nMines = 0;
}

我知道就功能而言,我的代码还有其他问题,但是我正在设法弄清楚这件事。 调试时发生的情况是,当我到达“ x”边界的末尾时,它返回,但随后立即跳入下一个递归调用,该调用将其移到相同的“ x”位置。

showCells(x + 1, y);
showCells(x - 1, y);

我想知道我需要哪种类型的限定词,以及在哪里放置它以确保它不会在同一位置两次搜索。 提前致谢!

您正在创建一个无限循环,因为每个单元格都会重复到每个相邻的单元格,然后每个空单元格都会重新回到原始单元格,依此类推。

您可以通过在第一个if语句中添加条件来解决此问题:

if (x >= SIZE || y >= SIZE || x <= 0 || y <= 0 || cell[x][y].isDisabled()) {
    return;
}

由于有一个方便的功能,称为短路功能 ,如果xy超出范围,则对isDisabled()的检查甚至不会引发错误,因为它将永远不会被评估。

编辑:要回答关于将setDisabled(true)放在哪里的后续操作-您总是想在单击它后禁用一个单元格,对吗? 因此,将其放在if语句之前的findMines()下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM