//game.h
void Init_board(char mine[rows][cols], char show[rows][cols]);//初始化棋盤
void Set_mine(char mine[rows][cols]);//設置雷的位置
void Display(char show[rows][cols]);//打印棋盤
int Sweep(char mine[rows][cols], char show[rows][cols]);//開始掃雷
int Get_num(char mine[rows][cols], int x, int y);//計算雷個數
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
void Init_board(char mine[rows][cols], char show[rows][cols])
{
int i = 0;
int j = 0;
for (i = 0; i < rows - 1; i++)
{
for (j = 0; j < cols - 1; j++)
{
mine[i][j] = '0';
show[i][j] = '*';
}
}
}
void Set_mine(char mine[rows][cols])
{
int count = Count;
int x = 0;
int y = 0;
while (count)
{
x = rand() % 9 + 1;
y = rand() % 9 + 1;
if (mine[x][y] == '0')
{
mine[x][y] = '1';
count--;
}
}
}
void Display(char show[rows][cols])
{
int i = 0;
int j = 0;
printf(" ");
for (i = 1; i < cols - 1; i++)
{
printf("%d ", i);
}
printf("\n\n");
for (i = 1; i < rows - 1; i++)
{
printf("%d ", i);
for (j = 1; j < rows - 1; j++)
{
printf("%c ", show[i][j]);
}
printf("\n\n");
}
}
int Get_num(char mine[rows][cols], int x, int y)
{
int count = 0;
if (mine[x - 1][y - 1] == '1')
{
count++;
}
if (mine[x][y - 1] == '1')
{
count++;
}
if (mine[x + 1][y - 1] == '1')
{
count++;
}
if (mine[x - 1][y] == '1')
{
count++;
}
if (mine[x + 1][y] == '1')
{
count++;
}
if (mine[x - 1][y + 1] == '1')
{
count++;
}
if (mine[x][y + 1] == '1')
{
count++;
}
if (mine[x + 1][y + 1] == '1')
{
count++;
}
return count;
}
int Sweep(char mine[rows][cols], char show[rows][cols])
{
int count = 0;
int x = 0;
int y = 0;
while (count != ((rows - 2) * (cols - 2) - Count))
{
printf("請輸入座標(用空格隔開):\n");
scanf("%d%d", &x, &y);
if (mine[x][y] == '1')
{
printf("你已踩雷,被炸死了!\n");
return 0;
}
else
{
int ret = Get_num(mine, x, y);
show[x][y] = ret + '0';
Display(show);
count++;
}
}
printf("恭喜你贏了!\n");
Display(mine);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void menu()
{
printf("***************************\n");
printf("******** 掃雷小遊戲 *******\n");
printf("********* 1.play **********\n");
printf("********* 0.exit **********\n");
printf("***************************\n");
}
void game()
{
char mine[rows][cols];
char show[rows][cols];
Init_board(mine, show);
Set_mine(mine);
Display(show);
Display(mine);
Sweep(mine, show);
}
void test()
{
int input = 0;
do{
menu();
printf("請選擇:");
scanf("%d", &input);
switch (input)
{
case 1:
printf("進入遊戲:\n");
game();
break;
case 0:
printf("退出遊戲\n");
break;
defalt:
printf("輸入錯誤,請重新選擇");
break;
}
} while (input);
}
int main()
{
srand((unsigned)time(NULL));
test();
system("pause");
return 0;
}