4
\$\begingroup\$

What's the simplest way to generate a random "path" for a level in a game? I don't know what search terms I should use to read more. I've looked into maze generation but thats not quite right.

The end result should look like this:

pipes

\$\endgroup\$
1
  • 1
    \$\begingroup\$ For a more "controlled" random, you might want to use something akin to Perlin Noise. \$\endgroup\$
    – notlesh
    Nov 26, 2011 at 23:35

1 Answer 1

3
\$\begingroup\$

As long as you don't want to go "back", meaning that your path goes only into a single direction (let's assume it is going downwards on your image), you can use the following C# code to easily generate those paths:

[Flags]
public enum Direction
{
  Down=1,
  Left=2,
  Right=4
}

public class Path : List<Direction> {}

public Direction GetNewDirection(Direction allowed, Random rnd)
{
  Direction newd;
  int maxd = Enum.GetValues(typeof(Direction)).Length;
  int[] vals = (int[])Enum.GetValues(typeof(Direction));
  do
  {
  var t = rnd.Next(0,maxd);
   newd = (Direction) vals[t];
  }
  while ((newd & allowed) == 0);
  return newd;
}

public Path GenerateRandomPath(int startx, int starty, int endx, int endy, double prob)
{
   Path newpath = new Path();
   Random rnd = new Random();

   int curx = startx; int cury = starty; Direction curd = Direction.Right;
   Direction newd = curd;   

   while (!(curx == endx && cury == endy))
   {
     if (rnd.NextDouble() <= prob) // let's generate a turn
     {

       do
       {
        if (curx == endx) newd = GetNewDirection(Direction.Left | Direction.Down, rnd);
        else if (cury == endy) newd = Direction.Right;
        else if (curx <= 0) newd =  GetNewDirection(Direction.Right | Direction.Down, rnd);
        else newd =  GetNewDirection(Direction.Right | Direction.Down | Direction.Left, rnd);

       }
       while ( (newd | curd) == (Direction.Left | Direction.Right)); // excluding going back

       newpath.Add(newd);
       curd = newd;
       switch(newd)
       {
        case Direction.Left:
          curx--; 
          break;
        case Direction.Right:
          curx++;
          break;
          case Direction.Down:
          cury++;
          break;
       }
     }

   }


   return newpath;
}

You can generate the path by calling it:

var mynewpath = GenerateRandomPath(0,0,10,10,0.3);

Here the first four parameters are start and end coordinates of your field (determining the dimensions) and the last parameter is the curving probability. Hope it helps...

\$\endgroup\$
1
  • \$\begingroup\$ +1 For having a variable called newd. Also, for a fairly straightforward and simple solution. \$\endgroup\$ Nov 27, 2011 at 6:57

You must log in to answer this question.