game.h
#ifndef __GSME_H__
#define __GSME_H__
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define ROW 10
#define COL 10
#define ROWS (ROW+2)
#define COLS (COL+2)
#define DEFAULT_COUNT 55
void InitBoard(char board[ROWS][COLS],int row,int col,char set);
void SetMine(char board[ROWS][COLS]);
void Display(char board[ROWS][COLS],int row,int col);
int GetMineCount(char board[ROWS][COLS],int x,int y);
void Spread(char mine[ROWS][COLS],char show[ROWS][COLS],int x,int y);
#endif//__GSME_H__
game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void InitBoard(char board[ROWS][COLS],int row,int col,char set)
{
/*int i,j=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
board[i][j]=set;
}
}*/
memset(board,set,row*col*sizeof(board[0][0]));
}
int get_rand_num()
{
return rand()%ROW+1;
}
void SetMine(char board[ROWS][COLS])
{
int count=DEFAULT_COUNT;
while(count)
{
int x=get_rand_num();
int y=get_rand_num();
if(board[x][y]=='0')
{
board[x][y]='1';
count--;
}
}
}
void Display(char board[ROWS][COLS],int row,int col)
{
int i=0;
int j=0;
printf(" ");
for(i=0;i<col-1;i++)
printf("%2d",i);
printf("\n");
for(i=0;i<row-1;i++)
{
printf("%3d ",i);
for(j=0;j<col-1;j++)
{
printf("%c ",board[i][j]);
}
printf("\n");
}
}
int GetMineCount(char board[ROWS][COLS],int x,int y)
{
return ( board[x-1][y]
+board[x-1][y-1]
+board[x][y-1]
+board[x+1][y-1]
+board[x+1][y]
+board[x+1][y+1]
+board[x][y+1]
+board[x-1][y+1]-8*'0');
}
void Spread(char mine[ROWS][COLS],char show[ROWS][COLS],int x,int y)
{
int ret;
int a,b;
if((x>=1)&&(x<=ROW)&&(y>=1)&&(y<=COL))
{
if (mine[x-1][y-1]='0')
{
a=x-1;
b=y-1;
ret=GetMineCount(mine,x,y);
if(ret==0)
{
show[x-1][y-1]=' ';
mine[a][b]='0';
Spread(mine,show,a,b);
}
else
{
show[a][b]='0'+ret;
mine[a][b]='0';
}
}
}
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void menu()
{
printf("*******************************\n");
printf("*****欢迎来到扫雷游戏********\n");
printf("*******1、进入游戏*************\n");
printf("*******0、退出游戏*************\n");
printf("*******************************\n");
}
void game()
{
int x,y;
int count=0;
int win=0;
char mine[ROWS][COLS]={0};
char show[ROWS][COLS]={0};
InitBoard(mine,ROWS,COLS,'0');
InitBoard(show,ROWS,COLS,'*');
//布雷
SetMine(mine);
Display(mine,ROWS,COLS);
printf("排雷开始:>\n");
Display(show,ROWS,COLS);
//扫雷
while(win<(ROW*COL-DEFAULT_COUNT))
{
printf("请输入坐标:>");
scanf("%d%d",&x,&y);
if((x>=1)&&(x<=ROW)&&(y>=1)&&(y<=COL))
{
if(mine[x][y]=='1')
{
printf("很遗憾,你被炸死了\n");
return;
}
else
{
if(show[x][y]=='*')
win++;
count=GetMineCount(mine,x,y);
show[x][y]=count+'0';
Display(show,ROWS,COLS);
}
//Spread(mine,show,x,y);
}
else
{
printf("下标有误,请重新输入\n");
}
}
printf("恭喜你排雷成功\n");
}
void test()
{
int input;
do
{
menu();
srand((unsigned int)time(NULL));
printf("请选择:>");
scanf("%d",&input);
switch(input)
{
case 1:
game();
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
}
while(input);
}
int main()
{
test();
return 0;
}