C语言简单小游戏扫雷
时间: 2024-05-26 22:07:33 浏览: 168
扫雷是一款非常经典的小游戏,它最早是在Windows系统中自带的游戏之一,也是很多人在电脑上消磨时间的首选游戏之一。下面是一个简单的C语言实现的扫雷游戏的例子。
实现思路:
1. 定义一个二维数组存储地图信息(数字代表周围雷数,'X'代表地雷)
2. 随机生成若干个地雷坐标并将地雷位置存入地图数组
3. 循环读入玩家输入的坐标,如果输入的坐标为地雷,则游戏结束,否则显示周围雷数并继续游戏
4. 判断游戏是否胜利,若胜利则结束游戏
下面是简单的代码实现,仅供参考:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 9
#define COL 9
#define MINE_NUM 10
void InitMap(char map[][COL], int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
map[i][j] = '0';
}
}
}
void PrintMap(char map[][COL], int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%c ", map[i][j]);
}
printf("\n");
}
}
void SetMine(char map[][COL], int row, int col)
{
int i, j, k;
int x, y;
srand(time(NULL));
for (k = 0; k < MINE_NUM; k++)
{
do
{
x = rand() % row;
y = rand() % col;
} while (map[x][y] == 'X');
map[x][y] = 'X';
}
}
int GetMineCount(char map[][COL], int x, int y)
{
int count = 0;
int i, j;
for (i = x - 1; i <= x + 1; i++)
{
for (j = y - 1; j <= y + 1; j++)
{
if (i >= 0 && i < ROW && j >= 0 && j < COL && map[i][j] == 'X')
{
count++;
}
}
}
return count;
}
void ExpandMap(char mine[][COL], char show[][COL], int x, int y)
{
if (x < 0 || x >= ROW || y < 0 || y >= COL)
{
return;
}
if (show[x][y] != '0')
{
return;
}
show[x][y] = mine[x][y];
if (mine[x][y] == 'X')
{
return;
}
int count = GetMineCount(mine, x, y);
if (count > 0)
{
show[x][y] = count + '0';
return;
}
ExpandMap(mine, show, x - 1, y - 1);
ExpandMap(mine, show, x - 1, y);
ExpandMap(mine, show, x - 1, y + 1);
ExpandMap(mine, show, x, y - 1);
ExpandMap(mine, show, x, y + 1);
ExpandMap(mine, show, x + 1, y - 1);
ExpandMap(mine, show, x + 1, y);
ExpandMap(mine, show, x + 1, y + 1);
}
int IsWin(char mine[][COL], char show[][COL])
{
int i, j;
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
if (mine[i][j] == 'X' && show[i][j] != 'X')
{
return 0;
}
if (mine[i][j] != 'X' && show[i][j] == '0')
{
return 0;
}
}
}
return 1;
}
void PlayGame(char mine[][COL], char show[][COL])
{
int x, y;
while (1)
{
printf("Please input coordinate(x,y): ");
scanf("%d%d", &x, &y);
if (mine[x][y] == 'X')
{
printf("Game Over!\n");
break;
}
ExpandMap(mine, show, x, y);
PrintMap(show, ROW, COL);
if (IsWin(mine, show))
{
printf("You Win!\n");
break;
}
}
}
int main()
{
char mine[ROW][COL];
char show[ROW][COL];
InitMap(mine, ROW, COL);
InitMap(show, ROW, COL);
SetMine(mine, ROW, COL);
PrintMap(mine, ROW, COL);
PlayGame(mine, show);
return 0;
}
```
阅读全文