- Home /
How to randomize my maze generation algorithm(DFS & stacks)
I'm using DFS algorithm with a stack data structure where the logic so far while (stack is not empty){ pop last added cell mark as visited explore all available children(yet to be visited) in the following order left,right,top, down push to stack } while this does traverse the whole maze it does so in a very organized fashion which is down up right left
my question is how can I make it random?
code:
while ( nodeList.Count > 0) {
Node temp = nodeList.Pop();
temp.visited = true;
if (temp.left!=null && temp.left.visited == false) {
nodeList.Push(temp.left);
}
if (temp.right != null && temp.right.visited == false)
{
nodeList.Push(temp.right);
}
if (temp.up != null && temp.up.visited == false)
{
nodeList.Push(temp.up);
}
if (temp.down != null && temp.down.visited == false)
{
nodeList.Push(temp.down);
}
yield return new WaitForSeconds(1f);
}
Answer by MasterLG · Jun 21, 2016 at 09:36 AM
Perhaps consider this in place of all the if statements:
switch (Random.Range(0, 3)) {
case 0:
if (temp.left!=null && temp.left.visited == false)
{
nodeList.Push(temp.left);
}
break;
case 1:
if (temp.right != null && temp.right.visited == false)
{
nodeList.Push(temp.right);
}
break;
case 2:
if (temp.up != null && temp.up.visited == false)
{
nodeList.Push(temp.up);
}
break;
case 3:
if (temp.down != null && temp.down.visited == false)
{
nodeList.Push(temp.down);
}
break;
}
EDIT: There is a flaw in the above code wherein it will only attempt one direction at a time.
This new code is not the most elegant thing in the world, but it takes all 4 possible directions into consideration, then randomizes the order they're in, and then attempts all of them in the new order.
int[] direction = new int[] { 0, 1, 2, 3 };
for (int d = 0; d < direction.Length; d++) {
int r = Random.Range(0, 3);
int swap = direction[d];
direction[d] = direction[r];
direction[r] = swap;
}
foreach (int d in direction) {
switch (d) {
case 0:
if (temp.left!=null && temp.left.visited == false)
{
nodeList.Push(temp.left);
}
break;
case 1:
if (temp.right != null && temp.right.visited == false)
{
nodeList.Push(temp.right);
}
break;
case 2:
if (temp.up != null && temp.up.visited == false)
{
nodeList.Push(temp.up);
}
break;
case 3:
if (temp.down != null && temp.down.visited == false)
{
nodeList.Push(temp.down);
}
break;
}
}
but what happens in case a chosen neighbor didn't exist?
Ah, yeah, bad oversight from me. It does only check one direction at a time. I edited my answer with a newer iteration. This new stuff uses a related structure but checks all directions.