①建项目扫雷
②创建头文件game.h
#pragma once
#include<stdlib.h>
#include<time.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define easy_count 10
void initboard(char board[ROWS][COLS], int rows, int cols, char set);
void displayboard(char board[ROWS][COLS], int row, int col);
void setmine(char board[ROWS][COLS], int row, int col);
void findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
③创建源文件test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"game2.h"
void menu()
{
printf("*****************************\n");
printf("********* 扫 雷 *********\n");
printf("****1.play 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, '*');
//打印棋盘
//displayboard(mine, ROW, COL);
displayboard(show, ROW, COL);
//布置雷
setmine(mine, ROW, COL);
displayboard(mine, ROW, COL);
//扫雷
findmine(mine,show, ROW, COL);
}
void test()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
break;
default:
printf("您输入错误,请重新输入:");
break;
}
} while (input);
}
int main()
{
test();
return 0;
}
④创建源文件game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"game2.h"
void initboard(char board[ROWS][COLS], int rows, int cols, char set)
{
int i = 0;
int j = 0;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
board[i][j] = set ;
}
}
}
void displayboard(char board[ROWS][COLS], int row, int col)
{
int i = 0;
int j = 0;
for (i = 1; i <= col; i++)
{
if (i == 1)
printf(" %d", i);
else
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 setmine(char board[ROWS][COLS], int row, int col)
{
int count = easy_count;
while(count)
{
int x = rand() % ROW + 1;
int y = rand() % COL + 1;
if (board[x][y] == '0')
{
board[x][y] = '1';
count--;
}
}
}
int get_mine_count(char mine[ROWS][COLS],int x,int y)
{
return
mine[x - 1][y] +
mine[x - 1][y - 1] +
mine[x][y - 1] +
mine[x + 1][y - 1] +
mine[x + 1][y] +
mine[x + 1][y + 1] +
mine[x][y + 1] +
mine[x - 1][y + 1] - 8 * '0';
}
void findmine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
int win = 0;
while (win<ROW*COL-easy_count)
{
printf("请输入排查雷的坐标:");
scanf("%d%d", &x, &y);
if (x >= 1 && x <= ROW&&y >= 1 && y <= COL)
{
if (mine[x][y] == '1')//坐标合法
{
printf("您踩到雷了!\n");
displayboard(mine, ROW, COL);
break;
}
else
{
int num = get_mine_count(mine, x, y);
show[x][y] = num + '0';
displayboard(show, ROW, COL);
win++;
}
}
else
{
printf("您输入的坐标不合法,请重新输入:");
}
}
if (win == ROW*COL - easy_count)
{
printf("恭喜您,排雷成功。\n");
displayboard(mine, ROW, COL);
}
}
|