private int DistanceSquared(Tile a, Tile b) { int deltaX = b.MapLocation.X - a.MapLocation.X; int deltay = b.MapLocation.Y - a.MapLocation.Y; return (deltaX * deltaX) + (deltay * deltay); }
public Path(Tile[,] tiles, Tile start, Tile end) { Entries = new List<Tile>(tiles.GetLength(0) + tiles.GetLength(1)); Length = new Point(tiles.GetLength(0), tiles.GetLength(1)); for (int y = 0; y < Length.Y; y++) { for (int x = 0; x < Length.X; x++) { Entries.Add(tiles[x, y]); } } Start = start; End = end; }
public void AStar(Tile start, Tile end) { List<Tile> open = new List<Tile>(); open.Add(start); List<Tile> closed = new List<Tile>(); Tile l = null; while (l != end && open.Count != 0 && end.Parent == null) { l = FindBestNode(open); if (l.Equals(end)) continue; else { open.Remove(l); closed.Add(l); l.Region = DisplayRegion.Closed; foreach (Tile adj in l.AdjacencyList) { if (adj.Type == TileType.NotPassable || closed.Contains(adj)) continue; if (!open.Contains(adj)) { AddToOpenList(open, adj, l, end); adj.Parent = l; } else { int newDistance = l.DistanceFromStart + DistanceSquared(l, adj); if (newDistance < adj.DistanceFromStart) { adj.Parent = l; adj.DistanceFromStart = newDistance; } } } } } if (end.Parent != null) GeneratePath(start, end); else throw new Exception("Check to make sure that your path is a valid path (monsters can travel along the path from start to finish)"); start.Region = DisplayRegion.Start; }
public void AddToAdjacencyList(Tile t) { if (t == null) return; if (AdjacencyList == null) AdjacencyList = new List<Tile>(); AdjacencyList.Add(t); }
private void AddToOpenList(List<Tile> open, Tile adj, Tile l, Tile end) { adj.DistanceFromStart = l.DistanceFromStart + DistanceSquared(l, adj); adj.DistanceToEnd = DistanceSquared(adj, end); open.Add(adj); }
private void GeneratePath(Tile start, Tile end) { path = new List<Tile>(); Tile p = end.Parent; while (p != start) { path.Insert(0, p); p.Region = DisplayRegion.InPath; p = p.Parent; } }