Example #1
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 AStarPathFinder();

            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);
        }
Example #2
0
        public override Path InitiateTurn()
        {
            Path.PathAction action;

            if (Target.OccupiedBy == null)
            {
                action = Path.PathAction.Move;
            }
            else if (Target.OccupiedBy.GetComponent <Monster>() != null)
            {
                action = Path.PathAction.Attack;
                Console.WriteLine("Chasing::InitiateTurn() found out that Target tile is occupied by a hero -> this shouldn't happen.");
            }
            else
            {
                action = Path.PathAction.Use;
            }

            AStarPathFinder pf   = new AStarPathFinder(action);
            Path            path = pf.Find(Monster.Tile, Target);

            Monster.Tile.OccupiedBy = null;
            Monster.Tile            = null;

            return(path);
        }
Example #3
0
    protected override void FindPath()
    {
        this.m_TargetObjectPosition = this.m_TargetInfo.ActorPosition;

        List <TilePosition> border = BorderPointHelper.GetInflateOneBorder(this.m_TargetInfo);

        if (border.Contains(this.m_PreviousPosition - this.m_TargetObjectPosition))
        {
            this.m_TargetPosition = this.m_PreviousPosition;
            this.OnTargetReached();
        }
        else
        {
            List <TilePosition> aStarPath = AStarPathFinder.CalculateAStarPahtTile
                                                (this.FindPathStrategy, this.m_PreviousPosition, this.m_TargetPosition);

            this.m_LinePath.Clear();
            int destinationIndex = aStarPath.Count - 1;
            for (int i = destinationIndex - 1; i >= 0; i--)
            {
                TilePosition position = aStarPath[i];
                if (border.Contains(position - this.m_TargetObjectPosition))
                {
                    destinationIndex = i;
                    break;
                }
            }
            this.m_TargetPosition = aStarPath[destinationIndex];
            for (int i = 1; i <= destinationIndex; i++)
            {
                TilePosition astarPoint = aStarPath[i];
                this.m_LinePath.Enqueue(astarPoint);
            }
        }
    }
 public void ShouldFindStraightLine()
 {
     var surface = SurfaceFactory.CreateSurface(10, 10);
      var astar = new AStarPathFinder(surface);
      Path path = astar.FindPath(new Point(5, 5), new Point(7, 7));
      Assert.AreEqual(3, path.Count);
 }
Example #5
0
File: Unit.cs Project: Skittss/Hex
 protected BattleTurn.ActionArgs PerformAction(Player[] players, HexGrid grid, bool commitAction)
 {
     //if in range of target => attack
     if (CoordRange.CoordInRange(cubeCoordinate, target.CubeCoordinate, Stats.Range.Value))
     {
         if (commitAction)
         {
             BasicAttack(players, target, grid);
         }
         return(new BattleTurn.ActionArgs(this, target, BattleTurn.updateAction.Attack, null, -1));
     }
     //if out of range => try to move into range, move by step distance in unit stats.
     else
     {
         //follow shortest path if possible.
         Vector3[] path = AStarPathFinder.GetPath(cubeCoordinate, target.CubeCoordinate, Stats.Range.Value, grid.Size, grid.GetAllOccupiedTiles());
         if (!(path == null))
         {
             //calculate the index of the path to move to depending on move distance.
             // i.e. a unit with move distance 2 can skip the first location on the path,
             // and move to the second in one update call.
             int     moveIndex       = (Stats.MoveDistance.Value > path.Length) ? path.Length - 1 : Stats.MoveDistance.Value - 1;
             Vector3 stepDestination = path[moveIndex];
             if (commitAction)
             {
                 MoveToTile(grid, stepDestination);
             }
             //return action log data about what move the unit is making i.e. (this unit is acting, its moving, along path specified)...
             return(new BattleTurn.ActionArgs(this, target, BattleTurn.updateAction.Move, path, moveIndex));
         }
         //if no possible path is found, do nothing - there is no possible move.
         return(new BattleTurn.ActionArgs(this, null, BattleTurn.updateAction.None, null, -1));
     }
 }
        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();
        }
