用C语言写一个扫雷小游戏
时间: 2023-12-29 20:17:50 浏览: 107
好的,下面是一个简单的扫雷小游戏,使用C语言编写。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 9
#define COLS 9
#define MINE_NUM 10
void init_board(char board[][COLS], int rows, int cols, char ch);
void print_board(char board[][COLS], int rows, int cols);
void set_mine(char board[][COLS], int rows, int cols, int mine_num);
void get_mine_count(char board[][COLS], int rows, int cols, int row, int col, int *count);
int main()
{
char board[ROWS][COLS];
int row, col, count;
char ch;
srand((unsigned int)time(NULL));
init_board(board, ROWS, COLS, ' ');
set_mine(board, ROWS, COLS, MINE_NUM);
printf("Welcome to Minesweeper!\n");
printf("You have %d mines to find.\n", MINE_NUM);
do {
print_board(board, ROWS, COLS);
printf("Enter a row and a column: ");
scanf("%d %d", &row, &col);
if (board[row][col] != ' ') {
printf("This cell has already been opened.\n");
}
else {
get_mine_count(board, ROWS, COLS, row, col, &count);
if (count == -1) {
printf("Game over! You hit a mine.\n");
board[row][col] = '*';
print_board(board, ROWS, COLS);
break;
}
else {
board[row][col] = count + '0';
if (count == 0) {
int i, j;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS && board[i][j] == ' ') {
get_mine_count(board, ROWS, COLS, i, j, &count);
board[i][j] = count + '0';
}
}
}
}
}
}
} while (ch != 'q');
return 0;
}
void init_board(char board[][COLS], int rows, int cols, char ch)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
board[i][j] = ch;
}
}
}
void print_board(char board[][COLS], int rows, int cols)
{
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++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void set_mine(char board[][COLS], int rows, int cols, int mine_num)
{
int i, j, count = 0;
while (count < mine_num) {
i = rand() % rows;
j = rand() % cols;
if (board[i][j] == ' ') {
board[i][j] = 'X';
count++;
}
}
}
void get_mine_count(char board[][COLS], int rows, int cols, int row, int col, int *count)
{
int i, j;
*count = 0;
if (board[row][col] == 'X') {
*count = -1;
}
else {
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < rows && j >= 0 && j < cols && board[i][j] == 'X') {
(*count)++;
}
}
}
}
}
```
这个扫雷小游戏使用字符数组来存储游戏面板,其中空格表示未开启的格子,数字表示周围的地雷数量,'X'表示地雷,'*'表示被炸到的地雷。
游戏开始时先调用init_board函数将所有格子初始化为' ',然后调用set_mine函数随机设置地雷。
玩家每次输入一个坐标,程序判断该格子是否已经被开启,如果没有就计算周围地雷数量,如果是地雷则游戏结束,否则将该格子的值设为周围地雷数量,如果周围没有地雷则递归展开周围的格子,直到周围有地雷为止。
最后一种情况是玩家输入'q'退出游戏。
阅读全文