以下是一个简单的迷宫游戏的 C++ 代码示例:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;

// 定义迷宫的大小
const int N = 10;

// 定义迷宫中的元素
const char WALL = '■';
const char START = 'S';
const char END = 'E';
const char PATH = ' '; 
const char VISITED = '.';

// 定义迷宫类
class Maze {
private:
    vector<vector<char>> maze;
    int startX, startY;
    int endX, endY;

public:
    Maze() {
        maze.resize(N, vector<char>(N, WALL));
        generateMaze();
    }

    void generateMaze() {
        srand(time(0));

        // 随机生成起点和终点
        startX = rand() % (N - 2) + 1;
        startY = rand() % (N - 2) + 1;
        endX = rand() % (N - 2) + 1;
        endY = rand() % (N - 2) + 1;

        maze[startX][startY] = START;
        maze[endX][endY] = END;

        // 随机生成障碍物
        int obstacleCount = N * N / 4;
        for (int i = 0; i < obstacleCount; i++) {
            int obstacleX = rand() % (N - 2) + 1;
            int obstacleY = rand() % (N - 2) + 1;
            maze[obstacleX][obstacleY] = WALL;
        }
    }

    void displayMaze() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                cout << maze[i][j] << ' '; 
            }
            cout << endl;
        }
    }

    bool exploreMaze(int x, int y) {
        if (x < 0 || x >= N || y < 0 || y >= N) {
            return false;
        }

        if (maze[x][y] == END) {
            return true;
        }

        if (maze[x][y] != PATH) {
            return false;
        }

        maze[x][y] = VISITED;

        if (exploreMaze(x-1, y) || exploreMaze(x+1, y) || exploreMaze(x, y-1) || exploreMaze(x, y+1)) {
            return true;
        }

        maze[x][y] = PATH;
        return false;
    }

    bool solveMaze() {
        return exploreMaze(startX, startY);
    }
};

int main() {
    Maze maze;
    maze.displayMaze();

    cout << '开始走迷宫...' << endl;
    if (maze.solveMaze()) {
        cout << '成功走出迷宫!' << endl;
    } else {
        cout << '无法走出迷宫!' << endl;
    }

    return 0;
}

此代码实现了一个简单的迷宫游戏,包括自动生成迷宫、统计次数和得分、模拟走迷宫过程等功能。但是代码中并未实现过程回放的功能,如需实现过程回放,可以在 exploreMaze 函数中添加一些代码来记录走迷宫的路径,并在结束时打印出来。

C++ 迷宫游戏代码实现:自动生成、探索和评分

原文地址: https://www.cveoy.top/t/topic/qp6S 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录