Browse code

Add callback during generation

Robert Cranston authored on 21/05/2025 01:50:09
Showing 2 changed files

... ...
@@ -5,6 +5,7 @@ A simple C++11 command line maze generator.
5 5
 Features:
6 6
 
7 7
 -   Printing
8
+-   Callback during generation
8 9
 -   Algorithms
9 10
     -   Hunt And Kill
10 11
         -   Handles mazes of any size
... ...
@@ -1,6 +1,8 @@
1
+#include <chrono>
1 2
 #include <cstdlib>
2 3
 #include <ctime>
3 4
 #include <iostream>
5
+#include <thread>
4 6
 #include <vector>
5 7
 
6 8
 struct Maze
... ...
@@ -43,7 +45,8 @@ struct Maze
43 45
     std::vector<Cell> cells;
44 46
 };
45 47
 
46
-Maze hunt_and_kill(int w, int h, unsigned seed)
48
+template<typename C = void(*)(Maze &)>
49
+Maze hunt_and_kill(int w, int h, unsigned seed, C callback = [](Maze &){})
47 50
 {
48 51
     auto maze = Maze(w, h, Maze::WALL);
49 52
     std::srand(seed);
... ...
@@ -55,6 +58,8 @@ Maze hunt_and_kill(int w, int h, unsigned seed)
55 58
     auto done = false;
56 59
     while (!done)
57 60
     {
61
+        // Call callback.
62
+        callback(maze);
58 63
         // Find number of neighbors.
59 64
         auto n = 0;
60 65
         for (auto ny = -2; ny <= 2; ny += 2)
... ...
@@ -100,7 +105,11 @@ Maze hunt_and_kill(int w, int h, unsigned seed)
100 105
 
101 106
 int main()
102 107
 {
108
+    using namespace std::chrono;
103 109
     auto seed = (unsigned)std::time(nullptr);
104
-    auto maze = hunt_and_kill(80/2, 24-1, seed);
110
+    auto maze = hunt_and_kill(80/2, 24-1, seed, [](Maze & maze) {
111
+        maze.print();
112
+        std::this_thread::sleep_for(milliseconds(20));
113
+    });
105 114
     maze.print();
106 115
 }