C++写简单的迷宫

文章基于C++和操作系统等方面的基础知识,迷宫程序有些不太完善,欢迎各位大佬提建议哦

编译器DEV-C++ 5.11

#include <iostream>
#include <vector>
#include <stack>
#include <stdlib.h>
#include <time.h>
#include <conio.h> // 用于_getch()
#include <thread> // 用于线程
#include <chrono> // 用于时间操作
#include <atomic> // 用于原子操作

using namespace std;

const char WALL = '#';
const char PATH = ' ';
const char START = 'S';
const char END = 'E';
const char PLAYER = 'P';
const char VISITED = '.'; // 表示玩家访问过的路径

struct Position {
    int x, y;
};

class Maze {
private:
    int size;
    vector<vector<char>> grid;
    Position start, end, player;
    int moves;
    int difficulty;
    vector<Position> path; // 存储玩家走过的路径
    atomic<int> countdown; // 倒计时秒数,使用原子操作以确保线程安全
    atomic<bool> gameFinished; // 标记游戏是否结束
    int score; // 玩家的分数

public:
    Maze(int n, int diff) : size(n), difficulty(diff), moves(0), countdown(60), gameFinished(false), score(0) {
        srand(time(NULL));
        generateMaze();
    }
    void calculateScore() {
        // 分数计算公式可以根据需要调整
        int timeBonus = countdown; // 剩余时间作为时间奖励
        int difficultyBonus = difficulty; // 难度奖励
        score = timeBonus * difficultyBonus;
    }
    
    void generateMaze() {
        grid.resize(size, vector<char>(size, WALL));

        // 初始化起点
        start = {1, 1};
        grid[start.x][start.y] = PATH;

        // 使用回溯算法生成迷宫
        stack<Position> positions;
        positions.push(start);
        while (!positions.empty()) {
            Position current = positions.top();
            positions.pop();
            vector<Position> neighbors = getUnvisitedNeighbors(current);
            if (!neighbors.empty()) {
                positions.push(current);
                int randIndex = rand() % neighbors.size();
                Position next = neighbors[randIndex];
                grid[next.x][next.y] = PATH;
                grid[(current.x + next.x) / 2][(current.y + next.y) / 2] = PATH;
                positions.push(next);
            }
        }

        // 设置终点
        end = {size - 2, size - 2};
        grid[end.x][end.y] = PATH;

        player = start;
    }

    vector<Position> getUnvisitedNeighbors(Position p) {
        vector<Position> neighbors;
        vector<Position> directions = {{0, 2}, {2, 0}, {0, -2}, {-2, 0}};
        for (auto& d : directions) {
            Position next = {p.x + d.x, p.y + d.y};
            if (next.x > 0 && next.x < size - 1 && next.y > 0 && next.y < size - 1 && grid[next.x][next.y] == WALL) {
                neighbors.push_back(next);
            }
        }
        return neighbors;
    }
    void printMazeWithCountdown() {
        system("cls"); // 清屏
        cout << "倒计时: " << countdown << "秒   分数: " << score << endl; // 显示倒计时和分数
        for (int i = 0; i < size; ++i) {
            for (int j = 0; j < size; ++j) {
                if (player.x == i && player.y == j) {
                    cout << PLAYER; // 显示玩家位置
                } else if (end.x == i && end.y == j) {
                    cout << END; // 显示终点位置
                } else {
                    cout << grid[i][j]; // 显示迷宫的其他部分
                }
            }
            cout << endl;
        }
    }
   void printMaze() {
        system("cls"); // 清屏
        cout << "倒计时: " << countdown << "秒" << endl; // 显示倒计时
        for (int i = 0; i < size; ++i) {
            for (int j = 0; j < size; ++j) {
                if (player.x == i && player.y == j) {
                    cout << PLAYER; // 显示玩家位置
                } else if (end.x == i && end.y == j) {
                    cout << END; // 显示终点位置
                } else {
                    cout << grid[i][j]; // 显示迷宫的其他部分
                }
            }
            cout << endl;
        }
    }

