I am creating a simple 9x9 grid for Minesweeper. One of the primary functions of this game is to have a recursion to check all the sides when the tile clicked has no bombs surro
One of the primary functions of this game is to have a recursion to check all the sides when the tile clicked has no bombs surrounding it.
Looks like you are stucked on the part where you need to update the cell with number according to the number of bombs surrounding it.
These are the things for you to take note:
To update the numbers on the cells, there is no need to use recursion. The only part I used recursion is when user clicks on a cell with value == 0
(stepped on an empty grid).
Checking all 8 directions can be done easily without writing large number of if-conditions
. All you need is a pair of nested for-loop
. Just traverse the 3x3
grid like a 2D array (see diagram below for illustration).
To traverse the 3x3
matrix as shown in the diagram, we can use a pair of nested loops:
for(int x=(coordX-1); x<=(coordX+1); x++)
for(int y=(coordY-1); y<=(coordY+1); y++)
if(x!=-1 && y!= -1 && x! = ROWS && y! = COLS && map[x][y] != 'B')
if(map[x][y] == '.')
map[x][y] = '1';
else
map[x][y] += 1;
The if-condition
prevents working on array element which is out of bounds.