【问题标题】:Recursive Function in Minesweeper扫雷中的递归函数
【发布时间】:2017-06-13 21:20:11
【问题描述】:

我目前正在为一个学校项目编写扫雷游戏的代码,但我被困在我们显示用户想要的地雷的部分,如果它是 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);
         }
      }
   }
}

【问题讨论】:

  • 你能告诉我们你是如何声明(和初始化)Board的吗?
  • if (row &lt;= 0 || row &gt;= board-&gt;num_rows + 1 看起来代码从 1 开始索引数组。我希望 if (row &lt; 0 || row &gt;= board-&gt;num_rows ... 因为 C 数组索引从 0 开始。
  • 感谢编辑,但是您是如何为the_board 分配内存的?
  • 您没有为列分配足够的内存:board-&gt;the_board[row] = malloc(board-&gt;num_cols * sizeof(Tile)); 应该是 board-&gt;the_board[row] = malloc((board-&gt;num_cols + 2)* sizeof(Tile));

标签: c


【解决方案1】:

据我了解,您一直在关注这个问题一段时间,并在董事会周围添加了一个空白,但这仍然不起作用。也许这个提示会帮助你解决这个问题。我不认为添加边距是一个好主意,您绝对应该尝试不添加边距,但是,嘿,这是您的应用程序。

包括边距,你的棋盘是一个二维数组,索引 [0..cols+2)[0..rows+2)

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

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

【讨论】:

  • 类似的 cmets 也适用于分配的行数。然后是索引负行号的有趣问题 - 再次存储在结构中的值是什么?
  • 它应该是 2 位,带有可见性标志和地雷标志,但这是完全不同的故事。不过,我不认为这个网站的目的是做别人的功课。
猜你喜欢
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多