mc2017 mc2017 -4 years ago 51
C Question

Recursive Function in Minesweeper

I'm currently working on coding the game of minesweeper for a school project, but I'm stuck on the part where we reveal the mine that the user wants and if it's a 0, reveal all the mines around it, and so on. I made my game board 2 rows and columns larger than what the actual user-specified game board size should be so that I have a border around it to count the number of mines around edge cases. (num_rows and num_cols are the dimensions that the board actually should be)

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


The code that I posted below always results in segmentation error. I think that it's a problem with when I run into the border. Anyone have any suggestions? Sorry if the code is really bad/hard to read. I'm a beginner to C and programming in general. Thanks in advance!

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);
}
}
}
}

Answer Source

From what I understand, you've been chasing this issue for a while and added a margin around the board, but this still doesn't work. Maybe this hint will help you sort this out. I don't think adding margins is a good idea, you should definitely try to do without but, hey, it's your app.

including the margins, your board is a 2d array, indices [0..cols+2)[0..rows+2)

So, you initial row allocation in CreateBoard() is wrong, your rows are too short by 2 units.

(Tile*)malloc(board->num_cols * sizeof(Tile));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download