Sign up ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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:


share|improve this question

migrated from Nov 26 '11 at 22:49

This question came from our site for professional and enthusiast programmers.

For a more "controlled" random, you might want to use something akin to Perlin Noise. – stephelton Nov 26 '11 at 23:35

1 Answer 1

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:

public enum Direction

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));
  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

        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

       curd = newd;
        case Direction.Left:
        case Direction.Right:
          case Direction.Down:


   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...

share|improve this answer
+1 For having a variable called newd. Also, for a fairly straightforward and simple solution. – Richard Marskell - Drackir Nov 27 '11 at 6:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.