我为我的Java扫雷游戏编写了此方法,该方法应该检查一组坐标周围的点,然后计算附近有多少枚炸弹。

public void numberMines(){
    int count = 0;
    int x = 0;
    int y = 0;
    int xMin = x-1;
    int xMax = x+1;
    int yMin = y-1;
    int yMax = y+1;
    if (x == 0){
        xMin = 0;
    }
    if (y == 0){
        yMin = 0;   //these restrictions take care of the spots in the edges
    }
    if (x == rows){
        xMax = rows;
    }
    if (y == columns){
        yMax = columns;
    }
    //first 2 loops go through every spot on the board
    for (x=0; x<rows; x++){
        for (y=0; y<columns; y++){
            //if the spot selected is not a bomb, for loops check spaces surrounding it
            if (mineBoard[x][y] != bomb){
                for (int i = xMin; i <=xMax; i++){
                    for (int j = yMin; j <=yMax; j++){
                        if (mineBoard[i][j] == bomb){
                            count++;
                        }
                    }
                }
            }

            if (count > 0){       //converts them characters
                mineBoard[x][y] = (char)(count + '0');
                count = 0;
            }
         }
    }
}


每次我运行此方法时,它都会返回3、2、1或为空,因此它会计算周围有多少枚炸弹,但是由于某种原因,它会循环循环,并在第一个炸弹之后的每个非炸弹点返回相同的东西一。我真的看不到我搞砸了,请帮忙!

最佳答案

移动以下代码块:

int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
    xMin = 0;
}
if (y == 0){
    yMin = 0;   //these restrictions take care of the spots in the edges
}
if (x == rows){
    xMax = rows;
}
if (y == columns){
    yMax = columns;
}


在您的for循环中:

for (x=0; x<rows; x++){
    for (y=0; y<columns; y++){
       //Insert code here <---


因为目前,您只需要对x = 0,y = 0进行一次这些计算。



如果在counti,循环之前将j的设置移动到0,并且在所有循环开始之前不进行一次设置,然后又在显示结果。



根据您的评论-我认为您的有效索引范围是0..(rows-1)0..(columns-1)-因此您也遇到了篱笆墙错误。修改这些行:

if (x == rows-1){
    xMax = rows-1;
}
if (y == columns-1){
    yMax = columns-1;
}


但是,您的x / y循环中仍应包含整个块。当它们不在外面时,您不会出现超出范围的错误,因为当xMaxyMax处于最大值时,您永远不会计算xy

关于java - Java minesweeper方法在炸弹周围添加数字无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10186767/

10-10 14:57