头文件(函数声明.h)
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define lei 10//设置雷的个数
//初始化棋盘
void Initboard(char board[ROWS][COLS], int rows, int cols, char set);//set 设置
void Disboard(char board[ROWS][COLS], int row, int col);
//布置雷
void Setboard(char board[ROWS][COLS], int row, int col);
//排雷
void Findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
定义函数
#include"函数声明.h"
void Initboard(char board[ROWS][COLS], int rows, int cols,char set)
{
int i = 0;
for (i = 0; i < rows; i++)
{
int j = 0;
for (j = 0; j < cols; j++)
{
board[i][j] = set;
}
}
}
void Disboard(char board[ROWS][COLS], int row, int col)
{
int i = 0;
printf("----------------------------------\n");
for (i = 0; i <= 9; i++)
{
printf("%d",i );
}
printf("\n");
for(i=1;i<=row;i++)
{
int j = 0;
printf("%d", i);
for (j = 1; j <= col;j++)
{
printf("%c", board[i][j]);
}
printf("\n");
}
printf("---------------------------------\n");
}
void Setboard(char board[ROWS][COLS], int row, int col)
{
int n = lei;
while(n)
{
//1.生成随机下标
int x = rand() % row + 1;
int y = rand() % col + 1;//与参数关联,防止传死了
if (board[x][y] != '1')
{
board[x][y] = '1';
n--;
}
}
}
int get_n(char mine[ROWS][COLS],int x,int y)//ASII码规定 字符‘3’+或- 字符‘0’=数字 3
{//便例 点(x,y)/附近的八个点,如果有雷,点(x,y)显示雷的数量
return mine[x - 1][y] +
mine[x - 1][y - 1] +
mine[x][y - 1] +
mine[x + 1][y - 1] +
mine[x + 1][y] +
mine[x + 1][y + 1] +
mine[x][y + 1] +
mine[x - 1][y + 1] - 8 * '0';
}
//排雷
void Findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int win = 0;
while (win<row*col-lei)
{
printf("请输入要排查的坐标\n");
scanf_s("%d%d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)//写棋盘范围
{
if (mine[x][y] == '1')
{
printf("很遗憾,游戏结束\n");
Disboard(mine, ROW, COL);
break;
}
else {
int n = get_n(mine ,x,y);
show[x][y] = n+'0';
Disboard(show, ROW, COL);
}
}
else {
printf("输入错误,超出范围,请重新输入\n");
}
}
if (win == row * col - lei)
{
printf("扫完了,已经一个都不剩了");
}
游戏主体:
#include "函数声明.h"
//雷是“1” 空格是‘0’
void menu()
{
printf("*******************\n");
printf("*****1.开始游戏****\n");
printf("*****2.结束********\n");
printf("*******************\n");
}
void game()
{
char mine[ROW+2][COLS] = { 0 };//存放雷的信息
char show[ROW+2][COLS] = { 0 };//存放排查出的雷的信息
//初始化信息
Initboard(mine, ROWS, COLS,'0');//0,每一个位置都是0(空)
Initboard(show, ROWS, COLS,'*');//* 每一个位置都是炸弹
//布置雷
Setboard(mine, ROW, COL);
Disboard(show, ROW, COL);
//打印棋盘
//Disboard(mine, ROW, COL);
/*Disboard(show, ROW, COL);*/
//排雷
Findmine(mine,show,ROW,COL);
}
int main()
{ int input = 0;
srand((unsigned int)time(NULL));
{
menu();
printf("请选1或2\n");
scanf_s("%d", &input);
switch (input)
{
case 1:
printf("扫雷\n");
game();
break;
case 2:
printf("退出游戏\n");
break;
default:
printf("输入错误,请重新输入\n");
break;
}
} while (input);
return 0;
}