好吧,这是我更新的代码。它没有减速,但没有路径出现。
public static IntPosition[] GetPath(BlockType[,] blocks, IntPosition start, IntPosition end, int threshhold)
{
List<Node> MapNodes = new List<Node>();
MapNodes.Add(new Node() { Position = start });
bool[,] explored = new bool[blocks.GetLength(0), blocks.GetLength(1)];
explored[start.X, start.Y] = true;
int? endNode = null;
int index = 0;
while (endNode == null && index < threshhold)
{
List<Node> addNodes = new List<Node>();
foreach (Node n in MapNodes)
{
//left
if (n.Position.X - 1 >= 0)
if (explored[n.Position.X - 1, n.Position.Y] == false)
if (blocks[n.Position.X - 1, n.Position.Y] == BlockType.Open)
{
int i = addNodes.Count;
addNodes.Add(new Node() { Position = new IntPosition(n.Position.X - 1, n.Position.Y), ParentNode = n });
explored[n.Position.X - 1, n.Position.Y] = true;
if (addNodes[i].Position == end)
endNode = i;
}
//right
if (n.Position.X + 1 <= blocks.GetLength(0) - 1)
if (explored[n.Position.X + 1, n.Position.Y] == false)
if (blocks[n.Position.X + 1, n.Position.Y] == BlockType.Open)
{
int i = addNodes.Count;
addNodes.Add(new Node() { Position = new IntPosition(n.Position.X + 1, n.Position.Y), ParentNode = n });
explored[n.Position.X + 1, n.Position.Y] = true;
if (addNodes[i].Position == end)
endNode = i;
}
//up
if (n.Position.Y - 1 >= 0)
if (explored[n.Position.X, n.Position.Y - 1] == false)
if (blocks[n.Position.X, n.Position.Y - 1] == BlockType.Open)
{
int i = addNodes.Count;
addNodes.Add(new Node() { Position = new IntPosition(n.Position.X, n.Position.Y - 1), ParentNode = n });
explored[n.Position.X, n.Position.Y - 1] = true;
if (addNodes[i].Position == end)
endNode = i;
}
//down
if (n.Position.Y + 1 <= blocks.GetLength(1))
if (explored[n.Position.X, n.Position.Y + 1] == false)
if (blocks[n.Position.X, n.Position.Y + 1] == BlockType.Open)
{
int i = addNodes.Count;
addNodes.Add(new Node() { Position = new IntPosition(n.Position.X, n.Position.Y + 1), ParentNode = n });
explored[n.Position.X, n.Position.Y + 1] = true;
if (addNodes[i].Position == end)
endNode = i;
}
}
MapNodes.AddRange(addNodes);
index++;
}
if (endNode == null)
return new IntPosition[] { };
else
{
List<IntPosition> path = new List<IntPosition>();
path.Add(end);
Node CurrentNode = (MapNodes[(int)endNode].ParentNode);
bool endReached = false;
while (endReached == false)
{
path.Add(CurrentNode.Position);
if (CurrentNode.Position == start)
endReached = true;
else
CurrentNode = CurrentNode.ParentNode;
}
path.Reverse();
return path.ToArray();
}
}
public class IntPosition
{
public int X;
public int Y;
public IntPosition(int x, int y)
{
X = x;
Y = y;
}
public IntPosition() { X = 0; Y = 0; }
public override bool Equals(object obj)
{
return ((IntPosition)obj).X == X && ((IntPosition)obj).Y == Y;
}
}