// Maze Generator.
// Worthless Bums 2012.


// Ggenerate a maze.
function generateSpecifiedMaze (%mazeType, %sizeX, %sizeY)
{//echo("generateSpecifiedMaze()");
	// Switch by maze type.
	switch (%mazeType)
	{
		case 0:	// Eller maze.
			%sizeX = 16;
			%sizeY = 32;
			generateSpecifiedEllerMaze(%sizeX, %sizeY);
	}
}
//Generates the specified Eller maze.
function generateSpecifiedEllerMaze (%sizeX, %sizeY, %startX, %startY)
{//echo("generateSpecifiedEllerMaze()");
	// Initialize $mazeArray.
	$mazeArray[64, 64] = 0;
	
	// Step 1: Initialize the cells of the first row to each exist in their own set.
	for (%x = %startX; %x < %sizeX; %x++)
	{
		$mazeArray[%x, 0] = %x;
	}
	
	for (%y = %startY; %y < %sizeY; %y++)
	{
		// Step 2: Now, randomly join adjacent cells, but only if they are not in the same set.
		//		   When joining adjacent cells, merge the cells of both sets into a single set,
		//		   indicating that all cells in both sets are now connected (there is a path
		//		   that connects any two cells in the set).
		for (%x = %startX; %x < %sizeX; %x++)
		{
			// Choose two random cells.
			do
			{
				%x1 = getRandom(%startX, %sizeX);
				%x2 = getRandom(%startX, %sizeX);
			} while (%x1 != %x2)
			
			if ($mazeArray[%x1, %y] != $mazeArray[%x2, %y])
			{
				// Join the cells into the same set.
				// NOTE: We'll do latter into the former.
				$mazeArray[%x2, %y] = $mazeArray[%x1, %y];
			}
		}
		
		// Step 3: For each set, randomly create vertical connections downward to the next row.
		//		   Each remaining set must have at least one vertical connection. The cells in
		//		   the next row thus connected must share the set of the cell above them.
		for (%x = %startX; %x < %sizeX; %x++)
		{
			%verticalConnection = getRandom(1, 100);
			if (%verticalConnection <= 75)
			{
				$mazeArray[%x, %y] = $mazeArray[%x, %y - 1];
			}
		}
	}
}
// Displays the current maze.
function echoMaze ()
{//echo("echoMaze()");
	// Ranges.
	%startx = 32;
	%starty = 32;
	
	// Loop through and echo dungeon map.
	for (%x = 0; %x < %startx; %x++)
	{
        %line = "";
		
        for (%y = 0; %y < %starty; %y++)
		{
            %line = %line @ $mazeArray[%x, %y] @ " ";
		}
		
        echo(%line);
	}
}