扫雷游戏的C语言代码实现
时间: 2023-08-28 18:04:54 浏览: 114
下面是一个简单的扫雷游戏的 C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define EASY_COUNT 10
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);
void DisplayBoard(char board[ROWS][COLS], int row, int col);
void SetMine(char board[ROWS][COLS], int row, int col);
int GetMineCount(char board[ROWS][COLS], int x, int y);
int main()
{
char board[ROWS][COLS] = {0};
int win = 0;
int x, y;
int count = 0; // 用来记录玩家已经排除了多少非雷格子
InitBoard(board, ROWS, COLS, '*');
SetMine(board, ROW, COL);
DisplayBoard(board, ROW, COL);
while (1)
{
printf("请输入排除非雷格子的坐标(x,y): ");
scanf("%d,%d", &x, &y);
if (x < 1 || x > ROW || y < 1 || y > COL)
{
printf("坐标非法,请重新输入!\n");
continue;
}
if (board[x][y] != '*')
{
printf("该位置已经排除,请重新输入!\n");
continue;
}
if (board[x][y] == '1' || board[x][y] == '2' || board[x][y] == '3' || board[x][y] == '4' || board[x][y] == '5' || board[x][y] == '6' || board[x][y] == '7' || board[x][y] == '8')
{
printf("该位置周围已经有 %c 个雷,请重新输入!\n", board[x][y]);
continue;
}
if (board[x][y] == '#')
{
printf("你踩到雷了,游戏结束!\n");
break;
}
int mine_count = GetMineCount(board, x, y);
count++;
if (count == ROW * COL - EASY_COUNT)
{
printf("你赢了,游戏结束!\n");
break;
}
board[x][y] = mine_count + '0';
DisplayBoard(board, ROW, COL);
}
return 0;
}
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
board[i][j] = set;
}
}
}
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
int i, j;
for (i = 1; i <= row; i++)
{
for (j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void SetMine(char board[ROWS][COLS], int row, int col)
{
int count = EASY_COUNT;
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (board[x][y] == '*')
{
board[x][y] = '#';
count--;
}
}
}
int GetMineCount(char board[ROWS][COLS], int x, int y)
{
return board[x - 1][y - 1] + board[x - 1][y] + board[x - 1][y + 1] + board[x][y - 1] + board[x][y + 1] + board[x + 1][y - 1] + board[x + 1][y] + board[x + 1][y + 1] - 8 * '*';
}
```
该代码实现的扫雷游戏是一个简单的版本,只支持输入坐标进行排雷操作,不支持扫雷标记、双击打开周围格子等高级功能。如果需要实现这些高级功能,可以在该代码的基础上进行扩展。
阅读全文