0

我为我的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,或者是空的,所以它会计算周围有多少炸弹,但由于某种原因,它过度循环并在第一个之后的每个不是炸弹的地方都返回相同的东西一。我真的看不到我搞砸了,请帮助!

4

2 回答 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。


如果您将, , 循环count之前的设置移动到 0并且在所有循环开始之前没有完成一次,并且再次在显示结果的条件内完成,那么代码可能看起来也更清晰。ij


根据您的评论 - 我认为您的有效索引范围为0..(rows-1)-0..(columns-1)所以您也有一个栅栏错误。修改这些行:

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

但是仍然在x/y循环中保留整个块。当它们在外面时,您不会得到超出范围的错误,因为您从不计算xMax以及yMax何时x以及y它们处于最大值。

于 2012-04-17T07:17:05.700 回答
0

避免在方法的开头声明所有变量,最好在接近使用时声明它们。要解决您的问题,您需要在循环中计算计数、xMin、xMax、yMin 和 yMax,如下所示:

public void numberMines(){
    //first 2 loops go through every spot on the board
    for (int x=0; x<rows; x++){
        for (int y=0; y<columns; y++){
            int count = 0;
            //if the spot selected is not a bomb, for loops check spaces surrounding it
            if (mineBoard[x][y] != bomb){
                for (int i = (x == 0 ? 0 : x-1); i <= (x == rows ? rows : x+1); i++){
                    for (int j = (y == 0 ? 0 : y-1); j <= (y == rows ? rows : y+1); j++){
                        if (mineBoard[i][j] == bomb){
                            count++;
                        }
                    }
                }
            }

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

我已经内联了边界检查,这不是必需的,但会使代码更短,以便在此处显示。

于 2012-04-17T07:19:55.233 回答