用c++编程语言写一个扫雷的小游戏
时间: 2023-05-24 21:01:39 浏览: 101
C++实现扫雷小游戏
5星 · 资源好评率100%
好的,我可以帮您写一个扫雷游戏的代码。以下是代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ROW 10
#define MAX_COL 10
#define MINE_NUM 10
void PrintMap(char map[MAX_ROW][MAX_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");
}
}
int CountMine(char map[MAX_ROW][MAX_COL], int row, int col, int x, int y)
{
int i, j, count = 0;
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] == '*')
count++;
}
}
return count;
}
void GenerateMine(char map[MAX_ROW][MAX_COL], int row, int col, int mine_num)
{
int i, j, x, y;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
map[i][j] = '0';
}
}
srand((unsigned int)time(NULL));
for (i = 0; i < mine_num; i++) {
x = rand() % row;
y = rand() % col;
if (map[x][y] == '*') {
i--;
continue;
}
map[x][y] = '*';
}
}
void ExpandMap(char map[MAX_ROW][MAX_COL], int row, int col, int x, int y)
{
int count;
if (map[x][y] != '0')
return;
count = CountMine(map, row, col, x, y);
map[x][y] = count + '0';
if (count == 0) {
if (x > 0) {
ExpandMap(map, row, col, x-1, y);
if (y > 0) ExpandMap(map, row, col, x-1, y-1);
if (y < col-1) ExpandMap(map, row, col, x-1, y+1);
}
if (y > 0) ExpandMap(map, row, col, x, y-1);
if (y < col-1) ExpandMap(map, row, col, x, y+1);
if (x < row-1) {
ExpandMap(map, row, col, x+1, y);
if (y > 0) ExpandMap(map, row, col, x+1, y-1);
if (y < col-1) ExpandMap(map, row, col, x+1, y+1);
}
}
}
int main()
{
char map[MAX_ROW][MAX_COL];
int row = MAX_ROW, col = MAX_COL;
int x, y;
GenerateMine(map, row, col, MINE_NUM);
PrintMap(map, row, col);
while (1) {
printf("Please input coordinate:(x y)");
scanf("%d %d", &x, &y);
if (map[x][y] == '*') {
printf("Game over!\n");
PrintMap(map, row, col);
break;
}
ExpandMap(map, row, col, x, y);
PrintMap(map, row, col);
}
return 0;
}
请问还有什么需要我帮助的吗?
阅读全文