Ejemplo n.º 1
0
        public void DijkstraPathFinder_FindShortestPath_Success()
        {
            // Arrange
            var graph = new WeightedGraph <char>();

            graph.AddEdge('A', 'B', 3);
            graph.AddEdge('A', 'C', 2);
            graph.AddEdge('A', 'D', 1);
            graph.AddEdge('D', 'C', 4);
            graph.AddEdge('D', 'G', 5);
            graph.AddEdge('C', 'G', 2);
            graph.AddEdge('B', 'E', 3);
            graph.AddEdge('E', 'F', 1);
            graph.AddEdge('E', 'H', 4);
            graph.AddEdge('F', 'G', 1);
            graph.AddEdge('F', 'H', 2);
            graph.AddEdge('G', 'H', 2);

            var pathFinder = new DijkstraPathFinder <char>();

            var result = pathFinder.FindShortestPath(graph, 'A', 'H');

            Assert.AreEqual(6, result.TotalCost);
            Assert.AreEqual(4, result.Path.Count());
            Assert.AreEqual('A', result.Path.ElementAt(0));
            Assert.AreEqual('C', result.Path.ElementAt(1));
            Assert.AreEqual('G', result.Path.ElementAt(2));
            Assert.AreEqual('H', result.Path.ElementAt(3));
        }
Ejemplo n.º 2
0
        public void TestOn3x3Map()
        {
            byte[,] map = new byte[3, 3] {
                { 1, 2, 3, },
                { 3, 4, 2, },
                { 5, 6, 5, },
            };

            var start  = new Location(0, 0);
            var finish = new Location(2, 2);

            var pathFinder = new DijkstraPathFinder();

            var path = pathFinder.Find(map, start, finish).ToList();

            var result = new List <Location>()
            {
                new Location(2, 1),
                new Location(2, 0),
                new Location(1, 0),
                new Location(0, 0),
            };

            Assert.Equal(result, path);
        }
Ejemplo n.º 3
0
        public void TestOn5x5MapWithAlmostWall()
        {
            byte[,] map = new byte[5, 5] {
                { 1, 2, 0, 6, 7 },
                { 3, 4, 3, 4, 6 },
                { 5, 6, 0, 6, 2 },
                { 7, 8, 0, 2, 6 },
                { 7, 8, 0, 2, 6 },
            };

            var start  = new Location(0, 0);
            var finish = new Location(4, 4);

            var pathFinder = new DijkstraPathFinder();

            var path = pathFinder.Find(map, start, finish).ToList();

            var result = new List <Location>()
            {
                new Location(3, 4),
                new Location(3, 3),
                new Location(2, 3),
                new Location(1, 3),
                new Location(1, 2),
                new Location(1, 1),
                new Location(1, 0),
                new Location(0, 0),
            };

            Assert.Equal(result, path);
        }
        private void FindAllRoutesCommandExecuted(MapView mapView)
        {
            DCGraph.ResetGraph();
            //Remove old route graphics
            RemoveRouteGraphics(mapView);
            var dijkstraApproxBucket = new DijkstraApproximateBucketPathFinder(DCGraph);

            var startVertex       = dijkstraApproxBucket.FindClosestVertex(StartLocation.ToCoordinates());
            var endVertex         = dijkstraApproxBucket.FindClosestVertex(EndLocation.ToCoordinates());
            var dijkstaKArrayHeap = new DijkstraMinHeapPathFinder(DCGraph);
            var dikstraList       = new DijkstraPathFinder(DCGraph);

            var astarList         = new AStarPathFinder(DCGraph);
            var astarApproxBucket = new AStarApproximateBucketPathFinder(DCGraph);
            var astarKarrayHeap   = new AStarMinHeapPathFinder(DCGraph);


            AStarKArrayHeapRunningTime = GetRunningTime(astarKarrayHeap, startVertex, endVertex, mapView);
            DCGraph.ResetGraph();
            AStarApproximateBucketRunningTime = GetRunningTime(astarApproxBucket, startVertex, endVertex, mapView);
            DCGraph.ResetGraph();
            AStarListRunningTime = GetRunningTime(astarList, startVertex, endVertex, mapView);
            DCGraph.ResetGraph();

            DijkstraApproximateBucketRunningTime = GetRunningTime(dijkstraApproxBucket, startVertex, endVertex, mapView);
            DCGraph.ResetGraph();
            DijkstraListRunningTime = GetRunningTime(dikstraList, startVertex, endVertex, mapView);
            DCGraph.ResetGraph();
            DijkstraKArrayHeapRunningTime = GetRunningTime(dijkstaKArrayHeap, startVertex, endVertex, mapView);
            DCGraph.ResetGraph();
        }
