C++ 迷宫游戏代码解析:从随机生成到路径寻觅
#include <bits/stdc++.h> // 包含所有标准库的头文件
using namespace std;
const char WALL = '@'; // 墙的标志
const char START = 'S'; // 起点的标志
const char END = 'E'; // 终点的标志
const char PATH = ' '; // 路径的标志
const char VISITED = 'e'; // 已访问的标志
const int MAX_SCORE = 100; // 最大得分
class labyrinth{ // 定义迷宫类
private:
void labyrinth_() { // 打印迷宫
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << maze[i][j] << ' '; // 打印迷宫的每个字符
}
cout << endl; // 打印换行符
}
cout << endl; // 打印换行符
}
int size; // 迷宫的大小
int diff; // 迷宫的难度
vector<vector<char>>maze; // 迷宫的二维字符数组
int beginR,beginC; // 起点的行和列
int endR,endC; // 终点的行和列
public:
labyrinth(int size, int diff) : size(size), diff(diff) { // 构造函数 初始化迷宫
maze = vector<vector<char>>(size, vector<char>(size, WALL)); // 初始化迷宫为墙
for (int i = 1; i < size - 1; i++) { // 遍历内部的格子
for (int j = 1; j < size - 1; j++) {
maze[i][j] = PATH; // 将迷宫内部的格子设置为路径
}
}
srand(time(nullptr)); // 设置随机种子
beginR = rand() % (size - 2) + 1; // 随机生成起点的行
beginC = rand() % (size - 2) + 1; // 随机生成起点的列
endR = rand() % (size - 2) + 1; // 随机生成终点的行
endC = rand() % (size - 2) + 1; // 随机生成终点的列
maze[beginR][beginC] = START; // 将起点标记为起点字符
maze[endR][endC] = END; // 将终点标记为终点字符
int fork= size * diff/ 10; // 计算障碍物的数量
for (int i = 0; i < fork; i++) { // 随机生成障碍物
int row = rand() % (size - 2) + 1;
int col = rand() % (size - 2) + 1;
maze[row][col] = WALL; // 将障碍物标记为墙
}
}
void play() { // 开始游戏
int score = 0; // 得分
int steps = 0; // 步数
vector<pair<int, int>> path; // 走过的路径
int curRow = beginR; // 当前行
int curCol = beginC; // 当前列
while (curRow != endR || curCol != endC) { // 当未到达终点时
maze[curRow][curCol] = VISITED; // 标记当前位置为已访问
path.push_back(make_pair(curRow, curCol)); // 将当前位置加入路径中
cout << "当前位置:(" << curRow << ", " << curCol << ")" << endl; // 输出当前位置
labyrinth_(); // 打印迷宫
char move; // 移动方向
cout << "请输入移动方向(1上,2下,3左,4右):";
cin >> move; // 输入移动方向
int nextRow = curRow; // 下一个位置的行
int nextCol = curCol; // 下一个位置的列
switch (move) { // 根据移动方向更新下一个位置的行和列
case '1':
nextRow--;
break;
case '2':
nextRow++;
break;
case '3':
nextCol--;
break;
case '4':
nextCol++;
break;
default:
cout << "移动方向无效!" << endl;
continue;
}
if (maze[nextRow][nextCol] == WALL) { // 如果下一个位置是墙
cout << "该方向不通,已撞墙!" << endl;
continue;
}
curRow = nextRow; // 更新当前位置的行
curCol = nextCol; // 更新当前位置的列
steps++; // 步数加一
}
score = MAX_SCORE - steps * diff; // 计算得分
cout << "恭喜你成功走出迷宫!得分:" << score << endl; // 输出得分
for (const auto& p : path) { // 将路径上的位置标记为路径
maze[p.first][p.second] = PATH;
labyrinth_(); // 打印迷宫
}
}
};
int main() {
int size, diff; // 迷宫大小和难度
cout<<"迷宫大小(3至10):";
cin>>size; // 输入迷宫大小
cout<<"迷宫难度(1至10):";
cin>>diff; // 输入迷宫难度
labyrinth game(size, diff); // 创建迷宫对象
game.play(); // 开始游戏
return 0;
}
原文地址: https://www.cveoy.top/t/topic/qzy5 著作权归作者所有。请勿转载和采集!