-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminesweeper.c
125 lines (108 loc) · 2.84 KB
/
minesweeper.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 20
int board[ROWS][COLS];
int revealed[ROWS][COLS];
void initializeBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = 0;
revealed[i][j] = 0;
}
}
}
void plantMines() {
srand(time(NULL));
for (int i = 0; i < MINES; i++) {
int row = rand() % ROWS;
int col = rand() % COLS;
if (board[row][col] == -1) {
i--;
} else {
board[row][col] = -1;
for (int r = row - 1; r <= row + 1; r++) {
for (int c = col - 1; c <= col + 1; c++) {
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && board[r][c] != -1) {
board[r][c]++;
}
}
}
}
}
}
void reveal(int row, int col) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS || revealed[row][col]) {
return;
}
revealed[row][col] = 1;
if (board[row][col] == 0) {
for (int r = row - 1; r <= row + 1; r++) {
for (int c = col - 1; c <= col + 1; c++) {
reveal(r, c);
}
}
}
}
void displayBoard() {
printf("Current Board:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (revealed[i][j]) {
if (board[i][j] == -1) {
printf("* ");
} else {
printf("%d ", board[i][j]);
}
}else {
printf(". ");
}
}
printf("\n");
}
}
int main() {
printf("-----****------MiNeSwEePeR------****-----\n");
initializeBoard();
plantMines();
while (1) {
displayBoard();
int row, col;
printf("Enter row and column: ");
scanf("%d %d", &row, &col);
if (board[row][col] == -1) {
printf("Game over!\n");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
if(board[i][j]==-1)
{
printf("* ");
}
else{
printf("%d ",board[i][j]);
}
}
printf("\n");
}
break;
}
reveal(row, col);
int revealedCount = 0;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (revealed[i][j]) {
revealedCount++;
}
}
}
if (revealedCount == ROWS * COLS - MINES) {
printf("Congratulations! You win!\n");
break;
}
}
return main();
}