Ejemplo n.º 5
0
        private static string GetActualResult(string inputLines)
        {
            var tempFileName = Path.GetTempFileName();

            using (var writer = new StreamWriter(tempFileName))
                writer.Write(inputLines);

            var actualResult = GetActualResult();

            try
            {
                File.Delete(tempFileName);
            }
            catch (IOException) { }

            return(actualResult);

            string GetActualResult()
            {
                using (var reader = new StreamReader(tempFileName))
                {
                    var(graph, source, target) = DataParser.GetInputData(reader.ReadLine);
                    var resultPath = DijkstraPathFinder.GetShortestPath(graph, source, target);
                    return(DataParser.ResultGenerate(resultPath, graph));
                }
            }
        }
        public Amount Convert(Amount amount, Currency from, Currency to)
        {
            var pathFinder = new DijkstraPathFinder(this.exchangeRates);

            return(pathFinder
                   .FindSequence(from, to)
                   .Convert(amount));
        }
Ejemplo n.º 7
0
        private void AssertShortestPath(string exchangeRatesDescription, string expectedRateSequence)
        {
            var table = ExchangeRateTableCreator.From(exchangeRatesDescription);

            var pathFinder = new DijkstraPathFinder(table);
            var sequence   = pathFinder.FindSequence(new Currency("EUR"), new Currency("JPY"));

            sequence.ToString().Should().Be(expectedRateSequence);
        }
Ejemplo n.º 8
0
        public Location[] FindShortestWay(Location start, Location finish)
        {
            // TODO: In real project we could use DI.
            var pathFinder = new DijkstraPathFinder();

            // var pathFinder = new AStarPathFinder();

            return(pathFinder.Find(Map, start, finish));
        }
Ejemplo n.º 9
0
        public override void LoadContent()
        {
            base.LoadContent();
            _eventBus = BlackBoard.GetEntry <JEventBus>("EventBus") ?? JEventBus.GetDefault();
            _eventBus.Register(this);

            var _grid = BlackBoard.GetEntry <Grid>("Grid");

            _dijkstraPathFinder = new DijkstraPathFinder(ByteArrayHelper.CreateBase(_grid.Width));
        }
Ejemplo n.º 10
0
        public void TryFindShortestPath_Large200x400MapTrying24KnownPathsFrom1Source_ReturnsExpectedPaths()
        {
            KnownSeriesRandom randomX = new KnownSeriesRandom(150, 137, 51, 31, 40, 135, 116, 148, 83, 94, 153, 30, 63, 80, 31, 107, 64, 95, 6, 145, 105, 66, 96, 37);
            KnownSeriesRandom randomY = new KnownSeriesRandom(255, 359, 175, 279, 169, 293, 335, 208, 235, 327, 67, 234, 56, 272, 241, 215, 230, 377, 194, 301, 161, 348, 89, 171);

            int[] pathLengths = { 398, 489, 219, 423, 206, 421, 444, 351, 311, 414, 213, 323, 118, 345, 369, 315, 301, 465, 389, 439, 259, 453, 178, 201 };
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(Algorithms.TestSetup.TestHelpers.Map200x400);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);

            for (int i = 0; i < 24; i++)
            {
                int   x1          = 7;
                int   y1          = 1;
                int   x2          = randomX.Next(199);
                int   y2          = randomY.Next(399);
                ICell source      = map.GetCell(x1, y1);
                ICell destination = map.GetCell(x2, y2);

                Stopwatch timer = Stopwatch.StartNew();

                Path shortestPath = dijkstraPathFinder.TryFindShortestPath(source, destination);

                Console.WriteLine(
                    $"Path from `{x1}:{y1}` to `{x2}:{y2}` was {shortestPath?.Steps?.Count()} long and took Elapsed Milliseconds: {timer.ElapsedMilliseconds}");
                Assert.AreEqual(pathLengths[i % 24], shortestPath?.Steps?.Count());
            }

            // Sample Output (Release Mode)
            //Path from `7:1` to `150:255` was 398 long and took Elapsed Milliseconds: 36
            //Path from `7:1` to `137:359` was 489 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `51:175` was 219 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `31:279` was 423 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `40:169` was 206 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `135:293` was 421 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `116:335` was 444 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `148:208` was 351 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `83:235` was 311 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `94:327` was 414 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `153:67` was 213 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `30:234` was 323 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `63:56` was 118 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `80:272` was 345 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `31:241` was 369 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `107:215` was 315 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `64:230` was 301 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `95:377` was 465 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `6:194` was 389 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `145:301` was 439 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `105:161` was 259 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `66:348` was 453 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `96:89` was 178 long and took Elapsed Milliseconds: 0
            //Path from `7:1` to `37:171` was 201 long and took Elapsed Milliseconds: 0
        }
Ejemplo n.º 11
0
        public void TryFindShortestPath_Large200x400MapFromX5Y1ToX29Y187_ReturnsExpectedPath()
        {
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(Algorithms.TestSetup.TestHelpers.Map200x400);
            IMap  map         = Map.Create(mapCreationStrategy);
            ICell source      = map.GetCell(5, 1);
            ICell destination = map.GetCell(29, 187);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);

            Path shortestPath = dijkstraPathFinder.TryFindShortestPath(source, destination);

            Assert.AreEqual(705, shortestPath.Length);
        }
