以下是一个简单的C++闯关游戏示例,玩家需要在地图上找到宝藏并安全返回起点。游戏中有多个障碍和宝藏,玩家需要避开障碍并收集宝藏,最后返回起点即可通关。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x, y;
};
bool cmp(const Point &a, const Point &b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
int main() {
const int N = 10; // 地图大小为 10x10
const int M = 10; // 障碍数量为 10
const int T = 1; // 宝藏数量为 1
vector<Point> treasure(T); // 宝藏位置
vector<Point> obstacle(M); // 障碍位置
for (int i = 0; i < M; i++) {
obstacle[i].x = rand() % N;
obstacle[i].y = rand() % N;
}
for (int i = 0; i < T; i++) {
treasure[i].x = rand() % N;
treasure[i].y = rand() % N;
}
sort(obstacle.begin(), obstacle.end(), cmp); // 按 x 坐标升序排序障碍位置
sort(treasure.begin(), treasure.end(), cmp); // 按 x 坐标升序排序宝藏位置
Point start = {0, 0}; // 起点位置为 (0, 0)
bool can_pass[N][N] = {false}; // 记录每个位置是否可以通过
for (int i = 0; i < M; i++) {
can_pass[obstacle[i].x][obstacle[i].y] = true; // 设置障碍位置为不可通过
}
vector<Point> path; // 记录路径的向量
bool visited[N][N] = {false}; // 记录每个位置是否被访问过
if (dfs(start, can_pass, visited, path)) { // 使用深度优先搜索算法搜索路径
cout << "找到一条路径:" << endl;
for (int i = 0; i < path.size(); i++) {
cout << "(" << path[i].x << ", " << path[i].y << ") "; // 输出路径上的点坐标
}
cout << endl;
} else {
cout << "无法找到路径。" << endl;
}
return 0;
}