game.h(头文件)
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define EASY 80
void InitBoard(char board[ROWS][COLS], int row, int col,char set);
void Display(char board[ROWS][COLS], int row, int col);
void SetMine(char board[ROWS][COLS], int row, int col);
void Saolei(char board[ROWS][COLS], char mine[ROWS][COLS], int row, int col);
game.c(游戏函数的实现)
#include"game.h"
void InitBoard(char board[ROWS][COLS], int row, int col,char set)
{
int i = 0;
for (i = 0; i < row; i++)
{
int j = 0;
{
for (j = 0; j < col; j++)
{
board[i][j] = set;
}
}
}
}
void Display(char board[ROWS][COLS], int row, int col)
{
int i = 0;
for (i = 0; i <= col; i++)
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i <= row; i++)
{
printf("%d ", i);
int j = 0;
for (j = 1; j <= col; j++)
{
printf("%c ",board[i][j]);
}
printf("\n");
}
}
void SetMine(char board[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int count = EASY;
while (count)
{
x = rand() % 9 + 1;
y = rand() % 9 + 1;
if (board[x][y] == '0')
{
board[x][y] = '1';
count--;
}
}
}
int Num(char mine[ROWS][COLS] ,int x, int y)
{
return (mine[x][y - 1] + mine[x][y + 1] + mine[x - 1][y] + mine[x + 1][y] + mine[x - 1][y - 1] + mine[x - 1][y + 1] + mine[x + 1][y + 1] + mine[x + 1][y - 1]) - 8 * '0';
}
void Saolei(char board[ROWS][COLS], char mine[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int win = 0;
while (win < row * col - EASY)
{
printf("请输入您想要扫的坐标:>");
scanf("%d %d", &x, &y);
if (x > 0 && x <= row && y > 0 && y <= col)
{
if (mine[x][y] != '1')
{
int ret = Num(mine, x, y);
board[x][y] = ret + '0';
Display(board, ROW, COL);
win++;
}
else
{
printf("你被炸死了\n");
Display(mine, ROW, COL);
break;
}
}
else
{
printf("非法坐标请重新输入\n");
}
}
if (win == row * col - EASY)
printf("恭喜你,成功排雷\n");
Display(mine, ROW, COL);
}
test.c(测试过程)
#include"game.h"
void menu()
{
printf("**********************************\n");
printf("************** 1.play ************\n");
printf("************** 0.exit ************\n");
printf("**********************************\n");
}
void game()
{
char mine[ROWS][COLS] = { 0 };
char show[ROWS][COLS] = { 0 };
InitBoard(mine, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
SetMine(mine, ROW, COL);
Display(show, ROW, COL);
Saolei(show, mine, ROW, COL);
}
int main()
{
srand((unsigned int)time(NULL));
int input = 0;
do
{
menu();
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("错误值,请重新输入\n");
break;
}
} while (input);
return 0;
}