Ejemplo n.º 12
0
        static void Main()
        {
            IGraph      g;
            IPathFinder pathFinder = new DijkstraPathFinder();

            Console.WriteLine("=== Graph initialized with Adj. Matrix ===");
            g = TestAM();
            //ShowConns(g);
            ShowPath(pathFinder.FindPath(g, 0, 7));

            Console.WriteLine("=== Graph initialized with Adj. List ===");
            g = TestAL();
            //ShowConns(g);
            ShowPath(pathFinder.FindPath(g, 0, 6));
        }
Ejemplo n.º 13
0
        public void ShortestPath_DestinationUnreachable_ThrowsPathNotFoundException()
        {
            string mapRepresentation = @"########
                                      #....#.#
                                      #.#..#.#
                                      #.#..#.#
                                      #....#.#
                                      ########";
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(mapRepresentation);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);
            ICell source      = map.GetCell(1, 1);
            ICell destination = map.GetCell(6, 1);

            dijkstraPathFinder.ShortestPath(source, destination);
        }
Ejemplo n.º 14
0
        public void ShortestPath_DestinationIsNull_ThrowsArgumentNullException()
        {
            string mapRepresentation = @"########
                                      #....#.#
                                      #.#..#.#
                                      #.#..#.#
                                      #......#
                                      ########";
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(mapRepresentation);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);
            ICell source      = map.GetCell(1, 4);
            ICell destination = null;

            Path shortestPath = dijkstraPathFinder.ShortestPath(source, destination);
        }
Ejemplo n.º 15
0
        public void SinglePath()
        {
            var reader = new StringReader(
                @"graph {
A -- B -- C
}");
            var dotReader = new DotReader(reader);
            var g         = dotReader.Read();

            g.Edges["A", "B"].UserData[DistanceProperty] = 1;
            g.Edges["B", "C"].UserData[DistanceProperty] = 2;

            var finder = new DijkstraPathFinder(DistanceProperty);
            var path   = finder.FindPath(g.Nodes["A"], g.Nodes["C"]).ToArray();

            Assert.Equal(new[] { g.Nodes["A"], g.Nodes["B"], g.Nodes["C"] }, path);
        }
Ejemplo n.º 16
0
        public void UnreachableNode()
        {
            var reader = new StringReader(
                @"graph {
A -- B -- C -- D
E
}");
            var dotReader = new DotReader(reader);
            var g         = dotReader.Read();

            g.Edges["A", "B"].UserData[DistanceProperty] = 1;
            g.Edges["B", "C"].UserData[DistanceProperty] = 2;
            g.Edges["C", "D"].UserData[DistanceProperty] = 3;

            var finder = new DijkstraPathFinder(DistanceProperty);

            Assert.Null(finder.FindPath(g.Nodes["A"], g.Nodes["E"]));
        }
Ejemplo n.º 17
0
        public void TryFindShortestPath_DestinationUnreachable_ReturnsNull()
        {
            string mapRepresentation = @"########
                                      #....#.#
                                      #.#..#.#
                                      #.#..#.#
                                      #....#.#
                                      ########";
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(mapRepresentation);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);
            ICell source      = map.GetCell(1, 1);
            ICell destination = map.GetCell(6, 1);

            Path shortestPath = dijkstraPathFinder.TryFindShortestPath(source, destination);

            Assert.AreEqual(null, shortestPath);
        }
        public void TestPathfinderDynamicChangeCostOfMove()
        {
            DijkstraPathFinder pathFinder = new DijkstraPathFinder(new byte[, ]
            {
                { 1, 1, 1, 1 },
                { 1, 1, 1, 1 },
                { 1, 1, 1, 1 },
                { 1, 1, 1, 1 }
            });

            pathFinder.ChangeCostOfMove(1, 1, 0);
            pathFinder.ChangeCostOfMove(2, 2, 0);
            var movementInfo = pathFinder.GetHexesInMovementRange(new Point(0, 0), 8);
            var result       = pathFinder.Find(new Point(0, 0), new Point(3, 3), movementInfo);

            Assert.IsNotNull(result);
            Assert.IsNotEmpty(result);
            Assert.AreEqual(5, result.Count);
        }
Ejemplo n.º 19
0
        public void TestOn5x5MapWithWall()
        {
            byte[,] map = new byte[5, 5] {
                { 1, 2, 0, 6, 7 },
                { 3, 4, 0, 4, 6 },
                { 5, 6, 0, 6, 2 },
                { 7, 8, 0, 2, 6 },
                { 7, 8, 0, 2, 6 },
            };

            var start  = new Location(0, 0);
            var finish = new Location(4, 4);

            var pathFinder = new DijkstraPathFinder();

            var path = pathFinder.Find(map, start, finish)?.ToList();

            Assert.Null(path);
        }
