2017-06-13 141 views
1

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

请阅读[mcve]。 – Stargateur

+0

你能告诉我们你是如何申报(并初始化)'Board'的? –

+0

编辑,谢谢! – mc2017

回答

2

据我所知,你一直追着这个问题了一段时间,并增加了利润率的棋盘上,但是这仍然无法正常工作。也许这个提示会帮助你解决这个问题。我不认为增加利润率是一个好主意,你绝对应该尝试不做,但是,嘿,这是你的应用程序。

包括利润,你的主板是一个二维数组,指数[0..cols + 2)0..rows + 2)

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

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

相似的注释也适用于分配的行数。然后有一个有趣的索引负数行号的问题 - 结构中存储的值又是多少? –

+0

它应该是2bits,有一个可见性标志和一个地雷旗,但这是一个完全不同的故事。不过,我认为这个网站的目的不是为了做别人的功课。 –