1.简介:
通过C语言实现扫雷
2.代码实现:
我开创了三个文件,一个用来存储主函数,一个是游戏头文件,最后是游戏主函数,这样的优点是使得模块化,便于可读以及后期修改。
1)主函数代码:
代码语言:javascript复制#include"game.h"
void menu()
{
printf("********************n");
printf("**** 1.play ******n");
printf("**** 0.exit ******n");
}
void play()
{
char mine[COWS][COLS];
char show[COWS][COLS];
//初始化棋盘
initboard(mine, COWS, COLS, '0');
initboard(show, COWS, COLS, '*');
//打印棋盘
Displayboard(show, COW, COL);
//布置雷
setmine(mine, COW, COL);
//Displayboard(mine, COW, COL);
//排查雷
findmine(mine,show, COW, COL);
}
int main()
{
int input=0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:");
scanf_s("%d", &input);
switch(input)
{
case 1:
printf("开始游戏n");
play();
break;
case 0:
printf("游戏结束n");
break;
default:
printf("输入错误,请重新输入n");
break;
}
} while (input);
return 0;
}
2)游戏头文件:
代码语言:javascript复制#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define COW 9
#define COL 9
#define COWS COW 2
#define COLS COL 2
#define easy_count 10//雷的数量
void initboard(char board[COWS][COLS], int cows, int cols, char set);
void Displayboard(char board[COWS][COLS], int cow, int col);
void setmine(char board[COWS][COLS], int cow, int col);
void findmine(char mine[COWS][COLS], char show[COWS][COLS], int cow, int col);
3)游戏主函数:
代码语言:javascript复制#include"game.h"
void initboard(char board[COWS][COLS], int cows, int cols, char set)
{
int i = 0;
int j = 0;
for (i = 0; i < cows; i )
{
for (j = 0; j < cols; j )
board[i][j] = set;
}
}
void Displayboard(char board[COWS][COLS], int cow, int col)
{
int i = 0;
int j = 0;
for (i = 0; i <=col; i )
{
printf("%d ", i);
}
printf("n");
for (i = 1; i <= cow; i )
{
printf("%d ", i);
for (j = 1; j <= col; j )
{
printf("%c ", board[i][j]);
}
printf("n");
}
}
void setmine(char board[COWS][COLS], int cow, int col)
{
int count = easy_count;
while (count)
{
int i = rand() % cow 1;
int j = rand() % col 1;
if (board[i][j] == '0')
{
board[i][j] = '1';
count--;
}
}
}
int getmine(char mine[COWS][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');
}
void findmine(char mine[COWS][COLS], char show[COWS][COLS], int cow, int col)
{
int x = 0;
int y = 0;
int win = 0;
while (win<cow*col-easy_count)
{
printf("请输入要排查的坐标:");
scanf_s("%d%d", &x, &y);
if (x >= 1 && x <= cow && y >= 1 && y <= col)
{
if (mine[x][y] == '1')
{
printf("你已被炸死n");
Displayboard(mine, COW, COL);
break;
}
else
{
int count = getmine(mine, x, y);
show[x][y] = count '0';
Displayboard(show, COW, COL);
win ;
}
}
else
{
printf("坐标非法,请重新输入");
}
}
if (win == cow * col - easy_count)
{
printf("恭喜你,已全部找到雷");
Displayboard(mine, COW, COL);
}
}