还是用三个文件写代码,分别是game.c 和 game.h 和 test.c 。文件如下:
代码如下:
game.c
#include "game.h"
void init_board(char board[ROWS][COLS], int row, int col,char set)
{
int i = 0;
for (i = 0; i <ROWS;i++)
{
int j = 0;
for (j = 0; j <COLS; j++)
{
board[i][j] = set;
}
}
}
void play_board(char board[ROWS][COLS], int row, int col)
{
printf("---- 排雷游戏 ------\n");
int i = 0;
for (i = 0; i <=row; i++)
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i <= row; i++)
{
int j = 0;
printf("%d ", i);
for (j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
printf("----------------------\n");
}
void prepare_board(char board[ROWS][COLS], int row, int col)
{
int i = 0;
int j = 0;
int count = BOM;
while (count)
{
int a = rand() % row + 1;
int b = rand() % col + 1;
if (board[a][b] == '0')
{
board[a][b] = '1';
count--;
}
}
}
void show_play(char arr1[ROWS][COLS], char arr2[ROWS][COLS], int row, int col)
{
int i = 0;
int j = 0;
int count = BOM;
char win='0';
int a = 0;
while (a=row*col-count)
{
printf("请输入排雷\n");
scanf("%d %d", &i, &j);
if (i<1 || i>row || j<1 || j>row)
{
printf("输入不对,请重新输入\n");
continue;
}
if (arr1[i][j] == '1')
{
printf("你被炸死了\n");
play_board(arr1, ROW, COL);//打印看一下,传入参数是传入的arr1;
break;
}
else
{
win=((arr1[i - 1][j] + arr1[i - 1][j - 1] + arr1[i][j - 1] + arr1[i + 1][j - 1] + arr1[i + 1][j] + arr1[i + 1][j + 1] + arr1[i][j + 1] + arr1[i - 1][ j + 1])-8*'0')+'0';
arr2[i][j] = win;
play_board(arr2, ROW, COL);//打印看一下,传入参数是传入的arr2;
count++;
//打印
}
}
if(0==a)
printf("排雷成功\n");
}
game.h
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define ROW 9
#define COL 9
#define BOM 10
#define ROWS ROW+2
#define COLS COL+2
void init_board(char board[ROWS][COLS], int row, int col,char set);
void play_board(char board[ROWS][COLS], int row, int col);
void prepare_board(char board[ROWS][COLS], int row, int col);
void show_play(char arr1[ROWS][COLS],char arr2[ROWS][COLS], int row, int col);
test.c
#include "game.h"
void menu()
{
printf("----------------------------\n");
printf("------- 1.play -------\n");
printf("------- 0.exit -------\n");
printf("----------------------------\n");
}
void game()
{
//创建
char arr1[ROWS][COLS] = { 0 };
char arr2[ROWS][COLS] = { 0 };
//初始化
init_board(arr1, ROW, COL,'0');
init_board(arr2, ROW, COL,'*');
//布置
prepare_board(arr1, ROW, COL);
//打印
//play_board(arr1, ROW, COL);
//printf("\n");
play_board(arr2, ROW, COL);
//排雷
show_play(arr1,arr2, ROW, COL);
}
int main()
{
srand((unsigned int)time(NULL));
//扫雷游戏
int input = 0;
do
{
printf("请选择:>\n");
menu();
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
break;
default:
printf("选择错误,请重新选择\n");
break;
}
} while (input);
return 0;
}