Ejemplo n.º 20
0
        public void TryFindShortestPath_Large200x400MapTrying12KnownPaths_ReturnsExpectedPaths()
        {
            KnownSeriesRandom randomX = new KnownSeriesRandom(150, 137, 51, 31, 40, 135, 116, 148, 83, 94, 153, 30, 63, 80, 31, 107, 64, 95, 6, 145, 105, 66, 96, 37);
            KnownSeriesRandom randomY = new KnownSeriesRandom(255, 359, 175, 279, 169, 293, 335, 208, 235, 327, 67, 234, 56, 272, 241, 215, 230, 377, 194, 301, 161, 348, 89, 171);

            int[] pathLengths = { 822, 229, 598, 730, 344, 507, 398, 655, 737, 799, 683, 350 };
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(Algorithms.TestSetup.TestHelpers.Map200x400);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);

            for (int i = 0; i < 12; i++)
            {
                int   x1          = randomX.Next(199);
                int   y1          = randomY.Next(399);
                int   x2          = randomX.Next(199);
                int   y2          = randomY.Next(399);
                ICell source      = map.GetCell(x1, y1);
                ICell destination = map.GetCell(x2, y2);

                Stopwatch timer = Stopwatch.StartNew();

                Path shortestPath = dijkstraPathFinder.TryFindShortestPath(source, destination);

                Console.WriteLine(
                    $"Path from `{x1}:{y1}` to `{x2}:{y2}` was {shortestPath?.Steps?.Count()} long and took Elapsed Milliseconds: {timer.ElapsedMilliseconds}");
                Assert.AreEqual(pathLengths[i % 12], shortestPath?.Steps?.Count());
            }

            // Sample Output (Release Mode)
            //Path from `150:255` to `137:359` was 822 long and took Elapsed Milliseconds: 64 ( A* 9 )
            //Path from `51:175` to `31:279` was 229 long and took Elapsed Milliseconds:   47 ( A* 3 )
            //Path from `40:169` to `135:293` was 598 long and took Elapsed Milliseconds:  59 ( A* 1 )
            //Path from `116:335` to `148:208` was 730 long and took Elapsed Milliseconds: 82 ( A* 2 )
            //Path from `83:235` to `94:327` was 344 long and took Elapsed Milliseconds:   52 ( A* 1 )
            //Path from `153:67` to `30:234` was 507 long and took Elapsed Milliseconds:   73 ( A* 4 )
            //Path from `63:56` to `80:272` was 398 long and took Elapsed Milliseconds:    72 ( A* 1 )
            //Path from `31:241` to `107:215` was 655 long and took Elapsed Milliseconds:  76 ( A* 2 )
            //Path from `64:230` to `95:377` was 737 long and took Elapsed Milliseconds:   67 ( A* 4 )
            //Path from `6:194` to `145:301` was 799 long and took Elapsed Milliseconds:   69 ( A* 3 )
            //Path from `105:161` to `66:348` was 683 long and took Elapsed Milliseconds:  61 ( A* 4 )
            //Path from `96:89` to `37:171` was 350 long and took Elapsed Milliseconds:    57 ( A* 2 )
        }
Ejemplo n.º 21
0
        public void TryFindShortestPath_Large200x400MapTrying12KnownPathsWithDiagonals_ReturnsExpectedPaths()
        {
            KnownSeriesRandom randomX = new KnownSeriesRandom(150, 137, 51, 31, 40, 135, 116, 148, 83, 94, 153, 30, 63, 80, 31, 107, 64, 95, 6, 145, 105, 66, 96, 37);
            KnownSeriesRandom randomY = new KnownSeriesRandom(255, 359, 175, 279, 169, 293, 335, 208, 235, 327, 67, 234, 56, 272, 241, 215, 230, 377, 194, 301, 161, 348, 89, 171);

            int[] pathLengths = { 749, 203, 557, 667, 328, 463, 371, 602, 692, 733, 626, 326 };
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(Algorithms.TestSetup.TestHelpers.Map200x400);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map, 1);

            for (int i = 0; i < 12; i++)
            {
                int   x1          = randomX.Next(199);
                int   y1          = randomY.Next(399);
                int   x2          = randomX.Next(199);
                int   y2          = randomY.Next(399);
                ICell source      = map.GetCell(x1, y1);
                ICell destination = map.GetCell(x2, y2);

                Stopwatch timer = Stopwatch.StartNew();

                Path shortestPath = dijkstraPathFinder.TryFindShortestPath(source, destination);

                Console.WriteLine($"Path from `{x1}:{y1}` to `{x2}:{y2}` was {shortestPath?.Steps?.Count()} long and took Elapsed Milliseconds: {timer.ElapsedMilliseconds}");
                Assert.AreEqual(pathLengths[i % 12], shortestPath?.Steps?.Count());
            }

            // Sample Output (Release Mode)
            //Path from `150:255` to `137:359` was 749 long and took Elapsed Milliseconds: 32
            //Path from `51:175` to `31:279` was 203 long and took Elapsed Milliseconds: 24
            //Path from `40:169` to `135:293` was 557 long and took Elapsed Milliseconds: 32
            //Path from `116:335` to `148:208` was 667 long and took Elapsed Milliseconds: 30
            //Path from `83:235` to `94:327` was 328 long and took Elapsed Milliseconds: 28
            //Path from `153:67` to `30:234` was 463 long and took Elapsed Milliseconds: 24
            //Path from `63:56` to `80:272` was 371 long and took Elapsed Milliseconds: 25
            //Path from `31:241` to `107:215` was 602 long and took Elapsed Milliseconds: 26
            //Path from `64:230` to `95:377` was 692 long and took Elapsed Milliseconds: 26
            //Path from `6:194` to `145:301` was 733 long and took Elapsed Milliseconds: 23
            //Path from `105:161` to `66:348` was 626 long and took Elapsed Milliseconds: 23
            //Path from `96:89` to `37:171` was 326 long and took Elapsed Milliseconds: 25
        }