Example #7
0
        public void TestAStarLinearPath()
        {
            var world = new TrueCraft.World.World("default", new FlatlandGenerator());
            var astar = new AStarPathFinder();

            var watch = new Stopwatch();

            watch.Start();
            var path = astar.FindPath(world, new BoundingBox(),
                                      new Coordinates3D(0, 4, 0), new Coordinates3D(5, 4, 0));

            watch.Stop();
            DrawGrid(path, world);
            Console.WriteLine(watch.ElapsedMilliseconds + "ms");

            var expected = new[]
            {
                new Coordinates3D(0, 4, 0),
                new Coordinates3D(1, 4, 0),
                new Coordinates3D(2, 4, 0),
                new Coordinates3D(3, 4, 0),
                new Coordinates3D(4, 4, 0),
                new Coordinates3D(5, 4, 0)
            };

            for (var i = 0; i < path.Waypoints.Count; i++)
            {
                Assert.AreEqual(expected[i], path.Waypoints[i]);
            }
        }
Example #8
0
        public void FindPath()
        {
            Stopwatch watch = Stopwatch.StartNew();

            bool[,] boolMap = SearchHelpers.GetSearchBoolMap(theGameStatus.TheMap);
            Point            startLocation        = new Point(100, 100);
            Point            endLocation          = new Point(300, 300);
            SearchParameters tempSearchParameters = new SearchParameters(startLocation, endLocation,
                                                                         boolMap);

            AStarPathFinder tempAStarPathFinder = new AStarPathFinder(tempSearchParameters);
            List <Point>    tempPath            = tempAStarPathFinder.FindPath();

            if (tempPath.Count == 0)
            {
                TheGameCore.RaiseMessage("No path found: " + startLocation + "-" + endLocation);
            }
            else
            {
                tempPath.Insert(0, startLocation);
                Vector3[] tempVect3 = SearchHelpers.PathToVector3Array(theGameStatus.TheMap, tempPath, 0.1f);
                RenderLayerBase.TheSceneManager.TheRenderLayerGame.AddPath(tempVect3);
            }
            watch.Stop();
            TheGameCore.RaiseMessage("FindPath() took " + watch.ElapsedMilliseconds + "ms,: " + startLocation + "-" + endLocation);
        }
Example #9
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 AStarPathFinder();

            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);
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public IScene ConfigureScene(Size size)
        {
            /*var waypoints = new Collection<Point>
             * {
             *  new Point(15.0d, 120.0d),
             *  new Point(500.0d, 120.0d),
             *  new Point(500.0d, 380.0d),
             *  new Point(250.0d, 380.0d),
             *  new Point(250.0d, 585.0d)
             * };
             * var emitter = new EnemyWaveEmitter(
             *  waveFactory,
             *  new Rect(new Point(10.0d, 100.0d), new Point(20.0d, 140.0d)),
             *  Colors.Black,
             *  waypoints
             * );
             *
             * homeBase = new MyHomeBase(
             *  new Rect(new Point(225.0d, 590.0d), new Size(50.0d, 20.0d)),
             *  Colors.Black,
             *  2500.0d
             * );
             *
             * emitter.EnemyCreated += OnEnemyCreated;
             * emitter.EnemyKilled += OnEnemyKilled;
             * emitter.EnemyReachedEnd += OnEnemyReachedEnd;
             *
             * scene.Children.Add(new LandscapeMap(size, Colors.DarkBlue, Colors.CadetBlue));
             * scene.Children.Add(new WayPath(waypoints, Colors.BurlyWood, Colors.Brown));
             * scene.Children.Add(emitter);
             * scene.Children.Add(homeBase);
             * scene.Children.Add(new MyHomeBaseHealthIndicator(
             *  homeBase,
             *  new Rect(new Point(200.0d, 10.0d), new Size(200.0d, 10.0d)),
             *  Colors.Chartreuse,
             *  Colors.Chartreuse,
             *  Colors.Red)
             * );
             * scene.Children.Add(userPointer);*/

            var scene = game.Scene;

            /*seeker = new Seeker(new Vector2(100.0f, 100.0f), 0.85f, Colors.White, Colors.DarkSlateGray);
             * userPointer = new UserPointer(Colors.White);
             *
             * scene.Children.Add(seeker);
             * scene.Children.Add(userPointer);*/

            var pathFinder = new AStarPathFinder(game);

            //var enemy = new Enemy(scene.Resources, game.CoordinatesSystem, new Position(0, 1), pathFinder, 250.0f, 0.56f, 1.0f);
            //var landscape = new Landscape(scene.Resources, game.Map, size);

            //scene.Children.Add(landscape);
            //scene.Children.Add(new Grid(scene.Resources, new Size(25.0d, 25.0d), size));
            //scene.Children.Add(enemy);

            return(scene);
        }
 public void ShouldAvoidPixel()
 {
     var surface = SurfaceFactory.CreateSurface(10, 10);
      var astar = new AStarPathFinder(surface);
      surface.SetPixel(5, 5, Color.Black);
      var path = astar.FindPath(new Point(3, 3), new Point(7, 7));
      Assert.AreEqual(8, path.Count);
 }
