用C++开发一个扫雷游戏
时间: 2024-06-12 20:08:15 浏览: 159
用C++编的扫雷游戏
由于您没有给出具体的要求和限制,以下是一个简单的扫雷游戏的示例代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
int board[ROWS][COLS];
int revealed[ROWS][COLS];
void init_board() {
int i, j, count = 0;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = 0;
revealed[i][j] = 0;
}
}
srand(time(NULL));
while (count < MINES) {
i = rand() % ROWS;
j = rand() % COLS;
if (board[i][j] != -1) {
board[i][j] = -1;
count++;
}
}
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] != -1) {
if (i > 0 && j > 0 && board[i - 1][j - 1] == -1) board[i][j]++;
if (i > 0 && board[i - 1][j] == -1) board[i][j]++;
if (i > 0 && j < COLS - 1 && board[i - 1][j + 1] == -1) board[i][j]++;
if (j > 0 && board[i][j - 1] == -1) board[i][j]++;
if (j < COLS - 1 && board[i][j + 1] == -1) board[i][j]++;
if (i < ROWS - 1 && j > 0 && board[i + 1][j - 1] == -1) board[i][j]++;
if (i < ROWS - 1 && board[i + 1][j] == -1) board[i][j]++;
if (i < ROWS - 1 && j < COLS - 1 && board[i + 1][j + 1] == -1) board[i][j]++;
}
}
}
}
void print_board(int show_all) {
int i, j;
printf(" ");
for (j = 0; j < COLS; j++) {
printf("%d ", j);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%d ", i);
for (j = 0; j < COLS; j++) {
if (show_all || revealed[i][j]) {
if (board[i][j] == -1) {
printf("* ");
} else {
printf("%d ", board[i][j]);
}
} else {
printf(". ");
}
}
printf("\n");
}
}
int check_win() {
int i, j, count = 0;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] != -1 && revealed[i][j]) {
count++;
}
}
}
return count == ROWS * COLS - MINES;
}
int main() {
int x, y, game_over = 0;
init_board();
printf("Welcome to Minesweeper!\n");
do {
print_board(0);
printf("Enter coordinates (x y): ");
scanf("%d %d", &x, &y);
if (x < 0 || x >= ROWS || y < 0 || y >= COLS) {
printf("Invalid coordinates!\n");
} else if (revealed[x][y]) {
printf("Already revealed!\n");
} else {
revealed[x][y] = 1;
if (board[x][y] == -1) {
game_over = 1;
printf("Game over!\n");
print_board(1);
} else {
if (check_win()) {
printf("You win!\n");
print_board(1);
break;
}
}
}
} while (!game_over);
return 0;
}
```
该程序生成一个 $10 \times 10$ 的扫雷游戏板,其中包含 $10$ 个地雷。玩家通过输入坐标来逐个揭开方块,如果揭开的方块是地雷,则游戏结束;否则,揭开的方块会显示数字,表示周围 $8$ 个方块中有多少个是地雷。当所有非地雷方块都被揭开时,游戏胜利。程序运行时,会提示玩家输入坐标,并在每次揭开方块后更新游戏板的状态。当游戏结束时,会显示所有方块的状态。
阅读全文