Ejemplo n.º 22
0
        public void ShortestPath_DestinationReachableFromSource_ExpectedPath()
        {
            string mapRepresentation = @"########
                                      #....#.#
                                      #.#..#.#
                                      #.#..#.#
                                      #......#
                                      ########";
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(mapRepresentation);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map);
            ICell source      = map.GetCell(1, 4);
            ICell destination = map.GetCell(5, 4);

            Path shortestPath = dijkstraPathFinder.ShortestPath(source, destination);

            Assert.AreEqual(5, shortestPath.Length);
            Assert.AreEqual(source, shortestPath.Start);
            Assert.AreEqual(destination, shortestPath.End);
            Assert.AreEqual(map.GetCell(2, 4), shortestPath.StepForward());
        }
        public void TestPathfinder()
        {
            DijkstraPathFinder pathFinder = new DijkstraPathFinder(new byte[, ]
            {
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1 }
            });
            var result = pathFinder.GetHexesInMovementRange(new Point(4, 4), 3);

            Assert.IsNotNull(result);
            Assert.IsNotEmpty(result.tileReturnPath);
            // Assert.AreEqual(4, result.Count);

            var pathfindingResult = pathFinder.Find(new Point(4, 4), new Point(6, 2), result);
        }
Ejemplo n.º 24
0
        private IclusterIGCWrapper FindNearestUnexploredCluster()
        {
            IclusterIGCWrapper nearestCluster = null;
            int nearestClusterDistance        = int.MaxValue;

            foreach (var unexploredClusterObjectID in GameInfo.UnexploredClustersByObjectID.Keys)
            {
                var fromCluster = _client.GetShip().GetCluster();
                var toCluster   = _client.GetCore().GetCluster((short)unexploredClusterObjectID);

                DijkstraPathFinder pathFinder = new DijkstraPathFinder(_client.GetCore(), fromCluster, toCluster);

                int distance = pathFinder.GetDistance(fromCluster, toCluster);

                if (distance < nearestClusterDistance)
                {
                    nearestCluster = toCluster;
                }
            }

            return(nearestCluster);
        }
Ejemplo n.º 25
0
        public void TryFindShortestPath_DestinationReachableFromSourceAndDiagonalMovementIsAllowed_ExpectedPath()
        {
            string mapRepresentation = @"########
                                      #....#.#
                                      #.#..#.#
                                      #.#..#.#
                                      #......#
                                      ########";
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(mapRepresentation);
            IMap map = Map.Create(mapCreationStrategy);
            DijkstraPathFinder dijkstraPathFinder = new DijkstraPathFinder(map, 1.41);
            ICell source      = map.GetCell(1, 1);
            ICell destination = map.GetCell(6, 4);

            Path shortestPath = dijkstraPathFinder.TryFindShortestPath(source, destination);

            Assert.AreEqual(6, shortestPath.Length);
            Assert.AreEqual(source, shortestPath.Start);
            Assert.AreEqual(destination, shortestPath.End);
            Assert.AreEqual(map.GetCell(2, 1), shortestPath.StepForward());
            Assert.AreEqual(map.GetCell(3, 2), shortestPath.StepForward());
        }
Ejemplo n.º 26
0
 public void Init()
 {
     pathFinder = new DijkstraPathFinder();
 }
Ejemplo n.º 27
0
 public void Constructor_NullMapWithDiagonalCostSet_ThrowsArgumentNullException()
 {
     var dijkstraPathFinder = new DijkstraPathFinder(null, 1.41);
 }
