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引用到本編輯器中即可以實現A*尋路模擬:
IPathFinder pathFinder;
List<Rectangle> pathRect = new List<Rectangle>();
//模擬A*尋路
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]);
int start_y = Convert.ToInt32(str[2]);
str = end.Split('_');
int end_x = Convert.ToInt32(str[1]);
int end_y = Convert.ToInt32(str[2]);
pathFinder = new PathFinderFast(ObstructionMatrix);
List<PathFinderNode> 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).ToString());
string result = "";
RemoveRect();
for (int i = 0; i < path.Count; i++) {
result += string.Format("{0}_{1}", path[i].X, path[i].Y);
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);
}
}
}