【C/C++ 10】扫雷小游戏

一、题目

写一个扫雷小游戏,每次输入一个坐标,若该处是地雷,则游戏失败,若该处不是地雷,则显示周围地雷数量,若扫除全部非地雷区域,则扫雷成功。

二、算法

设置两张地图(二维数组)mine和show,一张用于埋雷,一张用于显示当前的排雷情况。

两张地图的大小都比游戏雷场的ROW和COL加了两行两列,方便计算每个点周围的雷数。

mine的数据类型是int,0表示无雷,1表示有雷。

三、代码

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1

#include <iostream>
#include <ctime>
#include <Windows.h>
using namespace std;

#define ROW 5
#define COL 5
#define ROWS (ROW + 2)
#define COLS (COL + 2)
#define BOOM 3

class Game
{
public:
	void Init()
	{
		memset(_mine, 0, sizeof(int) * ROWS * COLS);
		memset(_show, '*', ROWS * COLS);
		_boom = BOOM;

		for (int i = 0; i < ROWS; ++i)
			for (int j = 0; j < COLS; ++j)
				_mine[i][j] == 0;

		// 埋雷
		while (_boom)
		{
			int x = rand() % ROW + 1;
			int y = rand() % COL + 1;
			if (_mine[x][y] != 1)
			{
				_mine[x][y] = 1;
				--_boom;
			}
		}
	}

	void Display()
	{
		system("cls");
		cout << "--------- 扫雷 ---------" << endl << "   ";
		for (int i = 1; i <= COL; ++i)
			printf("%2d ", i);
		cout << endl;
		for (int i = 1; i <= ROW; ++i)
		{
			printf("%2d ", i);
			for (int j = 1; j <= COL; ++j)
			{
				cout << ' ' << _show[i][j] << ' ';
			}
			cout << endl;
		}
	}

	void ShowMines()
	{
		cout << endl << endl;
		cout << "--------- 雷场 ---------" << endl << "   ";
		for (int i = 1; i <= COL; ++i)
			printf("%2d ", i);
		cout << endl;
		for (int i = 1; i <= ROW; ++i)
		{
			printf("%2d ", i);
			for (int j = 1; j <= COL; ++j)
			{
				if (_mine[i][j] == 0)
					cout << "   ";
				else
					cout << " B ";
			}
			cout << endl;
		}
	}

	char GetMineCount(int x, int y)
	{
		return _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]
		     + _mine[x - 1][y] + _mine[x + 1][y] + '0';
	}

	void Sweep()
	{
		int count = ROW * COL - BOOM;
		while (count)
		{
			int x, y;
			cout << "请输入扫雷坐标:";
			cin >> x >> y;
			if (x < 1 || y < 1 || x > ROW || y > COL)
			{
				cout << "坐标输入不合法,请重新输入" << endl;
				continue;
			}
			if (_mine[x][y] == 1)
			{
				ShowMines();
				cout << endl << "很遗憾, 你踩到地雷了......" << endl;
				return;
			}
			else
			{
				_show[x][y] = GetMineCount(x, y);
				Display();
				count--;
			}
		}

		cout << endl << "恭喜你,扫雷成功!" << endl;
		ShowMines();
	}

private:
	int _mine[ROWS][COLS];
	char _show[ROWS][COLS];
	int _boom;
};

int main()
{
	srand((unsigned int)time(nullptr));

	Game game;
	game.Init();
	game.Display();
	game.Sweep();

	return 0;
}

四、测试

相关推荐
见过夏天9 小时前
C++ 基础入门完全指南
c++
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境3 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴4 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境6 天前
C++ 的Eigen 库全解析
c++
卷无止境6 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴6 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18008 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