Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- IEnumerator DesignMaze()
- {
- // assign tile instances
- tiles = new Tile[sizeX,sizeZ];
- for (int x=0; x<sizeX; ++x)
- for (int z=0; z<sizeZ; ++z)
- {
- tiles[x,z] = new Tile(x,z);
- }
- // set tile neighbours
- for (int x=0; x<sizeX; ++x)
- for (int z=0; z<sizeZ; ++z)
- {
- if (z<sizeZ-1) { tiles[x,z].neighbours[0] = tiles[x,z+1]; } // N 0
- if (x<sizeX-1) { tiles[x,z].neighbours[1] = tiles[x+1,z]; } // E 1
- if (z>0 ) { tiles[x,z].neighbours[2] = tiles[x,z-1]; } // S 2
- if (x>0 ) { tiles[x,z].neighbours[3] = tiles[x-1,z]; } // W 3
- }
- int[] opposite = new int[] { 2,3,0,1 };
- Stack<Tile> stack = new Stack<Tile>();
- int unvisitedCells = sizeX*sizeZ;
- Tile current = tiles[Random.Range(0,sizeX), Random.Range(0,sizeZ)];
- current.visited = true; --unvisitedCells;
- bool start = true;
- while (unvisitedCells > 0)
- {
- int[] unvisitedNeighbours = current.UnvisitedNeighbours();
- if (unvisitedNeighbours.Length > 0)
- {
- int pickNum = unvisitedNeighbours[Random.Range(0,unvisitedNeighbours.Length)];
- if (start)
- {
- start = false;
- startPos = new Vector3(current.x*tileSize*2,0,current.z*tileSize*2);
- startRot = Quaternion.Euler( 0, pickNum*90, 0 );
- }
- stack.Push(current);
- // break wall:
- current.walls[pickNum] = false;
- current.neighbours[pickNum].walls[ opposite[pickNum] ] = false;
- current = current.neighbours[pickNum];
- current.visited = true; --unvisitedCells;
- } else {
- current = stack.Pop();
- }
- }
- yield return null;
- }
- class Tile {
- public bool visited = false;
- public bool[] walls;
- public Tile[] neighbours;
- public int x;
- public int z;
- public Tile(int x, int z)
- {
- this.x = x;
- this.z = z;
- walls = new bool[] { true, true, true, true }; // N E S W
- neighbours = new Tile[4]; // N E S W
- }
- public int[] UnvisitedNeighbours ()
- {
- List<int> unvisited = new List<int>();
- for (int n=0; n<4; ++n)
- {
- if (neighbours[n] != null && !neighbours[n].visited)
- {
- unvisited.Add(n);
- }
- }
- return unvisited.ToArray();
- }
- public override string ToString ()
- {
- return string.Format ("[Tile "+x+","+z+"]");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement