宏定义地雷个数和地图大小扫雷小游戏`
//二维数组表示地图(用户看到的地图和地雷分布图)
//初始化二维数组 地图每个元素为¥ 地雷布局图,随机生成十个地雷
//打印地图
//输入一个坐标,表示翻开位置(合法性判定)
//判定胜负
// 0 该位置是地雷 游戏结束 打印地雷分布图
// 1 不是地雷 判定是否胜利
// 所有不是地雷的格子翻开为胜
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int menu() {
printf("********************\n");
printf("____________________\n");
printf(" 1 开始游戏\n");
printf(" 0 退出游戏\n");
printf(" 请输入你的选择:");
int n ;
scanf("%d", &n);
return n;
}
#define LEI 10
#define ROW 9
#define COL 9
void init(char show_m[ROW][COL],char mine_m[ROW][COL]) {
//初始化用户地图
for (int row = 0; row < ROW; ++row) {
for (int col = 0; col < COL; ++col) {
show_m[row][col] = '*';
}
}
//初始化地雷分布图
int n = LEI;
for (int row = 0; row < ROW; ++row) {
for (int col = 0; col < COL; ++col) {
mine_m[row][col] = '0';
}
}
while (n) {
//生成两个随机坐标
int row = rand() % ROW;
int col = rand() % COL;
if (mine_m[row][col] == '1') {
continue;
}
mine_m[row][col] = '1';
--n;
}
}
void print(char map[ROW][COL]) {
//前两行
printf(" | ");
for (int i = 0; i < COL; ++i) {
printf("%d ", i);
}
printf("\n");
printf("--|-");
for (int col = 0; col < COL; ++col) {
printf("--");
}
printf("\n");
for (int row = 0; row < ROW; ++row) {
printf(" %d| ",row);
for (int col = 0; col < COL; ++col) {
printf("%c ",map[row][col]);
}
printf("\n");
}
}
void sum_mine_m(int row,int col, char show_m[ROW][COL],
char mine_m[ROW][COL]) {
int count = 0;
if (row - 1 >= 0 && col - 1 >= 0 && mine_m[row][col] == 1) {
count++;
}
if (row - 1 >= 0 && mine_m[row][col] == 1) {
count++;
}
if (col - 1 >= 0 && mine_m[row][col] == 1) {
count++;
}
if ( row + 1 <= ROW && col - 1 >= 0 && mine_m[row][col] == 1) {
count++;
}
if (row - 1 >= 0 && col + 1 <= COL && mine_m[row][col] == 1) {
count++;
}
if (row + 1 <= ROW && mine_m[row][col] == 1) {
count++;
}
if ( col + 1 <= COL && mine_m[row][col] == 1) {
count++;
}
if ( row + 1 <= ROW && col + 1 <= COL && mine_m[row][col] == 1) {
count++;
}
show_m[row][col] = '0' + count;
}
void Game() {
//构建地图
char show_m[ROW][COL];
char mine_m[ROW][COL];
init( show_m, mine_m);
//空格个数
int open = 0;
while (1) {
//打印地图
print(show_m);
//用户输入坐标
printf("请输入一组坐标(行,列):");
int row = 0;
int col = 0;
scanf("%d %d", &row, &col);
//清屏
system("cls");
//判断输入合法性
if (row < 0 || row >= ROW || col < 0 || col >= COL) {
printf("您的输入有误,请重新输入!\n");
continue;
}
if (show_m[row][col] != '*') {
printf("该位置已翻开!请重新输入!\n");
continue;
}
//判定分是否踩雷
if (mine_m[row][col] == 1) {
printf("扫雷失败!\n");
print(mine_m);
break;
}
++open;
//判定游戏胜利
if (open == ROW * COL - LEI) {
printf("恭喜你,游戏胜利!\n");
print(mine_m);
break;
}
//统计周围地雷个数
sum_mine_m(row, col, show_m, mine_m);
}
}
int main() {
srand((unsigned)time(NULL));
while (1) {
int n = menu();
switch (n) {
case 0:
printf("bye bye !\n");
break;
case 1:
Game();
default:
printf("您的输入有误!\n");
}
}
system("pause");
return 0;
}