Ejemplo n.º 28
0
        private IclusterIGCWrapper GetStationBuildCluster(StationType stationType)
        {
            var stations         = ClientConnection.GetSide().GetStations();
            var homeStation      = stations.Where(p => p.GetCluster().GetHomeSector() == true).FirstOrDefault();
            var homeCluster      = homeStation.GetCluster();
            var homeRock         = homeCluster.GetAsteroids().Where(p => p.GetName().StartsWith("He") == false && p.GetName().StartsWith("a") == false && String.IsNullOrWhiteSpace(p.GetName()) == false).FirstOrDefault();
            var enemyHomeCluster = ClientConnection.GetCore().GetClusters().Where(p => p.GetHomeSector() == true && p.GetObjectID() != homeCluster.GetObjectID()).FirstOrDefault();

            // Always build a home tele first if we don't have one in our home cluster.
            if (stationType == StationType.Teleport && homeCluster.GetStations().Exists(p => p.GetName().Contains("Teleport") == true) == false &&
                _constuctorsInFlightToClusterObjectIDByShipObjectID.Values.Count(r => r.Cluster.GetObjectID() == homeCluster.GetObjectID()) == 0)
            {
                Log($"There is no home teleporter yet, let's put this tele con at home: {homeCluster.GetName()}");
                return(homeCluster);
            }

            // Try to find empty clusters where we have secured all sides.
            if (stationType == StationType.Refinery)
            {
                // For hihigher, this is the middle cluster.
                Log("Checking for an empty cluster that is bordered by our own stations.");
                var goodRefCluster = ClientConnection.GetCore().GetClusters()
                                     .Where(p => p.GetStations().Count == 0 && // Make sure there are no stations in it already.
                                            _constuctorsInFlightToClusterObjectIDByShipObjectID.Values.Count(r => r.Cluster.GetObjectID() == p.GetObjectID()) == 0 && // Are any other cons heading to this cluster?
                                            GameInfo.GetUnexploredClusters(p.GetMission()).ContainsKey(p.GetObjectID()) == false && // Is this cluster fully explored?
                                            p.GetWarps().All(r =>
                                                             r.GetDestination().GetCluster().GetStations().Count > 0 && // Neighboring clusters have at least one station
                                                             r.GetDestination().GetCluster().GetStations().All(s => s.GetSide().GetObjectID() == ClientConnection.GetSide().GetObjectID()))) // And all the stations belong to our side.
                                     .FirstOrDefault();

                if (goodRefCluster != null)
                {
                    Log($"Found a good cluster for a refinery: {goodRefCluster.GetName()}");
                    return(goodRefCluster);
                }
                else
                {
                    Log($"No good refinery cluster found. Looking for a good spot on available lines.");
                }
            }

            //var availableClusters = GameInfo.Clusters.Where(p => p.GetHomeSector() == true || ClientConnection.

            var routeFinder = new DijkstraPathFinder(GameInfo.Clusters, homeCluster.GetObjectID(), enemyHomeCluster.GetObjectID());
            var singleHopClusterDistances = homeCluster.GetWarps()
                                            .ToDictionary(
                p => p.GetDestination().GetCluster(),
                r => new DijkstraPathFinder(GameInfo.Clusters, r.GetDestination().GetCluster().GetObjectID(), enemyHomeCluster.GetObjectID())
                .GetDistance(r.GetDestination().GetCluster(), enemyHomeCluster));

            List <ClusterInfo> clustersNextToHome = GameInfo.Clusters.Where(p => p.GetWarps().Exists(r => r.GetDestinationCluster().GetObjectID() == homeCluster.GetObjectID()) == true).ToList();

            // Walk each path until a station is found.
            while (clustersNextToHome.Count > 0)
            {
                var currentClusterObjectID = clustersNextToHome[_random.Next(0, clustersNextToHome.Count)];
                clustersNextToHome.Remove(currentClusterObjectID);

                var pathFinder = new DijkstraPathFinder(GameInfo.Clusters, currentClusterObjectID.GetObjectID(), enemyHomeCluster.GetObjectID());

                var currentCluster = ClientConnection.GetCore().GetCluster(currentClusterObjectID.GetObjectID());

                Log($"Considering line for {currentCluster.GetName()}");

                for (var nextClusterObjectID = (short)pathFinder.NextClusterObjectID(currentCluster.GetObjectID(), enemyHomeCluster.GetObjectID());
                     currentCluster.GetObjectID() != enemyHomeCluster.GetObjectID();
                     currentCluster = ClientConnection.GetCore().GetCluster(nextClusterObjectID), nextClusterObjectID = (short)pathFinder.NextClusterObjectID(nextClusterObjectID, enemyHomeCluster.GetObjectID()).GetValueOrDefault(-1))
                {
                    var nextCluster = ClientConnection.GetCore().GetCluster(nextClusterObjectID);

                    Log($"Considering cluster: {currentCluster.GetName()}, nextCluster: {nextCluster.GetName()}");

                    // Don't select this cluster if another constructor is already on the way to it.
                    if (_constuctorsInFlightToClusterObjectIDByShipObjectID.Values.Count(r => r.Cluster.GetObjectID() == currentCluster.GetObjectID()) > 0)
                    //if (_constuctorsInFlightToClusterObjectIDByShipObjectID.ContainsValue(currentCluster.GetObjectID()) == true)
                    {
                        Log($"There is already a constructor heading to {currentCluster.GetName()}, skipping to next sector.");
                        continue;
                    }

                    // If the station is a friendly station, then we can put a ref or tech base next to it.
                    if (ClientConnection.GetCore().GetCluster(nextClusterObjectID).GetStations().Exists(p => p.GetSide().GetObjectID() == ClientConnection.GetSide().GetObjectID()) == true)
                    {
                        Log($"Friendly station found in nextCluster: {nextCluster.GetName()}");

                        // We don't want to put an output behind another friendly station. See if we can get closer!
                        if (stationType == StationType.Outpost)
                        {
                            Log("There is an outpost already in this line, so we don't want to put another one behind it.");
                            continue;
                        }

                        // If this matches to our home tech rock, then let's drop it here.
                        if (stationType == StationType.Teleport)
                        {
                            // If the sector already has a teleport, then see if we can get closer!
                            if (ClusterContainsStation(StationType.Teleport, currentCluster) == true)
                            {
                                Log("There is already a teleport here, seeing if we can get closer.");
                                continue;
                            }

                            // If the sector's tech rock matches the home rock, then put a tele in it.
                            if (currentCluster.GetStations().Count == 0 && GetClusterTechRock(currentCluster).GetName()[0] == homeRock.GetName()[0])
                            {
                                Log("There is a good tech rock here, let's a put a tele here too!");
                                return(currentCluster);
                            }
                        }

                        // We have a covering station in front of this one, so this is a good sector use for mining or tech bases, but we want refs to be as close to home as possible.
                        if (stationType == StationType.Refinery &&
                            ClusterContainsStation(StationType.Refinery, currentCluster) == false)
                        {
                            var homeSectorPath            = new DijkstraPathFinder(ClientConnection.GetCore(), currentCluster, homeCluster);
                            IclusterIGCWrapper refCluster = currentCluster;
                            for (nextCluster = currentCluster; nextCluster != homeCluster && nextCluster != null; nextCluster = homeSectorPath.NextCluster(nextCluster, homeCluster))
                            {
                                if (nextCluster.GetStations().Count(p => p.GetSide().GetObjectID() == ClientConnection.GetSide().GetObjectID()) > 0)
                                {
                                    Log($"Found a refinery cluster that is on a line protected by another station, with a friendly station backing it: {refCluster.GetName()}");
                                    return(refCluster);
                                }

                                refCluster = nextCluster;
                            }

                            //Log($"This is good spot for a refinery! Recommending: {currentCluster.GetName()}");
                            //return currentCluster;
                        }

                        if (stationType == StationType.Garrison &&
                            ClusterContainsStation(StationType.Garrison, currentCluster) == false)
                        {
                            Log($"This is good spot for a garrison! Recommending: {currentCluster.GetName()}");
                            return(currentCluster);
                        }

                        if (stationType == StationType.ShipYard &&
                            ClusterContainsStation(StationType.ShipYard, currentCluster) == false)
                        {
                            Log($"This is good spot for a ship yard! Recommending: {currentCluster.GetName()}");
                            return(currentCluster);
                        }

                        if (stationType == StationType.Supremacy && ClusterContainsStation(StationType.Supremacy, currentCluster) == false)
                        {
                            Log($"This is good spot for a supremacy! Recommending: {currentCluster.GetName()}");
                            return(currentCluster);
                        }

                        if (stationType == StationType.Expansion && ClusterContainsStation(StationType.Expansion, currentCluster) == false)
                        {
                            Log($"This is good spot for an expansion! Recommending: {currentCluster.GetName()}");
                            return(currentCluster);
                        }

                        if (stationType == StationType.Tactical && ClusterContainsStation(StationType.Tactical, currentCluster) == false)
                        {
                            Log($"This is good spot for a tactical! Recommending: {currentCluster.GetName()}");
                            return(currentCluster);
                        }
                    }

                    // If the station is an enemy station, then we want to put a tele or outpost next to it.
                    if (ClientConnection.GetCore().GetCluster(nextClusterObjectID).GetStations().Exists(p => p.GetSide().GetObjectID() != ClientConnection.GetSide().GetObjectID()) == true ||
                        (nextCluster.GetAsteroids().Count == 0 && ClientConnection.GetCore().GetCluster(nextClusterObjectID).GetHomeSector() == true))    // If we haven't actually eyed the enemy home, then we know their garrison is in there.
                    {
                        Log($"Next sector: {nextCluster.GetName()} has an enemy station in it.");

                        // Always put outposts next to enemy stations. That's our favorite!
                        if (stationType == StationType.Outpost && ClusterContainsStation(StationType.Outpost, currentCluster) == false)
                        {
                            Log($"Found a good cluster for this outpost: {currentCluster.GetName()}, next to an enemy sector.");
                            return(currentCluster);
                        }

                        // If the target sector doesn't already have an outpost in it, then put a tele one sector back if possible to allow an outpost to come forward.
                        if (stationType == StationType.Teleport && ClusterContainsStation(StationType.Outpost, currentCluster) == false)
                        {
                            var previousCluster = ClientConnection.GetCore().GetCluster((short)pathFinder.NextClusterObjectID(currentCluster.GetObjectID(), homeCluster.GetObjectID()));

                            if (previousCluster.GetStations().Count == 0)
                            {
                                Log($"There is an open cluster in {previousCluster.GetName()}, let's send the tele to there!");
                                return(previousCluster);
                            }
                        }
                    }
                }
            }

            if (stationType == StationType.Refinery)
            {
                Log($"No good cluster found for this refinery, waiting for a good option to appear.");
                return(null);
            }


            Log($"No targeted clusters were found, placing con in a random open cluster.");

            // No targeted clusters were found, let's go with any random empty cluster that we know about.
            var emptyClusters = ClientConnection.GetCore().GetClusters().Where(p => p.GetAsteroids().Count > 0 &&
                                                                               p.GetStations().Count == 0 &&
                                                                               _constuctorsInFlightToClusterObjectIDByShipObjectID.Values.Count(r => r.Cluster.GetObjectID() == p.GetObjectID()) == 0)
                                .ToArray();

            if (emptyClusters.Count() == 0)
            {
                return(null);
            }

            var targetCluster = emptyClusters[_random.Next(0, emptyClusters.Count())];

            Log($"Selecting random cluster: {targetCluster.GetName()} as target.");

            return(targetCluster);



            //int minHops = singleHopClusterDistances.Select(p => p.Value).OrderBy(p => p).First();
            //var bestClusterRoutesForOutposts = singleHopClusterDistances.Where(p => p.Value == minHops).ToDictionary(p => p.Key, r => r.Value);

            //foreach (var cluster in bestClusterRoutesForOutposts.Keys)
            //{
            //    Log($"Start: {cluster.GetName()}");

            //    routeFinder = new DijkstraPathFinder(GameInfo.Clusters, cluster.GetObjectID(), enemyHomeCluster.GetObjectID());

            //    for (var nextCluster = routeFinder.NextClusterObjectID(cluster.GetObjectID(), enemyHomeCluster.GetObjectID()); nextCluster != null; nextCluster = routeFinder.NextClusterObjectID(nextCluster.GetValueOrDefault(0), enemyHomeCluster.GetObjectID()))
            //    {
            //        Log($"\tNext: {ClientConnection.GetCore().GetCluster((short)nextCluster.GetValueOrDefault(0)).GetName()}");
            //    }
            //}
        }
