samedi 1 janvier 2022

Make a random maze in C++

I want to make a random maze generator, but I have no idea how I can make a random path (and make the inner walls of the maze). I know it has something to do with srand(), but I dont know how to work from there. The maze has to look like the picture below, where the +, | and - are walls and the dots are the path. Can anyone help me?

Thanks in advance :D

[![Maze][1]][1]

#include <vector>
#include <stack>
#include <sstream>
#include <time.h>

class Maze {
    private:
        int mazeHeight;
        int mazeWidth;
        int seedValue;
        std::vector <std::vector <char>> Maze;
    public:
        void checkuserInput(int Input1, int Input2);
        void mazeConstructor(int x, int y, int z, std::vector <std::vector <char>> vect);
        void findPath();
        void printMaze();
};
// Check if user input is valid
void checkUserInput(int Input1, int Input2) {
    int Height;
    int Width;
    if (!(Input1 >> Height)) {
        throw std::runtime_error ("Invalid input");
    }
    if (!(Input2 >> Height)) {
        throw std::runtime_error ("Invalid input");
    }
} 
//Make the variables accesible
void Maze::mazeConstructor(int x, int y, int z, std::vector <std::vector <char>> vect) {
    mazeHeight = x;
    mazeWidth = y;
    seedValue = z;
    Maze = vect;
}
// FIXME make the random path
void Maze::findPath() {
    int row = 1;
    int column = 1;
    Maze[row][column] = '.';
}
// Print the maze
void Maze::printMaze() {
    for (int i = 0; i < Maze.size(); i++) {
        for (int j = 0; j < Maze[0].size(); j++) {
            std::cout << Maze[i][j];
        }
        std::cout << std::endl;
    }
}

// Get command line arguements 
int main(int argc, char* argv[]) {
    Maze test;
    srand (time(0));
    int Height;
    int Width;
    int seedValue;
    Height = atoi(argv[2]);
    Width = atoi(argv[2]);
    try {
        checkUserInput(Height, Width);
    }
    catch(std::runtime_error& e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    if (argc > 3) {
        seedValue = atoi(argv[3]);
    } else {
        seedValue = rand();
    }
    std::vector <std::vector <char>> Maze (Height * 3 + 1, std::vector <char> (Width * 5 + 1, ' '));
    test.mazeConstructor(Height, Width, seedValue, Maze);
    test.findPath();
    test.printMaze();
}```


  [1]: https://i.stack.imgur.com/j8T9e.png
  [2]: https://i.stack.imgur.com/J7FOM.png



Aucun commentaire:

Enregistrer un commentaire