<game.h>
#pragma once
#include<stdio.h>
#include<Windows.h>
#include<time.h>
#include<stdlib.h>
#define ROWS 11
#define COLS 11
#define ROW 9
#define COL 9
#define BombNum 10
void InitBoard(char board[ROWS][COLS], int row, int col, char set);
void Display(char board[ROWS][COLS]);
void SetBomb(char board[ROWS][COLS], int row, int col);
void ExcBomb(char board1[ROWS][COLS], char board2[ROWS][COLS], int row, int col);
<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 = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
board[i][j] = set; //这里初始化放置雷的棋盘的时候全部为字符‘0’,那么到时候算周围雷的个数直接减去8*‘0’
}
}
}
//打印棋盘
void Display(char board[ROWS][COLS], int row, int col)
{
int i = 0;
int j = 0;
printf("------------------------------------\n");
for (i = 0; i <= row; i++) //打印第一行的列表
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i <= row; i++)
{
printf("%d ", i); //打印第二行的列表
for (j = 1; j <= col; j++)
{
printf("%c " ,board[i][j]);
}
printf("\n");
}
}
//布置雷
void SetBomb(char board[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int n = BombNum;
while(n)
{
x = rand() % row + 1;
y = rand() % col + 1;
if (board[x][y] != '1')
{
board[x][y] = '1';
n--;
}
}
}
//排查雷时两个棋盘都要传进来
//board1为存放雷的界面 ‘0’
//board2为排雷时的界面 ‘*’
void ExcBomb(char board1[ROWS][COLS], char board2[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int n = ROW * COL - BombNum;
while (n)
{
printf("请输入坐标>");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (board1[x][y] == '1')
{
printf("你已踩雷,游戏结束\n\n");
Display(board1, ROW, COL);
break;
}
else
{
n--;
int count = 0;
count = Num(board1, x, y);
board2[x][y] = count + '0';
Display(board2, ROW, COL);
}
}
else
{
printf("输入错误,请重新输入>");
}
}
if (n == 0)
{
printf("YOU WIN\n");
Display(board1, ROW, COL);
}
}
//统计周围雷的个数
int Num(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');
}
<test.c>
#define _CRT_SECURE_NO_WARNINGS 1
#include"game.h"
//扫雷
void menu()
{
printf("*************************************\n");
printf("************* 1.Play **************\n");
printf("************* 0.Exit **************\n");
printf("*************************************\n");
}
void game()
{
//初始化棋盘
char Dep[ROWS][COLS] = { 0 };//存放雷的
char Exc[ROWS][COLS] = { 0 };//用于排雷的
InitBoard(Dep, ROWS, COLS, '0');//'0'
InitBoard(Exc, ROWS, COLS, '*');//'*'
//布置雷
SetBomb(Dep, ROW, COL);
//打印棋盘
Display(Exc, ROW, COL);
//开始排雷
ExcBomb(Dep, Exc, ROW, COL);
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();//菜单
printf("请输入>");
scanf("%d", &input);
switch (input)
{
case 0:
printf("正在退出游戏\n");
Sleep(500);
break;
case 1:
game();
break;
default:
printf("选择错误,请重新输入>");
break;
}
} while (input);
return 0;
}