Rectangle rect;
private IPathFinder PathFinder = null;
private byte[,] Matrix = new byte[1024, 1024]; //尋路用二維矩陣
private int GridSize = 20; //單位格子大小
Point Start =new Point(0,0); //移動起點座標
Point End; //移動終點座標
構造初始化矩陣
privatevoid InitializeMatrix()
{
for (int y = 0; y < Matrix.GetUpperBound(1); y++)
{
for (int x = 0; x < Matrix.GetUpperBound(0); x++)
{
//預設值可以通過(非障礙物)在矩陣中用1表示
Matrix[x, y] = 1;
}
}
//構建障礙物(舉例)
for (int i = 0; i < 18; i++)
{
//障礙物在矩陣中用0表示
Matrix[i, 12] = 0;
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = GridSize;
rect.Height = GridSize;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, i * GridSize);
Canvas.SetTop(rect, 12 * GridSize);
}
for (int i = 12; i < 20; i++)
{
//障礙物在矩陣中用0表示
Matrix[18, i] = 0;
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = GridSize;
rect.Height = GridSize;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, 18 * GridSize);
Canvas.SetTop(rect, i * GridSize);
}
for (int i = 12; i < 19; i++)
{
//障礙物在矩陣中用0表示
Matrix[i, 20] = 0;
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = GridSize;
rect.Height = GridSize;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, i * GridSize);
Canvas.SetTop(rect, 20 * GridSize);
}
}
尋徑方式調用:一般我們通過滑鼠左擊事件來確定滑鼠位置
private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point p = e.GetPosition(Carrier);
int x = (int)p.X / GridSize;
int y = (int)p.Y / GridSize;
End = new Point(x, y); //計算終點座標
PathFinder = new PathFinderFast(Matrix);
PathFinder.HeavyDiagonals = true; //深度對角線移動
//PathFinder.Diagonals = true;//對角線
PathFinder.Formula = HeuristicFormula.Manhattan; //使用我個人覺得最快的曼哈頓A*演算法
PathFinder.SearchLimit = 2000; //尋徑範圍,即在多大的範圍內尋找
List<PathFinderNode> path = PathFinder.FindPath(Start, End); //開始尋徑
if (path == null)
{
MessageBox.Show("路徑不存在!");
}
else
{
string output = string.Empty;
for (int i = path.Count - 1; i >= 0; i--)
{
output = string.Format(output
+ "{0}"
+ path[i].X.ToString()
+ "{1}"
+ path[i].Y.ToString()
+ "{2}",
"(", ",", ") ");
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Green);
rect.Width = GridSize;
rect.Height = GridSize;
Carrier.Children.Add(rect);
Canvas.SetLeft(rect, path[i].X * GridSize);
Canvas.SetTop(rect, path[i].Y * GridSize);
}
MessageBox.Show("路徑座標分別為:" + output);
}
}
當然這裡還要調用最主要的尋徑的dll ,這個是尋徑的精華,附上源碼/Files/Caceolod/SilverGame.zip