Example #12
0
 void Update()
 {
     if (_pathFinder != null && _pathFinder.IsDone)
     {
         OnPathFound(_pathFinder.Path);
         _pathFinder = null;
     }
 }
Example #13
0
    protected override void FindPath()
    {
        List <TilePosition> aStarPath;
        List <TilePosition> linePath = AStarPathFinder.CalculatePathTile(this.FindPathStrategy, this.CharacterAI.BattleMapData.ActorObstacleArray,
                                                                         this.m_PreviousPosition, this.m_TargetPosition, out aStarPath);

        //this.CharacterAI.DrawPath(aStarPath);

        /*
         * Debug.Log("AStar Path Length is:" + aStarPath.Count);
         * foreach(TilePosition at in aStarPath)
         * {
         *      Debug.Log("row:" + at.Row + " ,column:" + at.Column);
         * }
         * Debug.Log("Line Path Length is:" + linePath.Count);
         * foreach (TilePosition lt in linePath)
         * {
         *      Debug.Log("row:" + lt.Row + " ,column:" + lt.Column);
         * }
         */
        this.SetPath(linePath);
        if (linePath.Count == 0)
        {
            this.OnTargetReached();
        }
        else
        {
            TilePosition targetTilePosition = linePath[linePath.Count - 1];

            if (this.m_MapData.GetBulidingObjectFromActorObstacleMap(targetTilePosition.Row, targetTilePosition.Column) !=
                this.m_Target)
            {
                Vector2      reachablePosition = (Vector2)PositionConvertor.GetWorldPositionFromActorTileIndex(linePath[linePath.Count - 2]);
                TilePosition targetTile        = aStarPath[aStarPath.Count - 1];
                for (int i = 1; i < aStarPath.Count; i++)
                {
                    if (this.m_MapData.GetBulidingObjectFromActorObstacleMap(aStarPath[i].Row, aStarPath[i].Column) == this.m_Target)
                    {
                        targetTile = aStarPath[i];
                        break;
                    }
                }
                Vector2 targetPosition = (Vector2)PositionConvertor.GetWorldPositionFromActorTileIndex(targetTile);

                if (Vector2.SqrMagnitude(targetPosition - reachablePosition) <= this.CharacterAI.AttackBehavior.AttackScopeSqr)
                {
                    this.m_TargetPosition = targetTile;
                    this.ShowTarget();
                    return;
                }
            }

            this.m_TargetPosition = targetTilePosition;
            this.m_Target         = this.CharacterAI.BattleMapData.GetBulidingObjectFromActorObstacleMap
                                        (this.m_TargetPosition.Row, this.m_TargetPosition.Column);
            this.ShowTarget();
        }
    }
 public void ShouldGoAround()
 {
     var surface = SurfaceFactory.CreateSurface(10, 10);
      surface.SetPixel(4, 4, Color.Black);
      surface.SetPixel(5, 4, Color.Black);
      surface.SetPixel(6, 4, Color.Black);
      var astar = new AStarPathFinder(surface);
      Path path = astar.FindPath(new Point(5, 7), new Point(5, 2));
      Assert.AreEqual(9, path.Count);
 }
Example #15
0
        private static void Main()
        {
            IPathFinder pathFinder = new AStarPathFinder(HeuristicFunc);

            data = GetData1();
            IEnumerable <IConnection> conns =
                pathFinder.FindPath(data.Item1, 0, 5);

            ShowPath(conns);
        }
Example #16
0
 public Node(AStarPathFinder pathFinder, Node parent, Vector2Int from, int pathCost)
 {
     path_finder  = pathFinder;
     position     = from;
     expect_cost += Mathf.Abs(pathFinder.destination.x - from.x);
     expect_cost += Mathf.Abs(pathFinder.destination.y - from.y);
     path_cost    = pathCost;
     index        = from.y * path_finder.dungeon.width + from.x;
     this.parent  = parent;
 }