     void outputPath() {
        // 将走过的路径标记在迷宫上
        for (const auto& pos : path) {
            grid[pos.x][pos.y] = VISITED;
        }
        printMaze();
    }
   void playMaze() {
        auto startTime = clock();
        thread timerThread(&Maze::startCountdown, this); // 创建一个线程来处理倒计时

        char move;
        bool moved = false;
        while (!gameFinished) {
            if (_kbhit()) {
                move = _getch();
                if (makeMove(move)) {
                    gameFinished = true; // 玩家到达终点,游戏结束
                    break;
                }
                moved = true;
            } else {
                printMazeWithCountdown(); // 时间不依赖于玩家移动而刷新
                moved = false;
            }
            this_thread::sleep_for(chrono::milliseconds(100)); // 暂停100毫秒以减少CPU使用率
        }

        timerThread.join(); // 等待倒计时线程结束

        if (gameFinished) {
            clock_t endTime = clock();
            double timeTaken = double(endTime - startTime) / CLOCKS_PER_SEC;
            calculateScore(); // 计算分数
            cout << "游戏结束! 总移动次数: " << moves << " 用时: " << timeTaken << "秒   分数: " << score << endl;
            if (player.x == end.x && player.y == end.y) {
                cout << "恭喜你到达终点!" << endl;
            } else {
                cout << "时间耗尽,游戏失败!" << endl;
            }
            
        // 询问用户是否输出路径
        char output;
        cout << "是否输出走过的路径?(y/n): ";
        cin >> output;
        if (output == 'y' || output == 'Y') {
            outputPath();
          } 
        }
    }

    void startCountdown() {
        while (countdown > 0 && !gameFinished) {
            this_thread::sleep_for(chrono::seconds(1)); // 暂停1秒
            countdown--;
        }
        if (countdown <= 0) {
            gameFinished = true; // 时间耗尽,游戏结束
        }
    }

    bool makeMove(char move) {
        int newX = player.x, newY = player.y;
        switch (move) {
            case 'w': newX--; break;
            case 's': newX++; break;
            case 'a': newY--; break;
            case 'd': newY++; break;
            default: return false;
        }

        if (newX >= 0 && newX < size && newY >= 0 && newY < size && grid[newX][newY] != WALL) {
            // 记录路径
            path.push_back({newX, newY});
            player.x = newX;
            player.y = newY;
            moves++;
            return player.x == end.x && player.y == end.y;
        }
        return false;
    }

};
int main() {
    int n, difficulty;
    cout << "请输入迷宫的大小N(奇数,例如5): ";
    cin >> n;
    cout << "请选择迷宫难度(1-简单,2-中等,3-困难): ";
    cin >> difficulty;
    while (difficulty < 1 || difficulty > 3) {cout << "无效的难度级别,请重新输入(1-简单,2-中等,3-困难): ";
        cin >> difficulty;
    }

    Maze maze(n, difficulty);
    maze.playMaze();

    return 0;
}

注意:这里输入迷宫大小为奇数,偶数有点问题。

  • 17
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很高兴为您回答这个问题!以下是一个简单迷宫求解程序: ```c #include <stdio.h> // 定义迷宫大小和路径 #define ROW_SIZE 10 #define COL_SIZE 10 int maze[ROW_SIZE][COL_SIZE] = { {1,1,1,1,1,1,1,1,1,1}, {0,0,1,0,0,0,1,0,1,1}, {1,0,1,0,1,0,1,0,1,1}, {1,0,1,0,1,0,0,0,0,1}, {1,0,1,1,1,1,1,1,0,1}, {1,0,1,0,0,0,0,0,0,1}, {1,0,1,0,1,1,1,1,0,1}, {1,0,0,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1}, {0,0,0,0,0,0,0,0,0,1} }; int path[ROW_SIZE][COL_SIZE]; // 定义方向 #define EAST 0 #define NORTH 1 #define WEST 2 #define SOUTH 3 // 定义堆栈 #define MAX_STACK_SIZE 100 int stack[MAX_STACK_SIZE]; int top = -1; void push(int item) { if (top >= MAX_STACK_SIZE - 1) { printf("stack overflow\n"); return; } stack[++top] = item; } int pop() { if (top < 0) { printf("stack underflow\n"); return -1; } return stack[top--]; } int is_empty() { return top < 0; } int get_direction(int r, int c, int direction) { switch (direction) { case EAST: return maze[r][c + 1]; case NORTH: return maze[r - 1][c]; case WEST: return maze[r][c - 1]; case SOUTH: return maze[r + 1][c]; } } void print_path() { printf("Path:\n"); for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { printf("%d ", path[i][j]); } printf("\n"); } } void solve_maze(int r, int c, int direction) { push(direction); while (!is_empty()) { direction = pop(); path[r][c] = 1; if (r == ROW_SIZE - 1 && c == COL_SIZE - 1) { print_path(); return; } for (int i = direction + 1; i < direction + 5; i++) { int new_direction = i % 4; if (get_direction(r, c, new_direction) == 0) { switch (new_direction) { case EAST: c++; break; case NORTH: r--; break; case WEST: c--; break; case SOUTH: r++; break; } push(new_direction); break; } } } printf("No solution found\n"); } int main() { solve_maze(0, 0, EAST); return 0; } ``` 该程序使用堆栈和回溯来解决迷宫问题。迷宫的大小由 `ROW_SIZE` 和 `COL_SIZE` 定义,路径由 `maze` 数组表示。程序搜索所有可能的路径,打印出正确路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值