扫雷中的递归函数

时间:2017-06-13 21:20:12

标签: c

我目前正致力于为学校项目编写扫雷游戏,但我仍然坚持我们揭示用户想要的矿山的部分,如果它是0,则显示周围的所有地雷,等等。我制作的游戏板比实际用户指定的游戏板尺寸大2行和列大,以便我有一个边框来计算边缘情况下的地雷数量。 (num_rows和num_cols是董事会实际应该的维度)

x x x x x x x   Quick illustration of what my board looks like.
x . . . . . x   '.' in this picture represent tiles of the actual game 
x . . . . . x   board while 'x' is the border around it
x . . . . . x
x . . . . . x
x x x x x x x

我在下面发布的代码总是导致分段错误。我认为,当我遇到边境时,这是一个问题。有人有什么建议吗?对不起,如果代码非常糟糕/难以阅读。我是C和编程的初学者。提前谢谢!

typedef struct Tile_struct {  //board struct definitions
       int visibility;
       int num_mines_around;
    } Tile;


typedef struct Board_struct {
   int num_rows;
   int num_cols;
   int num_mines;
   Tile** the_board;
} Board;

//This is how I allocated memory for the board
void CreateBoard(char** argv, Board* board) {

   int row, col;

   board->num_rows = atoi(argv[1]);
   board->num_cols = atoi(argv[2]);
   board->num_mines = atoi(argv[3]);

   board->the_board = (Tile**)malloc(board->num_rows * sizeof(Tile*));

   for (row = 0; row < (board->num_rows) + 2; row++) {

      board->the_board[row] = (Tile*)malloc(board->num_cols * 
      sizeof(Tile));

      for (col = 0; col < (board->num_cols) + 2; col++) {

          board->the_board[row][col].visibility = 0;  //hide all tiles
      }
    }
 } 

void RevealTiles(Board* board, int row, int col) {    

   int i, j;

   if (row <= 0 || row >= board->num_rows + 1 || col <= 0 || col >= 
board->num_cols + 1) {
      return;
   }
   else if (board->the_board[row][col].num_mines_around != 0) { 
      board->the_board[row][col].visibility = 4;  //reveal that tile
   }
   else {
      board->the_board[row][col].visibility = 4;
      for (i = row - 1; i <= row + 1; i++) {
         for (j = col - 1; j <= col + 1; j++) {
            if (i == row && j == col) {
               continue;
            }
            RevealTiles(board, i, j);
         }
      }
   }
}

1 个答案:

答案 0 :(得分:2)

根据我的理解,你一直在追逐这个问题,并在董事会中增加了一个余量,但这仍然不起作用。也许这个提示可以帮助你解决这个问题。我不认为添加保证金是一个好主意,你绝对应该尝试没有,但是,嘿,这是你的应用程序。

包括边距,你的板是2d数组,索引[0..cols + 2] [0..rows + 2]

因此,您在CreateBoard()中的初始行分配是错误的,您的行太短2个单位。

(Tile*)malloc(board->num_cols * sizeof(Tile));