Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <vector>
- #include <stack>
- using namespace sf;
- using namespace std;
- VideoMode operator/(VideoMode mode, float cef) {
- return { static_cast<unsigned int> (mode.width / cef),
- static_cast<unsigned int> (mode.height / cef) };
- }
- void eventProcess(RenderWindow& win) {
- Event e;
- while (win.pollEvent(e)) {
- if (e.type == Event::Closed) {
- win.close();
- }
- }
- }
- // n = maximium empty sections in a column
- // m = maximum empty sections in a row
- //false == empty section
- auto genMaze(unsigned int n, unsigned int m) {
- srand(time(nullptr));
- vector< vector<bool> > maze(2 * n + 1, vector<bool>(2 * m + 1, true));
- maze[1][1] = false;
- stack< pair<int, int> > trail;
- trail.push({ 1, 1 });
- while (!trail.empty()) {
- auto [ci, cj] = trail.top();
- vector< pair<int, int> > next, mb = {
- { ci + 2, cj }, { ci - 2, cj },
- { ci, cj + 2 }, { ci, cj - 2 }
- };
- for (auto [i, j] : mb) {
- if (i >= 0 and j >= 0 and i < 2 * n + 1 and j < 2 * m + 1 and maze[i][j]) {
- next.emplace_back(i, j);
- }
- }
- if (next.empty()) {
- trail.pop();
- continue;
- }
- auto [i, j] = next[rand() % next.size()];
- maze[i][j] = false;
- maze[(i + ci) / 2][(j + cj) / 2] = false;
- trail.emplace(i, j);
- }
- return maze;
- }
- int main() {
- RenderWindow window(VideoMode::getDesktopMode() / 1.5, "Maze");
- const int N = 18, M = 30;
- const float rectWidth = (float)window.getSize().x / (2 * M + 1);
- const float rectHeight = (float)window.getSize().y / (2 * N + 1);
- auto maze = genMaze(N, M);
- Clock clock;
- while (window.isOpen()) {
- eventProcess(window);
- if (clock.getElapsedTime().asSeconds() >= 7) {
- maze = genMaze(N, M);
- clock.restart();
- }
- window.clear();
- for (int i = 0; i < 2 * N + 1; i++) {
- for (int j = 0; j < 2 * M + 1; j++) {
- RectangleShape rect({ rectWidth, rectHeight });
- rect.setPosition({ rectWidth * j, rectHeight * i });
- rect.setFillColor((maze[i][j] ? Color::White : Color::Black));
- window.draw(rect);
- }
- }
- window.display();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment