Recursion error in GUI

前端 未结 2 497
天命终不由人
天命终不由人 2021-01-25 05:13

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

2条回答
  •  日久生厌
    2021-01-25 05:50

    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:

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

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

    3. In the loop, set conditions to ensure you are within bounds (of the 3x3 matrix) before reading current grid's value (see code below).

    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.

提交回复
热议问题