Example #17
0
        public override Path InitiateTurn()
        {
            AStarPathFinder pf   = new AStarPathFinder(Path.PathAction.Attack);
            Path            path = pf.Find(Monster.Tile, Candidate.Tile);

            Monster.Tile.OccupiedBy = null;
            Monster.Tile            = null;

            return(path);
        }
Example #18
0
    public List <IGraphNode> findPath(GraphNode from, GraphNode destination)
    {
        if (pathFinder == null)
        {
            pathFinder = new AStarPathFinder();
        }

        AStarPathFinder.resetIGraphNode(aliveNode.ToArray());
        return(pathFinder.findPath(from, destination));
    }
Example #19
0
    /// <summary>
    /// Aborts and removes any existing path finder worker threads and paths.
    /// </summary>
    public void ClearPath()
    {
        if (_pathFinder != null)
        {
            _pathFinder.Abort();
            _pathFinder = null;
        }

        _path = null;
    }
 public void ShouldGoAroundWithoutTwisting()
 {
     var surface = SurfaceFactory.CreateSurface(400, 400);
      for (int y = 156; y <= 165; y++)
      {
     surface.SetPixel(174, y, Color.Black);
      }
      var astar = new AStarPathFinder(surface);
      Path path = astar.FindPath(new Point(179, 161), new Point(169, 161));
      Assert.AreEqual(15, path.Count);
 }
Example #21
0
    public List <IGraphNode> FindPath(Vector3 from, Vector3 destination)
    {
        AStarPathFinder.resetIGraphNode(outerQuadNode);

        IGraphNode nodeFrom = null, nodeDestination = null;

        quadTreeConnectedNode.GetGraphNode(from, ref nodeFrom);
        quadTreeConnectedNode.GetGraphNode(destination, ref nodeDestination);

        return(pathFinder.findPath(nodeFrom, nodeDestination));
    }
Example #22
0
    protected override void FindPath()
    {
        List <TilePosition> aStarPath = AStarPathFinder.CalculateAStarPahtTile
                                            (this.FindPathStrategy, this.m_PreviousPosition, this.m_TargetPosition);

        this.m_LinePath.Clear();
        for (int i = 1; i < aStarPath.Count; i++)
        {
            TilePosition astarPoint = aStarPath[i];
            this.m_LinePath.Enqueue(astarPoint);
        }
    }
Example #23
0
        public void PathsFinderTestManhattanDistance()
        {
            var entity   = new BaseMovable();
            var endPoint = new Point();

            var collisionSystem = new CompositeAbstractCollisionSystem(new EightWayPossibleMovement(new ManhattanDistance()));
            var tileSize        = new Point();
            var searchParams    = new SearchParameters(entity.Position.ToPoint(), endPoint, collisionSystem, new Rectangle(new Point(), tileSize));
            var path            = new AStarPathFinder(searchParams, new EightWayPossibleMovement(new ManhattanDistance()));

            Assert.AreNotSame(path.ClosedNodes, path.MapNodes);
        }
Example #24
0
        public void GoesAroundObstacles()
        {
            var map = new MapContext(5, 3);

            map.StartingPoint = new Point(0, 1);
            map.TargetPoint   = new Point(4, 1);
            map.Obstacles.Add(new Point(2, 2));
            map.Obstacles.Add(new Point(2, 1));

            var subject = new AStarPathFinder();
            var path    = subject.FindPath(map);

            Check.That(path.Steps).Not.Contains(new Point(2, 1));
        }
Example #25
0
        bool CheckMovementInitialization()
        {
            if (Selected && // we're selected
                Player.SelectedNode != null && // player has clicked on a map node
                (Player.SelectedNode.OccupiedBy == null || Player.SelectedNode.OccupiedBy.GetComponent <Hero>() == null) && // the map node is not occupied by an allied unit
                Reachable != null && Reachable.Contains(Player.SelectedNode))    // destination tile is reachable
            {
                // action upon completion
                Path.PathAction action;
                if (Player.SelectedNode.OccupiedBy == null)
                {
                    action = Path.PathAction.Move;
                }
                else if (Player.SelectedNode.OccupiedBy.GetComponent <Monster>() != null)
                {
                    action = Path.PathAction.Attack;
                }
                else
                {
                    action = Path.PathAction.Use;
                }

                // if we're attacking, check whether we still can
                if (action == Path.PathAction.Attack)
                {
                    if (AlreadyAttacked)
                    {
                        return(false);
                    }

                    AlreadyAttacked = true;
                }

                // forbid user interaction while moving
                Player.InvalidateSelection();
                Player.Mode = Player.PlayerMode.Waiting;
                Player.InvalidateHighlight(Reachable);

                // initilize movement
                AStarPathFinder pf = new AStarPathFinder(action);
                Path            = pf.Find(Tile, Player.SelectedNode);
                Tile.OccupiedBy = null;
                Tile            = null;

                return(true);
            }

            return(false);
        }
