简体   繁体   中英

Java programming - nested for loops for minesweeper game

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? eg (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;
 }
}

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...

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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