我正在尝试使用递归除法来制作迷宫生成器,其解释如下:https://en.wikipedia.org/wiki/Maze_generation_algorithm
第一次迭代对我有用。但是当我多次这样做时,它做得不好。 问题是:我的递归方法是否正确? if和else语句后面跟着返回或回退。
private void DevideRecursive(int pMinX, int pMaxX, int pMinY, int pMaxY)
{
Debug.Log("minx: " + pMinX);
Debug.Log("maxx: " + pMaxX);
Debug.Log("miny: " + pMinY);
Debug.Log("maxy: " + pMaxY);
int randomX = Random.Range(pMinX +1, pMaxX);
int randomY = Random.Range(pMinY +1, pMaxY);
int randomWall = Random.Range(0, 4);
List<GameObject> WalllistX1 = new List<GameObject>();
List<GameObject> WalllistX2 = new List<GameObject>();
List<GameObject> WalllistY1 = new List<GameObject>();
List<GameObject> WalllistY2 = new List<GameObject>();
List<List<GameObject>> MainWallList = new List<List<GameObject>>();
MainWallList.Add(WalllistX1);
MainWallList.Add(WalllistX2);
MainWallList.Add(WalllistY1);
MainWallList.Add(WalllistY2);
//// add a wall on a random x coordinate
for (int x = pMinX; x < pMaxX; x++)
{
GameObject wall = Instantiate(WallHor);
wall.transform.position = new Vector2(tilesize * x + tilesize / 2, tilesize * randomY);
if (x < randomX)
{
WalllistX1.Add(wall);
}
else
{
WalllistX2.Add(wall);
}
}
//// add a wall on a random y coordinate
for (int y = pMinY; y < pMaxY ; y++)
{
GameObject wall = Instantiate(WallVer);
wall.transform.position = new Vector2(tilesize * randomX, tilesize * y + tilesize / 2);
if (y < randomY)
{
WalllistY1.Add(wall);
}
else
{
WalllistY2.Add(wall);
}
}
//make a hole in 3 out of tht 4 walls randomly
for (int i = 0; i < MainWallList.Count; i++)
{
Debug.Log("list" + MainWallList.Count);
if (randomWall != i)
{
Debug.Log("1: " + WalllistX1.Count);
Debug.Log("2: " + WalllistX2.Count);
Debug.Log("3: " + WalllistY1.Count);
Debug.Log("4: " + WalllistY2.Count);
RemoveWall(MainWallList[i]);
}
}
////
////
//// If either of the walls have a cell with only 1 grid stop the recursion
if (randomX - pMinX <= 1 || pMaxY - randomY <= 1)
{
return;
}
else
{
DevideRecursive(pMinX, randomY, randomX, pMaxY);
}
if (pMaxX - randomX <= 1 || pMaxY - randomY <= 1)
{
return;
}
else
{
DevideRecursive(randomY, pMaxX, randomX, pMaxY);
}
if (randomX - pMinX <= 1 || randomY - pMinY <=1)
{
return;
}
else
{
DevideRecursive(pMinX, randomY, pMinY, randomX);
}
if (pMaxX - randomX <= 1 || randomY - pMinY <= 1)
{
return;
}
else
{
DevideRecursive(randomY, pMaxX, pMinY, randomX);
}
}
我的代码做什么(或应该做什么)。在一个矩形迷宫中,在任意点上构建两个彼此垂直的墙。这两个壁将大腔室划分为四个小腔室,每个小腔室由四个壁隔开。随机选择四堵墙中的三堵墙,并在这三堵墙中的每一个的随机点处打开一个单元宽的洞。以这种方式递归继续,直到每个小室在两个方向的任一方向上都具有一个单元的宽度。
这是第一个迭代https://gyazo.com/08e1cb2483fcf841e4d854d001c51647
的快速说明例如,下一次迭代将在左上角。然后minX保持不变。 MaxX成为RandomX。 Y值相同。那么它应该再次做同样的事情(创建2面墙)