Dobrý den,
using System.Collections.Generic;
using System;
namespace MaGa
{
public struct Path
{
public sbyte DirectionX { get; set; }
public sbyte DirectionY { get; set; }
public int X { get; set; }
public int Y { get; set; }
public Path(int x, int y, sbyte directionX, sbyte directionY) : this()
{
DirectionX = directionX;
DirectionY = directionY;
X = x;
Y = y;
}
}
public static class MazeGenerator
{
static Random numberGenerator = new Random();
public static List<MazeObject> Generate(int width, int height)
{
List<MazeObject> output = new List<MazeObject>();
List<Path> path = new List<Path>()
{
new Path(0, 0, 0, 1),
new Path(0, 0, 1, 0)
};
int[,] tile = new int[width, height];
int index, value, x1, y1, x2, y2;
tile[0, 0] = 1;
while(path.Count > 0)
{
index = numberGenerator.Next(path.Count);
Path currentPath = path[index];
x1 = currentPath.X + currentPath.DirectionX;
y1 = currentPath.Y + currentPath.DirectionY;
x2 = x1 + currentPath.DirectionX;
y2 = y1 + currentPath.DirectionY;
path.RemoveAt(index);
try
{
value = tile[x2, y2];
}
catch
{
continue;
}
if(value == 0)
{
tile[x1, y1] = 1;
x2 = x1;
y2 = y1 + 1;
if(Neighbor(ref tile, x2, y2))
path.Add(new Path(x2, y2, 0, 1));
x2 = x1;
y2 = y1 - 1;
if(Neighbor(ref tile, x2, y2))
path.Add(new Path(x2, y2, 0, -1));
x2 = x1 + 1;
y2 = y1;
if(Neighbor(ref tile, x2, y2))
path.Add(new Path(x2, y2, 1, 0));
x2 = x1 - 1;
y2 = y1;
if(Neighbor(ref tile, x2, y2))
path.Add(new Path(x2, y2, -1, 0));
}
}
return output;
}
static bool Neighbor(ref int[,] tile, int x, int y)
{
try
{
return tile[x, y] == 0;
}
catch
{
return false;
}
}
}
}
Není hotovo, každopádně by se cyklus měl ukončit - po určité chvíli. Ovšem nikdy se nevyčerpají všechny cesty - nevidí někdo, prosím, proč?
Děkuji.