扫雷游戏实现

我们在实现扫雷游戏时,为了方便就会创建两个文件,一个是头文件,一个是源文件。

在头文件中我们会定义一些常量和需要实现的函数。

1.头文件

cpp 复制代码
#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define EASY_COUNT 10
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
//初始化棋盘
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);

接下来我们开始实现函数。

2.初始化棋盘

cpp 复制代码
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
	int i = 0;
	for (i = 0; i < rows; i++)
	{
		
		int j = 0;
		for (j = 0; j < cols; j++)
		{
			board[i][j] = set;
		}
	}
}

3.打印棋盘

cpp 复制代码
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	int i = 0;
	printf("--------扫雷游戏-------\n");
	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");
	}
}

4.布置雷

cpp 复制代码
void SetMine(char board[ROWS][COLS], int row, int col)
{
	//布置10个雷
	//⽣成随机的坐标,布置雷
	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--;
		}
	}
}

5.排雷

cpp 复制代码
int GetMineCount(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 + 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 count = GetMineCount(mine, x, y);
				show[x][y] = count + '0';
				DisplayBoard(show, ROW, COL);
				win++;
			}
		}
		else
		{
			printf("坐标⾮法,重新输⼊\n");
		}
	}
	if (win == row * col - EASY_COUNT)
	{
		printf("恭喜你,排雷成功\n");
		DisplayBoard(mine, ROW, COL);
	}
}

扫雷代码可能有些小伙伴会觉得复杂,其实大家静下心来慢慢看,没有想象中那么复杂的。
谢谢

相关推荐
2501_921649492 分钟前
免费获取股票历史行情与分时K线数据 API
开发语言·后端·python·金融·数据分析
尤物程序猿7 分钟前
Java如何不建表完成各种复杂的映射关系(鉴权概念、区域概念、通用概念)
java·开发语言
名誉寒冰19 分钟前
GDB 调试与 Core Dump(段错误)排查指南(Linux/C/C++)
linux·c语言·c++
Insight.43 分钟前
背包问题——01背包、完全背包、多重背包、分组背包(Python)
开发语言·python
aini_lovee1 小时前
改进遗传算法求解VRP问题时的局部搜索能力
开发语言·算法·matlab
Yeniden1 小时前
Deepeek用大白话讲解 --> 迭代器模式(企业级场景1,多种遍历方式2,隐藏集合结构3,Java集合框架4)
java·开发语言·迭代器模式
SmoothSailingT1 小时前
C#——LINQ方法
开发语言·c#·linq
景川呀1 小时前
Java的类加载器
java·开发语言·java类加载器
k***92161 小时前
Python 科学计算有哪些提高运算速度的技巧
开发语言·python
superman超哥1 小时前
仓颉条件变量深度解析与实践:解锁高效并发同步
开发语言·python·c#·仓颉