1.utili.h
#ifndef _UTILI_H_
#define _UTILI_H_
#include<stdio.h>
#include<time.h>
#endif /* _UTILI_H_ */
2.game.h
#ifndef _GAME_H_
#define _GAME_H_
#include"utili.h"
#define EXIT 0
#define PLAY 1
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define GAME_LEVEL 20
//初始化界面
void InitBoard(char board[ROWS][COLS], char set);
//显示棋盘
void DisplayBoard(char board[ROWS][COLS], int row, int col);
//设置雷
void SetMine(char mine[ROWS][COLS], int row, int col);
//扫雷
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
//开始游戏
void StartGame();
#endif /* _GAME_H_ */
3.GameMain.c
#include"game.h"
int main(int argc, char *argv[])
{
int select = 1;
while(select)
{
printf("***********************************\n");
printf("* 简 易 扫 雷 游 戏 *\n");
printf("***********************************\n");
printf("* [1] Play *\n");
printf("* [0] Exit *\n");
printf("***********************************\n");
printf("请选择:>");
scanf("%d", &select);
if(select == EXIT)
break;
if(select != PLAY)
{
printf("输入命令有误,请重新输入......\n");
continue;
}
//开始游戏
StartGame();
}
printf("扫雷游戏结束,拜拜.\n");
return 0;
}
4.game.c
#include"game.h"
void InitBoard(char board[ROWS][COLS], char set)
{
for(int i=0; i<ROWS; ++i)
{
for(int j=0; j<COLS; ++j)
{
board[i][j] = set;
}
}
}
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
for(int i=0; i<=row; ++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 SetMine(char mine[ROWS][COLS], int row, int col)
{
int count = GAME_LEVEL;
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--;
}
}
}
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';
}
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x, y;
int win = 0;
while(win < row*col-GAME_LEVEL)
{
printf("输入扫雷的位置:>");
scanf("%d %d", &x, &y);
//判断坐标的合法性
if((x<1||x>row) || (y<1||y>col))
{
printf("输入的坐标不合法,请重新输入.....\n");
continue;
}
//判断是否踩雷
if(mine[x][y] == '1')
{
DisplayBoard(mine, ROW, COL);
printf("很遗憾,排雷失败,你被炸死了.\n");
break;
}
//统计雷数,并修改显示数组
int count = GetMineCount(mine, x, y);
show[x][y] = count+'0';
win++;
system("cls");
DisplayBoard(show, ROW, COL);
}
if(win >= row*col-GAME_LEVEL)
{
DisplayBoard(mine, ROW, COL);
printf("恭喜你,排雷成功.....\n");
}
}
void StartGame()
{
//定义棋盘
char mine[ROWS][COLS];
char show[ROWS][COLS];
//初始化棋盘
InitBoard(mine, '0');
InitBoard(show, '*');
//进入游戏 //埋雷
SetMine(mine, ROW, COL);
//显示棋盘
DisplayBoard(show, ROW, COL);
//开始扫雷
FindMine(mine, show, ROW, COL);
}
5.成品