Example #26
0
        public void NoPathReturnsNull()
        {
            var map = new MapContext(5, 3);

            map.StartingPoint = new Point(0, 0);
            map.TargetPoint   = new Point(4, 1);
            map.AddObstacle(0, 1);
            map.AddObstacle(1, 0);
            map.AddObstacle(1, 1);

            var subject = new AStarPathFinder();
            var path    = subject.FindPath(map);

            Check.That(path).IsNull();
        }
Example #27
0
 public async void MoveEntityTo(Point endPoint, Entity entity, Point tileSize, MoverManager moverManager, bool interact = false, Point?interactWith = null)
 {
     var searchParams = new SearchParameters(entity.Position.ToPoint(), endPoint, CollisionSystem, new Size(Map.Width, Map.Height));
     await Task.Run(() =>
     {
         var path                 = new AStarPathFinder(searchParams, _possibleMovements).FindPath();
         var pathMover            = new PathMover(entity, new FinitePath(path), new ExpiringSpatialHashMovementComplete <Entity>(_expiringSpatialHash, PlayerEntity.Instance));
         pathMover.OnCancelEvent += (sender, args) => entity.MovingDirection = new Vector2();
         if (interact && interactWith != null)
         {
             pathMover.OnCompleteEvent += (sender, args) => Interact(interactWith.Value);
         }
         moverManager.AddMover(pathMover);
     });
 }
        // Если осталось мало противников, то может быть сложно их найти. Поэтому они сами нас найдут.
        private IEnumerator UpdateRandomEnemyPath()
        {
            while (true)
            {
                yield return(new WaitForSecondsRealtime(10));

                var activeEnemy = m_Enemies.First(x => x.activeInHierarchy)?.GetComponent <EnemyController>();
                if (activeEnemy != null)
                {
                    activeEnemy.Path = AStarPathFinder.FindPath(
                        activeEnemy.gameObject.transform.position,
                        m_Player.transform.position);
                }
            }
        }
Example #29
0
        public void FindsStraightPath()
        {
            var map = new MapContext(5, 3);

            map.StartingPoint = new Point(0, 1);
            map.TargetPoint   = new Point(4, 1);

            var subject = new AStarPathFinder();
            var path    = subject.FindPath(map);

            Check.That(path.Steps).ContainsExactly(
                new Point(1, 1),
                new Point(2, 1),
                new Point(3, 1),
                new Point(4, 1));
        }
Example #30
0
        private Command DoMouseMovement()
        {
            var destination = InputManager.GetMouseWorldPosition(Program.Game.Camera);

            if (Entity.X == destination.X && Entity.Y == destination.Y)
            {
                return(null);
            }

            if ((Program.Game.Map.FovMap.IsInFov(destination.X, destination.Y) || Program.Game.Map.IsExplored(destination.X, destination.Y)))
            {
                if (Program.Game.Map.CanEnter(destination.X, destination.Y))
                {
                    Program.Game.Map.FovMap.SetCellProperties(Entity.X, Entity.Y, true, true);

                    CurrentPath = AStarPathFinder.GetPath(new Point(Entity.X, Entity.Y), destination);

                    if (CurrentPath != null)
                    {
                        CurrentPath.Dequeue(); // Discard starting point

                        var step = CurrentPath.Dequeue();
                        var x    = step.X - Entity.X;
                        var y    = step.Y - Entity.Y;

                        if (CurrentPath.Count == 0)
                        {
                            CurrentPath = null;
                        }

                        return(new MoveCommand(x, y));
                    }
                }
                else
                {
                    var target = Program.Game.Entities.FirstOrDefault(e => e.HasComponent <FighterComponent>() && e.X == destination.X && e.Y == destination.Y);

                    if (target != null && Program.Game.Player.DistanceTo(target) < 2)
                    {
                        return(new AttackCommand(target));
                    }
                }
            }

            return(null);
        }
