迷路生成可視化(穴掘り法)
https://scrapbox.io/files/645e366bfc8c65001b2554f8.png
コード
code:迷路生成可視化.cpp
# include <Siv3D.hpp>
int32 interval(double& accumulator, double spawnTime) {
int32 n = 0;
for (accumulator += Scene::DeltaTime(); spawnTime <= accumulator; accumulator -= spawnTime)++n;
return n;
}
void Main()
{
double accumulator = 0.0;
double speed = 100;
//定数
enum object { path, wall };
enum direction { up, down, left, right };
constexpr Point dList4 = { {0,-2},{0,2},{-2,0},{2,0} }; //迷路の大きさ(奇数)
constexpr int32 w = 51, h = 51;
Grid<bool> maze(w, h, wall);
Array<Point>stack;
Point pos{ 2 * Random(w / 2 - 1) + 1,2 * Random(h / 2 - 1) + 1 };// 初期位置をランダムに決める(奇数)
stack << pos;
bool checked4 = { false }; while (System::Update()) {
if (SimpleGUI::Button(U"リセット", Vec2{ 50, 5 }))
{
maze = Grid<bool>(w, h, wall);
stack.clear();
pos={ 2 * Random(w / 2 - 1) + 1,2 * Random(h / 2 - 1) + 1 };
stack << pos;
}
SimpleGUI::Slider(U"速度", speed,10.0,500.0, Vec2{ 200, 5 });
//一定時間ごとに
for (auto i:step(interval(accumulator,1.0/speed))) {
if (stack.size()) {
pos = stack.back();
stack.pop_back();
//確認した方向を記録する変数
}
// 方向をランダムに決める
int32 r = Random(3);
// 範囲外に出ないか確認
if (InRange((pos + d).x, 1, w - 1) && InRange((pos + d).y, 1, h - 1)) {
// 既に道になっていないか確認
pos += d;
stack << pos;
}
}
}
}
//描画
constexpr int32 size = 10;
for (auto pos : step(maze.size())){
if (mazepos)Rect(pos * size + Point{ 50,50 }, size).draw(); }
Rect(pos* size + Point{ 50,50 }, size).draw(Palette::Red);
}
}