minesweeper.c (2240B)
1 #include "minesweeper.h" 2 3 void 4 init_db(Board *b) 5 { 6 int i; 7 b->db = (char **)malloc(b->rows * sizeof(char *)); 8 for (i = 0; i < b->rows; i++) 9 b->db[i] = (char *)malloc(b->cols); 10 11 if (b->mb == NULL) die(); 12 else fill_db(b); 13 } 14 15 void 16 fill_db(Board *b) 17 { 18 int i, j; 19 for (i = 0; i < b->rows; i++) 20 for (j = 0; j < b->cols; j++) 21 b->db[i][j] = BLANK; 22 } 23 24 void 25 init_mb(Board *b) 26 { 27 int i; 28 b->mb = (char **)malloc(b->rows * sizeof(char *)); 29 for (i = 0; i < b->rows; i++) 30 b->mb[i] = (char *)malloc(b->cols); 31 32 if (b->mb == NULL) die(); 33 else 34 { 35 place_mines(b); 36 add_adj(b); 37 fill_spaces(b); 38 } 39 } 40 41 void 42 place_mines(Board *b) 43 { 44 int i, r, c; 45 srand(time(NULL)); 46 for (i = 0; i < b->nmines; i++) 47 { 48 r = rand() % b->rows; 49 c = rand() % b->cols; 50 b->mb[r][c] = MINE; 51 } 52 } 53 54 void 55 add_adj(Board *b) 56 { 57 int i, j; 58 for (i = 0; i < b->rows; i++) 59 for (j = 0; j < b->cols; j++) 60 if (!is_mine(b, i, j)) 61 b->mb[i][j] = adj_mines(b, i, j) + '0'; 62 } 63 64 int 65 is_mine(const Board *b, int r, int c) 66 { 67 return (b->mb[r][c] == MINE) ? TRUE : FALSE; 68 } 69 70 int 71 outof_bounds(const Board *b, int r, int c) 72 { 73 return (r < 0 || r > b->rows-1 || c < 0 || c > b->cols-1) ? TRUE : FALSE; 74 } 75 76 uint8_t 77 adj_mines(const Board *b, int r, int c) 78 { 79 uint8_t nadj = 0; 80 81 if (!outof_bounds(b, r, c-1) && b->mb[r][c-1] == MINE) nadj++; // North 82 if (!outof_bounds(b, r, c+1) && b->mb[r][c+1] == MINE) nadj++; // South 83 if (!outof_bounds(b, r+1, c) && b->mb[r+1][c] == MINE) nadj++; // East 84 if (!outof_bounds(b, r-1, c) && b->mb[r-1][c] == MINE) nadj++; // West 85 if (!outof_bounds(b, r+1, c-1) && b->mb[r+1][c-1] == MINE) nadj++; // North-East 86 if (!outof_bounds(b, r-1, c-1) && b->mb[r-1][c-1] == MINE) nadj++; // North-West 87 if (!outof_bounds(b, r+1, c+1) && b->mb[r+1][c+1] == MINE) nadj++; // South-East 88 if (!outof_bounds(b, r-1, c+1) && b->mb[r-1][c+1] == MINE) nadj++; // South-West 89 90 return nadj; 91 } 92 93 void 94 fill_spaces(Board *b) 95 { 96 int i, j; 97 for (i = 0; i < b->rows; i++) 98 for (j = 0; j < b->cols; j++) 99 if (b->mb[i][j] != MINE && b->mb[i][j] == '0') 100 b->mb[i][j] = '-'; 101 } 102 103 void 104 die(void) 105 { 106 mvprintw(0, 0, "Error, cannot allocate memory, exiting..."); 107 refresh(); 108 exit(EXIT_FAILURE); 109 }