3) 設定障礙物
為 ScrollViewer 註冊滑鼠左鍵點擊與移動事件,配合邏輯實現繪製與擦除:
if (grid == null) return;
Point p = e.GetPosition(ObstructionViewer);
if (p.X < 738 && p.Y < 551)
{
p = e.GetPosition(Map);
test.Text = string.Format("當前座標 x:{0} y:{1}", (int)p.X, (int)p.Y);
SetObstructionMatrix((int)(p.X / GridWidthSlider.Value), (int)(p.Y / GridHeightSlider.Value), 0);
}
4) 模擬 A* 尋路
繪製完障礙物後,自繪起點終點,引用教程 A* DLL 實現模擬:
IPathFinder pathFinder;
List pathRect = new List();
private void FindPath_Click(object sender, RoutedEventArgs e)
{
if (grid == null || start == "" || end == "") return;
string[] str = start.Split('_');
int start_x = Convert.ToInt32(str[1]), start_y = Convert.ToInt32(str[2]);
str = end.Split('_');
int end_x = Convert.ToInt32(str[1]), end_y = Convert.ToInt32(str[2]);
pathFinder = new PathFinderFast(ObstructionMatrix);
List path = pathFinder.FindPath(new Point(start_x, start_y), new Point(end_x, end_y));
if (path == null) { MessageBox.Show("路徑不存在!"); }
else
{
textBlock3.Text = string.Format("耗時:{0}秒", Math.Round(pathFinder.CompletedTime, 8));
RemoveRect();
for (int i = 0; i < path.Count; i++)
{
SetRect(new SolidColorBrush(Colors.White), new SolidColorBrush(Colors.Black), GridWidthSlider.Value * 2 / 3, GridHeightSlider.Value * 2 / 3, GridWidthSlider.Value * 2 / 3, GridHeightSlider.Value * 2 / 3, path[i].X, path[i].Y);
}
}
}