Ejemplo n.º 29
0
 public void Constructor_NullMap_ThrowsArgumentNullException()
 {
     var dijkstraPathFinder = new DijkstraPathFinder(null);
 }
Ejemplo n.º 30
0
    private void Show(Pos start, Pos goal, int[][] cost)
    {
        var objs = GameObject.FindGameObjectsWithTag("Unit");

        foreach (var o in objs)
        {
            Destroy(o);
        }

        // ----- BFS -----

        var         gridGraph  = new GridGraph(16, 16, cost);
        IPathFinder pathFinder = new BfsPathFinder();
        var         path       = pathFinder.Find(gridGraph, start, goal);

        Show(gridGraph, new Vector2(0, 0), Color.white, path);

        var sumCost = 0;

        foreach (var p in path)
        {
            sumCost += cost[p.X][p.Y];
        }

        if (sumCost == 0)
        {
            Debug.LogError("BFS 没有找到路径");
        }
        else
        {
            Debug.LogError($"BFS 总成本: {sumCost}, 总步数: {path.Count}");
        }

        // ----- Dijkstra -----

        pathFinder = new DijkstraPathFinder();
        path       = pathFinder.Find(gridGraph, start, goal);

        Show(gridGraph, new Vector2(10, 0), Color.yellow, path);

        sumCost = 0;
        foreach (var p in path)
        {
            sumCost += cost[p.X][p.Y];
        }

        if (sumCost == 0)
        {
            Debug.LogError("Dijkstra 没有找到路径");
        }
        else
        {
            Debug.LogError($"Dijkstra 总成本: {sumCost}, 总步数: {path.Count}");
        }

        // ----- GreedyBestFirst -----

        pathFinder = new GreedyBestFirstPathFinder();
        path       = pathFinder.Find(gridGraph, start, goal);

        Show(gridGraph, new Vector2(0, 10), Color.grey, path);

        sumCost = 0;
        foreach (var p in path)
        {
            sumCost += cost[p.X][p.Y];
        }

        if (sumCost == 0)
        {
            Debug.LogError("GreedyBestFirst 没有找到路径");
        }
        else
        {
            Debug.LogError($"GreedyBestFirst 总成本: {sumCost}, 总步数: {path.Count}");
        }

        // ----- AStar -----

        pathFinder = new AStarPathFinder();
        path       = pathFinder.Find(gridGraph, start, goal);

        Show(gridGraph, new Vector2(10, 10), Color.magenta, path);

        sumCost = 0;
        foreach (var p in path)
        {
            sumCost += cost[p.X][p.Y];
        }

        if (sumCost == 0)
        {
            Debug.LogError("AStar 没有找到路径");
        }
        else
        {
            Debug.LogError($"AStar 总成本: {sumCost}, 总步数: {path.Count}");
        }
    }