头文件
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include <time.h>
#include <stdlib.h>
#include<Windows.h>
#define ROW 12
#define COL 12
#define NUM 20
#define BOOM '1'
extern void Game();
我们的主函数
int main()
{
srand((unsigned long)time(NULL));//srand ()函数用来设置算法的种子,time (NULL)返回当前的时间
//如果想在一个程序中生成随机数序列,需要至多在生成随机数之前设置一次随机种子
int quit = 0;
while (!quit) {
Menu();
int select = 0;
scanf("%d", &select);
switch (select) {
case 1:
Game();
break;
case 2:
quit = 1;
break;
default:
printf("数入有误,重新选择!\n");
break;
}
}
printf("BeyBey!\n");
return 0;
}
1.函数菜单
void Menu()
{
printf("#######################\n");
printf("#### 1. PLAY ####\n");
printf("#### 2. EXIT ####\n");
printf("#######################\n");
printf("please Select:");
}
2.游戏的框架:
void Game()
{
char show_board[ROW][COL];
char mine_board[ROW][COL];
memset(show_board, '*', sizeof(show_board));
memset(mine_board, '0', sizeof(mine_board));
SetMines(mine_board, ROW, COL);
int total = (ROW - 2) * (COL - 2) - NUM;//目标(找完到不是雷的地方)
int clear = 0;
while (1) {
system("cls");//清屏处理
int x = 0;
int y = 0;
ShowBoard(show_board, ROW, COL);
printf("请输入坐标<x,y>");
scanf("%d %d", &x, &y);
if (!(x >= 1 && y <= ROW - 2) && (y >= 1 && y <= COL - 2)) {
//判断扫雷的位置
printf("扫雷的位置有问题!\n");
continue;
}
if (show_board[x][y] != '*') {
//防止重复输入已被排过的地方
printf("扫雷的地方已被排除!\n");
continue;
}
//判断你输入的坐标是否有雷
if (mine_board[x][y] == '1') {
ShowBoard(mine_board, ROW, COL);
printf("对不起,你被炸死了!\n");
continue;
}
else {
int count = CountMine(mine_board, x, y);
show_board[x][y] = count + '0';
clear++;
}
if (clear >= total) {
printf("恭喜你,通关成功!\n");
break;
}
}
}
3.
void SetMines(char board[][COL], int row, int col)
{
int i = 1;
while (i < NUM) {
int _x = rand() % (row - 2) + 1;
int _y = rand() % (col - 2) + 1;
if (board[_x][_y] == BOOM) {
continue;
}
board[_x][_y] = BOOM;
i++;
}
}
4.显示面板
void ShowBoard(char board[][COL], int row, int col)
{
printf(" ");
for (int i = 1; i <= row - 2; i++) {
printf("%4d", i);
}
printf("\n ");
for (int k = 1; k <= col - 2; k++) {
printf("----");
}
printf("\n");
for (int i = 1; i <= row - 2; i++) {
printf("%2d|", i);
for (int j = 1; j <= col - 2; j++) {
printf(" %c |", board[i][j]);
}
printf("\n ");
for (int k = 1; k <= col - 2; k++) {
printf("----");
}
printf("\n");
}
}
5.
static int CountMine(char board[][COL], int x, int y)
{
//显示你输入坐标周围八个坐标有几个雷
return board[x - 1][y - 1] + board[x - 1][y] + \
board[x - 1][y + 1] + board[x][y - 1] + \
board[x][y + 1] + board[x + 1][y - 1] + \
board[x + 1][y] + board[x + 1][y + 1] - 8 * '0';
}