基本流程:
1. 创建用户交互菜单
2.创建地图并初始化;
3.打印地图;
4.程序读取玩家要翻的坐标并校验;
5.判断该位置的坐标是否有地雷,如果有地雷,则游戏结束;
6.如果不是地雷, 统计当前位置周围雷的个数, 并显示到地图上;
7.判定游戏是否胜利。
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#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 StartGame();
void InitBoard(char board[ROWS][COLS], int row, int col, char set);
void SetMine(char mine[ROWS][COLS], int row, int col);
void DisplayBoard(char board[ROWS][COLS], int row, int col);
void FindMine(char mine[ROWS][COLS],char show[ROWS][COLS], int row, int col);
int GetMineCount(char mine[ROWS][COLS], int x, int y);
int main(int argc, char* argv[])
{
int select = 1;
while (select)
{
printf("*******扫雷小游戏*******\n");
printf("* 1.Play *\n");
printf("* 0.Exit *\n");
printf("************************\n");
printf("请输入你的选择:>");
scanf("%d", &select);
if (select == 0)
break;
if (select != 1)
{
printf("输入有误,请重新输入...\n");
continue;
}
StartGame();
}
printf("退出游戏,欢迎下次使用...\n");
return 0;
}
void StartGame()
{
char show[ROWS][COLS];
char mine[ROWS][COLS];
//初始化棋盘
InitBoard(mine, ROWS, COLS, '0');//字符0代表无雷,1代表雷
InitBoard(show, ROWS, COLS, '*');
//埋雷
SetMine(mine, ROW, COL);
//显示棋盘
DisplayBoard(show, ROW, COL);
//扫雷
FindMine(mine, show, ROW, COL);
}
void InitBoard(char board[ROWS][COLS], int row, int col, char set)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
board[i][j] = set;
}
}
}
void SetMine(char mine[ROWS][COLS], int row, int col)
{
int count = EASY_COUNT;
srand(time(0));
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (mine[x][y] == '0')
{
mine[x][y] = '1';
count--;
}
}
}
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
for (int i = 0; i <= col; i++)
printf("%d ", i);
printf("\n");
for (int i = 1; i <= row; i++)
{
printf("%d ", i);
for (int j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int win = 0;
int x, y;
while (win < col * row - EASY_COUNT)
{
printf("请输入排雷的位置:>");
scanf("%d %d", &x, &y);
if ((x >= 1 && x <= row) && (y >= 1 && y <= col))
{
if (mine[x][y] == '1')
{
DisplayBoard(mine, ROW, COL);
printf("很遗憾,排雷失败,你被炸糊了...\n");
break;
}
int n = GetMineCount(mine, x, y);
show[x][y] = n + '0';
system("cls");
DisplayBoard(show, ROW, COL);
win++;
}
else
printf("非法输入,请重新输入...\n");
}
if (win >= col * row - EASY_COUNT)
{
printf("恭喜你,排雷成功...\n");
DisplayBoard(mine, ROW, COL);
}
}
int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
return mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1]
+ mine[x][y - 1] + mine[x][y + 1] +
mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - (8 * '0');
}