C++ 迷宫游戏:递归回溯算法实现迷宫探索

本项目使用 C++ 语言开发了一个迷宫游戏,该游戏使用递归回溯算法自动生成迷宫,并提供游戏过程模拟、回放和得分计算等功能。玩家可以通过键盘控制角色在迷宫中探索,最终到达终点。

游戏功能

  • 自动生成迷宫: 使用递归回溯算法自动生成不同大小和难度的迷宫。
  • 游戏过程模拟: 玩家可以通过键盘输入选择上下左右四个方向,程序会根据玩家的选择更新角色位置并实时显示迷宫状态。
  • 回放功能: 程序记录玩家的每一步操作,并提供回放功能,让玩家可以重新观看游戏过程。
  • 得分计算: 根据游戏时间和迷宫难度等级计算得分。

代码示例

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

using namespace std;

const char WALL = '■';
const char PATH = ' '; 
const char START = 'S';
const char END = 'E';

struct Position {
    int x;
    int y;
};

class MazeGame {
public:
    MazeGame(int size, int difficulty) {
        this->size = size;
        this->difficulty = difficulty;
        maze.resize(size, vector<char>(size, WALL));
        visited.resize(size, vector<bool>(size, false));
        srand(time(nullptr));
    }

    void generateMaze() {
        start = randomPosition();
        end = randomPosition();
        while (start.x == end.x && start.y == end.y) {
            end = randomPosition();
        }
        maze[start.x][start.y] = START;
        maze[end.x][end.y] = END;
        visited[start.x][start.y] = true;
        generateMazeRecursive(start.x, start.y);
    }

    void playGame() {
        Position current = start;
        int steps = 0;
        int score = 0;
        vector<Position> history;
        history.push_back(current);

        while (current.x != end.x || current.y != end.y) {
            printMaze();
            cout << "Score: " << score << endl;
            cout << "Steps: " << steps << endl;
            cout << "Enter the direction (WASD): ";
            char direction;
            cin >> direction;

            Position next = current;
            if (direction == 'w' || direction == 'W') {
                next.x--;
            } else if (direction == 'a' || direction == 'A') {
                next.y--;
            } else if (direction == 's' || direction == 'S') {
                next.x++;
            } else if (direction == 'd' || direction == 'D') {
                next.y++;
            }

            if (isValidMove(next)) {
                current = next;
                history.push_back(current);
                steps++;
                score += calculateScore();
            } else {
                cout << "Invalid move!" << endl;
            }
        }

        printMaze();
        cout << "Score: " << score << endl;
        cout << "Steps: " << steps << endl;
        cout << "Congratulations! You reached the end of the maze!" << endl;
    }

    void replayGame() {
        for (const Position& pos : history) {
            printMaze();
            cout << "Score: " << score << endl;
            cout << "Steps: " << steps << endl;
            cout << "Replaying..." << endl;
            maze[pos.x][pos.y] = '@'; // mark the path in replay
            this_thread::sleep_for(chrono::milliseconds(500));
        }
        printMaze();
        cout << "Score: " << score << endl;
        cout << "Steps: " << steps << endl;
        cout << "Replay finished!" << endl;
    }

private:
    int size;
    int difficulty;
    vector<vector<char>> maze;
    vector<vector<bool>> visited;
    Position start;
    Position end;
    vector<Position> history;
    int steps = 0;
    int score = 0;

    Position randomPosition() {
        Position pos;
        pos.x = rand() % size;
        pos.y = rand() % size;
        return pos;
    }

    void generateMazeRecursive(int x, int y) {
        vector<char> directions = {'U', 'D', 'L', 'R'};
        random_shuffle(directions.begin(), directions.end());

        for (char direction : directions) {
            int nextX = x;
            int nextY = y;

            if (direction == 'U') {
                nextX--;
            } else if (direction == 'D') {
                nextX++;
            } else if (direction == 'L') {
                nextY--;
            } else if (direction == 'R') {
                nextY++;
            }

            if (nextX >= 0 && nextX < size && nextY >= 0 && nextY < size && !visited[nextX][nextY]) {
                visited[nextX][nextY] = true;
                maze[nextX][nextY] = PATH;
                generateMazeRecursive(nextX, nextY);
            }
        }
    }

    bool isValidMove(const Position& pos) {
        if (pos.x < 0 || pos.x >= size || pos.y < 0 || pos.y >= size) {
            return false;
        }
        return maze[pos.x][pos.y] == PATH;
    }

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

    int calculateScore() {
        int baseScore = size * difficulty;
        return baseScore - steps;
    }
};

int main() {
    int size, difficulty;
    cout << "Enter the size of the maze: ";
    cin >> size;
    cout << "Enter the difficulty level (1-3): ";
    cin >> difficulty;

    MazeGame game(size, difficulty);
    game.generateMaze();
    game.playGame();

    char replay;
    cout << "Do you want to replay the game? (Y/N): ";
    cin >> replay;

    if (replay == 'Y' || replay == 'y') {
        game.replayGame();
    }

    return 0;
}

项目结构

maze_game/
├── maze_game.cpp
└── README.md

运行方法

  1. 将代码保存为 maze_game.cpp 文件。
  2. 使用 C++ 编译器编译代码:g++ maze_game.cpp -o maze_game
  3. 运行可执行文件:./maze_game

注意事项

  • 代码中使用了 this_thread::sleep_for 函数来控制回放速度,需要包含 <thread> 头文件。
  • 游戏难度等级由 1-3 来表示,数字越大难度越大。
  • 可以根据需要修改代码中的参数和规则来调整游戏难度和玩法。

未来展望

  • 添加图形界面,使用图形库来显示迷宫和角色。
  • 添加更多游戏元素,例如陷阱、道具等。
  • 支持多人游戏模式。

总结

本项目实现了一个简单的 C++ 迷宫游戏,为学习 C++ 编程语言和算法提供了一个实例。通过学习本项目的代码,可以学习到如何使用递归回溯算法生成迷宫,以及如何使用 C++ 语言实现游戏过程模拟、回放和得分计算等功能。

C++ 迷宫游戏:递归回溯算法实现迷宫探索

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

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