【发布时间】: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 <= 0 || row >= board->num_rows + 1看起来代码从 1 开始索引数组。我希望if (row < 0 || row >= board->num_rows ...因为 C 数组索引从 0 开始。 -
感谢编辑,但是您是如何为
the_board分配内存的? -
您没有为列分配足够的内存:
board->the_board[row] = malloc(board->num_cols * sizeof(Tile));应该是board->the_board[row] = malloc((board->num_cols + 2)* sizeof(Tile));
标签: c