Example #31
0
        public static void Main(string[] args)
        {
            string stopJSON;
            string transportAndScheduleJSON;

            using (WebClient webClient = new WebClient())
            {
                stopJSON = webClient.DownloadString("https://api.trafi.com/api/stops?userLocationId=kaunas");
                transportAndScheduleJSON = webClient.DownloadString("https://api.trafi.com/api/v3/schedules?userLocationId=kaunas");
            }

            ILocationParser locationParser   = new TrafiApiLocationParser(stopJSON);
            var             locationsWithIds = ((TrafiApiLocationParser)locationParser).ParseLocationsWithIds();

            ITransportParser transportParser = new TrafiApiTransportParser(transportAndScheduleJSON);
            var transports = transportParser.ParseTransports(locationsWithIds);

            IGraphFormer <AStarNode> graphFormer = new GraphFormer <AStarNode>();
            var stopGraph = graphFormer.FormGraph(locationsWithIds, transports);

            ITransitAdder pedestrianPathAdder = new PedestrianTransitAdder();

            stopGraph = pedestrianPathAdder.AddTransits(stopGraph);

            IWeightCalculator       weightCalculator    = new PenalisingWeightCalculator(new WeightCalculator());
            IWeightCalculator       heuristicCalculator = new HeuristicCalculator();
            IPathFinder <AStarNode> pathFinder          = new AStarPathFinder(stopGraph, weightCalculator, heuristicCalculator);

            IInputReader  inputReader  = new ConsoleInputReader();
            IOutputWriter outputWriter = new ConsoleOutputWriter();
            var           stopWatch    = new Stopwatch();

            var startingStopID = ((ConsoleInputReader)inputReader).ReadStopID(locationsWithIds);
            var endingStopID   = ((ConsoleInputReader)inputReader).ReadStopID(locationsWithIds);
            var departureTime  = inputReader.ReadTime();

            stopWatch.Reset();
            stopWatch.Start();
            var path = pathFinder.FindBestPath(stopGraph.Nodes[startingStopID], stopGraph.Nodes[endingStopID], departureTime);

            stopWatch.Stop();

            path.Squash();
            outputWriter.WriteElapsedTime(stopWatch.Elapsed);
            outputWriter.WritePath(path);
        }
Example #32
0
File: NPC.cs Project: qmhoang/SKR
        private ActorAction CalculateNextMove()
        {
            var location = Holder.Entity.Get <GameObject>();

            if (_level != location.Level)
            {
                _level  = location.Level;
                _oldPos = location.Location;
                _pf     = new AStarPathFinder(_level, 1.41f);
            }


            _oldPos = location.Location;

            var player = _level.World.Player;

            var target = player.Get <GameObject>().Location;

            var sight = Holder.Entity.Get <SightComponent>();

            sight.CalculateSight();
            if (sight.IsVisible(target))
            {
                var distance = location.Location.DistanceTo(target);

                if (distance <= 1.5)
                {
                    return(new MeleeAttackAction(Holder.Entity, player, Holder.Entity, player.Get <BodyComponent>().GetRandomPart()));
                }
                else
                {
                    _pf.Compute(location.X, location.Y, target.X, target.Y);
                    int nx = location.X, ny = location.Y;

                    if (_pf.Walk(ref nx, ref ny, false))
                    {
                        var       newPosition = new Point(nx, ny);
                        Direction dir         = Direction.Towards(newPosition - location.Location);

                        return(new BumpAction(Holder.Entity, dir));
                    }
                }
            }
            return(new WaitAction(Holder.Entity));
        }
Example #33
0
        public IEnumerable <RobotAction> GetNextActions(Robot robot)
        {
            // find the closest unwrapped cells
            var finder = new SimpleTargetSelector(Problem.Map);

            var targets = finder.GetPotentialTargets(robot.Position, 1);

            // sort them by moves
            var bestScore = int.MaxValue;
            Queue <RobotAction> bestRoute = null;

            if (targets.Count == 0)
            {
                return new[] { RobotAction.Done }
            }
            ;

            foreach (var p in targets)
            {
                var route = AStarPathFinder.GetRouteTo(robot.Position, p, Problem.Map);

                if (route.Count <= bestScore)
                {
                    bestScore    = route.Count;
                    bestRoute    = route;
                    robot.Target = p;
                }
            }

            if (robot.PriorTarget != null && robot.Target != robot.PriorTarget)
            {
                var priorRoute = AStarPathFinder.GetRouteTo(robot.Position, robot.PriorTarget.Value, Problem.Map);
                if (priorRoute.Count != 0)
                {
                    if (priorRoute.Count <= bestScore)
                    {
                        return(priorRoute);
                    }
                }
            }

            robot.PriorTarget = robot.Target;
            return(bestRoute);
        }
    }
