1.game.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROWS 11//由边角需要排查雷的个数,所以扩大棋盘的边界,得到边界的炸弹数
#define CLOS 11
#define ROW 9//9行9列的棋盘
#define CLO 9
#define MINE_NUMBER 10
//棋盘的初始化
void Init_board(char board[ROWS][CLOS], int rows, int clos, char set);
//打印棋盘
void Print_board(char board[ROWS][CLOS], int rows, int clos);
//布置雷
void Setmine(char board[ROWS][CLOS], int row, int clo);
//排查雷
void find_mine(char mine[ROWS][CLOS], char show[ROWS][CLOS], int row, int clo);
2.tase.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void nume()//游戏菜单
{
printf("************************\n");
printf("****** 1.play ******\n");
printf("****** 0.exit ******\n");
printf("************************\n");
}
void income()//进入游戏
{
char mine[ROWS][CLOS] = { 0 };//布置雷
char show[ROWS][CLOS] = { 0 };//查出的雷
//棋盘的初始化
Init_board(mine, ROW, CLO, '0');
Init_board(show, ROW, CLO, '*');
//打印棋盘
Print_board(show, ROW, CLO);
//布置雷
Setmine(mine, ROW, CLO);
//Print_board(mine, ROW, CLO);
//排查雷
find_mine(mine, show, ROW, CLO);
}
void game()
{
nume();
srand((unsigned int)time(NULL));
int input = 0;
printf("请选择>:");
do
{
scanf("%d", &input);
switch (input)
{
case 1:
printf("扫雷游戏:\n");
income();
nume();
break;
case 0:
printf("退出游戏:\n");
break;
default:
printf("选择错误,请重新选择\n");
break;
}
} while (input);
}
int main()
{
game();//开始游戏
return 0;
}
3.game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
//布置两个棋盘,用一个来显示棋盘的炸弹信息,另一个来显示炸弹的位置
void Init_board(char board[ROWS][CLOS], int rows, int clos, char set)
{
int i = 0;
for (i = 0; i <rows; i++)
{
int j = 0;
for (int j = 0; j < clos; j++)
{
board[i][j] = set;
}
}
}
//打印棋盘
void Print_board(char board[ROWS][CLOS], int row, int clo)
{
printf("------------扫雷------------\n");
int i = 0;
int j = 0;
for (j = 0; j <= clo; j++)
{
printf("%d", j);
}
printf("\n");
for (i = 0; i < row; i++)
{
printf("%d", i+1);
j = 0;
for (j = 0; j < clo; j++)
{
printf("%c", board[i][j]);
}
printf("\n");
}
printf("------------扫雷------------\n");
}
//随机布置十个雷的位置
void Setmine(char mine[ROWS][CLOS], int row, int clo)
{
int count = MINE_NUMBER;
while (count)
{
int x = rand() % row + 1;
int y = rand() % clo + 1;
if (mine[x-1][y-1] == '0')
{
mine[x-1][y-1] = '1';
count--;
}
}
}
//得到坐标附近一圈的炸弹的个数
int get_mine_number(char mine[ROWS][CLOS],int x,int y)
{
return (mine[x-1-1][y-1-1]+mine[x-1-1][y-1]+
mine[x-1-1][y-1+1]+mine[x-1][y-1-1]+
mine[x-1][y-1+1]+mine[x-1+1][y-1-1]+
mine[x-1+1][y-1]+mine[x-1+1][y-1+1] - 8 * '0');
}
//排查炸弹的个数
void find_mine(char mine[ROWS][CLOS], char show[ROWS][CLOS], int row, int clo)
{
int x = 0;
int y = 0;
printf("请输入坐标>:");
while (1)
{
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= clo)
{
if (mine[x-1][y-1] == '1')
{
printf("很遗憾,游戏结束\n");
Print_board(mine, ROW, CLO);
break;
}
else
{
int n = get_mine_number(mine,x,y);
show[x-1][y-1] = n + '0';
Print_board(show, ROW, CLO);
}
}
else
{
printf("坐标错误,请重新选择\n");
}
}
}
4.实验结果