1 | /* ncurses-minesweeper Copyright (c) 2020 Joshua 'joshuas3' Stockin |
2 | * <https://joshstock.in> |
3 | * <https://github.com/JoshuaS3/ncurses-minesweeper> |
4 | * |
5 | * This software is licensed and distributed under the terms of the MIT License. |
6 | * See the MIT License in the LICENSE file of this project's root folder. |
7 | * |
8 | * This comment block and its contents, including this disclaimer, MUST be |
9 | * preserved in all copies or distributions of this software's source. |
10 | */ |
11 |
|
12 | #include <stdlib.h> |
13 | #include <time.h> |
14 |
|
15 | #include "../state.h" |
16 | #include "nearest_cells.h" |
17 |
|
18 | void begin_game(game_board *board) { |
19 | // open start |
20 | uint16_t s = board->current_cell; |
21 |
|
22 | int16_t *open_start_cells = list_nearby_cells(board, s); |
23 |
|
24 | for (int cell = 0; cell < 9; cell++) { |
25 | board->cells[open_start_cells[cell]].opened = 1; |
26 | board->cells[open_start_cells[cell]].is_bomb = 0; |
27 | } |
28 |
|
29 | // generate mines |
30 | int mines_generated = 0; |
31 | uint16_t end = board->width * board->height; |
32 |
|
33 | srand(time(NULL)); |
34 |
|
35 | while (mines_generated < board->mine_count) { |
36 | int n = rand() % (end - 1); |
37 | game_board_cell *x = &board->cells[n]; |
38 | if (!x->is_bomb && !x->opened) { |
39 | x->is_bomb = 1; |
40 | mines_generated++; |
41 | } |
42 | } |
43 |
|
44 | // get and label surrounding mine counts |
45 | for (int i = 0; i < end; i++) { |
46 | if (board->cells[i].is_bomb) continue; |
47 | int16_t *close_cells = list_nearby_cells(board, i); |
48 | for (int j = 0; j < 9; j++) { |
49 | int16_t close_cell = close_cells[j]; |
50 | if (close_cell != i && board->cells[close_cell].is_bomb) board->cells[i].surrounding_bomb_count++; |
51 | } |
52 | free(close_cells); |
53 | } |
54 |
|
55 | // recursively open start area |
56 | for (int cell = 0; cell < 9; cell++) { |
57 | if (board->cells[open_start_cells[cell]].surrounding_bomb_count == 0) |
58 | recursively_open_nearby_cells(board, open_start_cells[cell]); |
59 | } |
60 | free(open_start_cells); |
61 |
|
62 | // start timer |
63 | board->time = time(NULL); |
64 |
|
65 | board->status = Playing; |
66 | } |
67 |
|