Java programming - nested for loops for minesweeper game

允我心安 提交于 2021-01-28 05:28:44

问题


Currently making a minesweeper game and stuck on being able to loop through the 8 surrounding cells to find the number of surrounding bombs. I have a helper method that I believe works fine that is used to check if the cell (passed by numberOfAdjacentBombs) contains a bomb. How do I go about creating a nested for loop that will loop through each surrounding cell? e.g (row-1, col-1), (row-1, col), (row-1, col+1).

Any help or hints is appreciated, thanks! :-)

 private int numberOfAdjacentBombs(int row, int col){
 int count = 0;
 //nested for loop
 count += getIfBomb(int, int)
}

The helper method checks if the cell contains a bomb and returns 1 if it does, 0 if it doesn't.

private in getIfBomb(int row, int col){
 if(cells[row][col].getHasBomb() == true){
  return 1;
}else{
  return 0;
 }
}

回答1:


Without taking into account boundary checks...

You need to check the columns and rows before, the actual column and row and the columns and rows after....

Something like...

row - 1, col - 1
row - 1, col
row - 1, col + 1
row, col - 1
row, col
row, col + 1
row + 1, col - 1
row + 1, col
row + 1, col + 1

Which might look something like...

for (int visitRow = row - 1; visitRow < row + 1; visitRow++) {
    for (int visitCol = col - 1; visitCol < col + 1; visitCol++) {
        count += getIfBomb(visitRow, visitCol)
    }
}

Now, your getIfBomb method is going to need to range check the values it's passed to check that they aren't out of bounds of the array...but I think I can leave that to you...




回答2:


Your grid probably looks a little something like this:

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

What you can do is construct a for loop that iterates from x-1 to x+1 and inside that, another loop from y-1 to y+1 (taking in consideration for edges, of course), and simply skip over the case when you are looking at (x, y):

for(int i = x-1; i <= x+1; i++) { //x-values
    for(int j = y-1; j <= y+1; j++) { //y-values
        if(i != x && j != y) {
            //do your snazzy minesweeper jazz here
        }
    }
}


来源:https://stackoverflow.com/questions/19019531/java-programming-nested-for-loops-for-minesweeper-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!