我目前正在编写一个学校项目的扫雷游戏编码,但是我被困在了我们揭示用户需要的地雷的部分,如果它是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);
}
}
}
}
请阅读[mcve]。 – Stargateur
你能告诉我们你是如何申报(并初始化)'Board'的? –
编辑,谢谢! – mc2017