Example #34
0
        public override Path InitiateTurn()
        {
            MapNode goal     = Monster.Reachable.First();
            int     bestDist = DistancesSum(goal);

            foreach (MapNode node in Monster.Reachable)
            {
                int currDist = DistancesSum(node);

                if (currDist > bestDist)
                {
                    goal     = node;
                    bestDist = currDist;
                }
            }

            if (goal == Monster.Tile)
            {
                PatrolNext = true;
                return(null);
            }

            Path.PathAction action;
            if (goal.OccupiedBy == null)
            {
                action = Path.PathAction.Move;
            }
            else if (goal.OccupiedBy.GetComponent <Monster>() != null)
            {
                action = Path.PathAction.Attack;
            }
            else
            {
                action = Path.PathAction.Use;
            }

            AStarPathFinder pf   = new AStarPathFinder(action);
            Path            path = pf.Find(Monster.Tile, goal);

            Monster.Tile.OccupiedBy = null;
            Monster.Tile            = null;

            return(path);
        }
Example #35
0
    private int handleFindPath(AsyncTask task, IDictionary<int, object> oResult)
    {
        int err = 0;

        short[,] mapData = (short[,])task.getParamDict()[(int)TaskType.MapData];
        Vec2<short> startPos = (Vec2<short>)task.getParamDict()[(int)TaskType.StartPos];
        Vec2<short> endPos = (Vec2<short>)task.getParamDict()[(int)TaskType.EndPos];
        IList<AStarNode> path = new Deque<AStarNode>();
        oResult.Add((int)TaskType.PathResult, path);

        AStarPathFinder pathFinder = new AStarPathFinder(
                mapData, new AsyncDispatchBehaviour.GameMoveCost());

        err = (int)pathFinder.findPath(0, 1, startPos, endPos, path);

        return err;
    }
 public float onGetMoveSpeed(AStarPathFinder finder, int roleTypeId, short tileId)
 {
     float spd = 0.0F;
     switch (tileId)
     {
         case 0:
             spd = 0.15F;
             break;
         case 1:
             spd = 0.05F;
             break;
         default:
             spd = -1;
             break;
     }
     return spd;
 }
    private void test()
    {
        Debug.Log("begin test");

        /*
        AStarPathFinder pathFinder = new AStarPathFinder(mapData, new GameMoveCost(),
                new AStarHCostHuffman()
                //new AStarHCostEuclidean()
                //new AStarHCostChebyshev()
                );

        IList<Vec2<short>> path = new List<Vec2<short>>();
        Vec2<short> startPos = new Vec2<short>(3, 55), endPos = new Vec2<short>(70, 25);
        int err = (int)pathFinder.findPath(0, ref startPos, ref endPos, path);

        Debug.Log("found path with err=" + err);

        if (err == 0)
            printPath(path);
        //*/

        //*
        _num = 10000;
        for (int i = 0; i < _num; ++i)
        {
            AStarPathFinder pathFinder = new AStarPathFinder(mapData, new GameMoveCost(),
                    new AStarHCostHuffman()
                //new AStarHCostEuclidean()
                //new AStarHCostChebyshev()
                    );

            AsyncTask task = new AsyncTask(i + 1);

            task.getParamDict().Add(0, pathFinder);
            task.getParamDict().Add(1, i);

            task.onHandleTask = new OnHandleTask(onHandleTestTask);
            task.onCompleteTask = new OnCompleteTask(onCompleteTestTask);
            _dispatcher.dispatch(task);
        }
        //*/

        Debug.Log("end test");
    }
Example #38
0
 public void Awake()
 {
     pathFinder = gameObject.AddComponent<AStarPathFinder>();
     pathFinder.initialize(this);
 }
Example #39
0
 public void setMap(TileMap map, int maxHeight)
 {
     this.map = map;
     this.maxHeight = maxHeight;
     this.pathfinder = new AStarPathFinder(map);
 }