private JArray Path2JSON(AStar AS) { JArray ja = new JArray(); Node oldnode = null; foreach (Node n in AS.PathByNodes) { JObject jo = new JObject(); double dist = 0; if (oldnode != null) dist = SystemData.Distance(n.System, oldnode.System); oldnode = n; jo["name"] = n.System.name; //jo.Add("name", n.Name); jo["x"] = n.X; jo["y"] = n.Y; jo["z"] = n.Z; jo["dist"] = Math.Round(dist * 100) / 100; ja.Add(jo); } // serialize JSON directly to a file using (StreamWriter file = File.CreateText(@"route.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, ja); } return ja; }
public static void Solve() { Stopwatch sw = new Stopwatch(); ReadData(); sw.Start(); ParseDataIntoGraph(); Console.WriteLine("Parsed data into graph in {0}", sw.Elapsed); sw.Stop(); AStar a = new AStar(g); a.ChoosenHeuristic = AStar.MaxAlongAxisHeuristic; //a.ChoosenHeuristic = AStar.ManhattanHeuristic; //a.ChoosenHeuristic = AStar.EuclidianHeuristic; int lowestPathCost = Int32.MaxValue; for (int start = 0; start < squareSize; start++) { Stopwatch swx = new Stopwatch(); swx.Start(); for (int end = 0; end < squareSize; end++) { Stopwatch sw1 = new Stopwatch(); sw1.Start(); if (a.SearchPath(nodes[0, start], nodes[squareSize_1, end])) { double pathCost = 0; bool isFirst = true; foreach (Arc arc in a.PathByArcs) { if (isFirst) { isFirst = false; pathCost += fileNodes[(int)arc.StartNode.X, (int)arc.StartNode.Y]; } pathCost += arc.Cost; //Console.WriteLine(arc.ToString()); } Console.WriteLine("{3} Path Cost from {0,2} to {1,2} is {2}", start, end, pathCost, sw1.Elapsed); if (pathCost < lowestPathCost) { lowestPathCost = (int)pathCost; } } else { Console.WriteLine("No results."); } } Console.WriteLine("\tElapsed time for startY={0,2} in {1}", start, swx.Elapsed); } Console.WriteLine("Lowest Path Cost: {0}", lowestPathCost); }
private void aStarMatches(Distance distanceCalc) { var map = new ArrayMap <bool>(MAP_WIDTH, MAP_HEIGHT); CellularAutomataGenerator.Generate(map); var graphTuple = initGraph(map, distanceCalc); var pather = new AStar(map, distanceCalc); var controlPather = new CA.AStar(graphTuple.Graph); controlPather.ChoosenHeuristic = distanceHeuristic(distanceCalc); for (int i = 0; i < ITERATIONS; i++) { Coord start = Coord.Get(SingletonRandom.DefaultRNG.Next(map.Width - 1), SingletonRandom.DefaultRNG.Next(map.Height - 1)); while (!map[start]) { start = Coord.Get(SingletonRandom.DefaultRNG.Next(map.Width - 1), SingletonRandom.DefaultRNG.Next(map.Height - 1)); } Coord end = Coord.Get(SingletonRandom.DefaultRNG.Next(map.Width - 1), SingletonRandom.DefaultRNG.Next(map.Height - 1)); while (end == start || !map[end]) { end = Coord.Get(SingletonRandom.DefaultRNG.Next(map.Width - 1), SingletonRandom.DefaultRNG.Next(map.Height - 1)); } var path1 = pather.ShortestPath(start, end); controlPather.SearchPath(graphTuple.Nodes[start.X, start.Y], graphTuple.Nodes[end.X, end.Y]); var path2 = controlPather.PathByNodes; if (path2.Length != path1.LengthWithStart) { Console.WriteLine($"Error: Control got {path2.Length}, but custom AStar got {path1.LengthWithStart}"); Console.WriteLine("Control: "); Utility.PrintHightlightedPoints(map, Utility.ToCoords(path2)); Console.WriteLine("AStar :"); Utility.PrintHightlightedPoints(map, path1.StepsWithStart); } bool lengthGood = (path1.LengthWithStart <= path2.Length); Assert.AreEqual(true, lengthGood); Assert.AreEqual(path1.Start, start); Assert.AreEqual(path1.End, end); checkWalkable(path1, map); checkAdjacency(path1, distanceCalc); } }
// 0 1 2 3 4 // 0 __ __ __ N6 __ // 1 N3 __ N5 __ __ // 2 __ N2 __ N4 __ // 3 __ __ N1 __ __ // 4 __ __ __ __ __ // // Begin:N1 // Goal:N6 // Links of Nodes: N3<-N2<-N1->N4->N5->N6 // Result way:N1->N4->N5->N6 public static void Main() { try { var G = new Graph(); Node N1 = G.AddNode(2,3,0); Node N2 = G.AddNode(1,2,0); Node N3 = G.AddNode(0,1,0); Node N4 = G.AddNode(3,2,0); Node N5 = G.AddNode(2, 1, 0); Node N6 = G.AddNode(3, 0, 0); G.AddArc(N1,N2,1); G.AddArc(N2,N3,1); G.AddArc(N1,N4,1); G.AddArc(N4,N5,1); G.AddArc(N5, N6, 1); Console.WriteLine( ListNodesAndArcs(G) ); Console.WriteLine("Start:"+N1.ToString()); Console.WriteLine("Goal:" + N6.ToString()); AStar AS = new AStar(G); if (AS.SearchPath(N1, N6)) { foreach (Arc A in AS.PathByArcs) Console.WriteLine(A.ToString()); } else { Console.WriteLine("No result !"); } } catch(Exception e) { Console.Write( "Error :\n\n"+e.ToString() ); } Console.ReadLine(); }
public static void Solve() { Stopwatch sw = new Stopwatch(); sw.Start(); ReadData(); ParseDataIntoGraph(); Console.WriteLine("Parsed data into graph in {0}", sw.Elapsed); AStar a = new AStar(g); a.ChoosenHeuristic = AStar.MaxAlongAxisHeuristic; //a.ChoosenHeuristic = AStar.ManhattanHeuristic; //a.ChoosenHeuristic = AStar.EuclidianHeuristic; if (a.SearchPath(nodes[0, 0], nodes[squareSize_1, squareSize_1])) { double pathCost = 0; bool isFirst = true; foreach (Arc arc in a.PathByArcs) { if (isFirst) { isFirst = false; pathCost += fileNodes[(int)arc.StartNode.X, (int)arc.StartNode.Y]; } pathCost += arc.Cost; } Console.WriteLine("Lowest Path Cost: {0}", pathCost); } else { Console.WriteLine("No results."); } //Console.WriteLine(ListNodesAndArcs(g)); }
private void Route(string s1, string s2, float maxrange, int mode) { Stopwatch sw = new Stopwatch(); if (lastJumprange != maxrange) { G = new Graph(); PrepareNodes(G, out nodes, maxrange, mode); //Console.WriteLine("Prepare nodes time: {0}", sw.Elapsed); lastJumprange = maxrange; } AStar AS = new AStar(G); Node start, stop; start = nodes.FirstOrDefault(x => x.System.SearchName == s1.ToLower()); stop = nodes.FirstOrDefault(x => x.System.SearchName == s2.ToLower()); bool res; if (start == null) { AppendText("Start system: " + s1 + " unknown"); return; } if (stop == null) { AppendText("Destination system: " + s2 + " unknown"); return; } sw = new Stopwatch(); sw.Start(); res = AS.SearchPath(start, stop); sw.Stop(); AppendText("Searching route from " + s1 + " to " + s2 + Environment.NewLine); AppendText("Find route Time: " + sw.Elapsed.TotalSeconds.ToString("0.000s") + Environment.NewLine); AppendText("Total distance: " + SystemData.Distance(s1, s2).ToString("0.00") + Environment.NewLine); AppendText("Max jumprange:" + maxrange + Environment.NewLine); double totdist = 0; int jumps = 0; if (res) { foreach (Arc A in AS.PathByArcs) { double dist = SystemData.Distance(A.StartNode.System.name, A.EndNode.System.name); AppendText(A.EndNode.System.name + " \tDist: " + dist.ToString("0.00") + " ly" + Environment.NewLine); totdist += dist; jumps++; Console.WriteLine(A.ToString()); } // JArray ja = Path2JSON(AS); } else Console.WriteLine("No result !"); AppendText("Total distance: " + totdist.ToString("0.00") + Environment.NewLine); AppendText("Jumps: " + jumps + Environment.NewLine); }
/// <summary> /// Set the A* search path /// </summary> /// <param name="StartGridRef">Origin</param> /// <param name="EndGridRef">Destination</param> /// <returns>true if a path exists</returns> public bool SearchAStarPath(Vector2 StartGridRef, Vector2 EndGridRef) { if (StartGridRef == LastOrigin && EndGridRef == LastDestination) return true; AS = new AStar(MapGraph); return AS.SearchPath(MapNodes[(int)StartGridRef.X + (int)StartGridRef.Y * level.Width], MapNodes[(int)EndGridRef.X + (int)EndGridRef.Y * level.Width]); }
private void Route(string s1, string s2, float maxrange, int mode) { EDDiscovery2.DB.ISystem ds1 = SystemData.GetSystem(s1); EDDiscovery2.DB.ISystem ds2 = SystemData.GetSystem(s2); if (ds1 == null) // warn here, quicker to complain than waiting for nodes to populate. { AppendText("Start system: " + s1 + " unknown"); return; } if (ds2 == null) { AppendText("Destination system: " + s2 + " unknown"); return; } double earea = 10.0; // add a little to the box for first/end points allowing out of box systems Point3D minpos = new EMK.LightGeometry.Point3D( Math.Min(ds1.x, ds2.x) - earea, Math.Min(ds1.y, ds2.y) - earea, Math.Min(ds1.z, ds2.z) - earea ); Point3D maxpos = new EMK.LightGeometry.Point3D( Math.Max(ds1.x, ds2.x) + earea, Math.Max(ds1.y, ds2.y)+ earea, Math.Max(ds1.z, ds2.z) + earea ); AppendText("Bounding Box " + minpos.X + "," + minpos.Y + "," + minpos.Z + " to " + maxpos.X + "," + maxpos.Y + "," + maxpos.Z + Environment.NewLine); Stopwatch sw = new Stopwatch(); G = new Graph(); // need to compute each time as systems in range changes each time PrepareNodes(G, maxrange, mode,minpos,maxpos); AStar AS = new AStar(G); Node start, stop; start = G.GetNodes.FirstOrDefault(x => x.System.SearchName == s1.ToLower()); stop = G.GetNodes.FirstOrDefault(x => x.System.SearchName == s2.ToLower()); bool res; sw = new Stopwatch(); sw.Start(); res = AS.SearchPath(start, stop); sw.Stop(); AppendText("Searching route from " + ds1.name + " to " + ds2.name + Environment.NewLine); AppendText("Find route Time: " + sw.Elapsed.TotalSeconds.ToString("0.000s") + Environment.NewLine); AppendText("Total distance: " + SystemData.Distance(s1, s2).ToString("0.00") + Environment.NewLine); AppendText("Max jumprange:" + maxrange + Environment.NewLine); if (res) { AppendText(Environment.NewLine + "Depart " + ds1.name + Environment.NewLine); double totdist = 0; int jumps = 0; foreach (Arc A in AS.PathByArcs) { double dist = SystemData.Distance(A.StartNode.System.name, A.EndNode.System.name); AppendText(string.Format("{0,-30}Dist: {1:0.00} ly" + Environment.NewLine, A.EndNode.System.name, dist)); totdist += dist; jumps++; Console.WriteLine(A.ToString()); } AppendText(Environment.NewLine + "Total distance: " + totdist.ToString("0.00") + Environment.NewLine); AppendText("Jumps: " + jumps + Environment.NewLine); // JArray ja = Path2JSON(AS); } else AppendText(Environment.NewLine + "NO Solution found - jump distance is too small or not enough star data between systems" + Environment.NewLine); }