Exemplo n.º 1
0
 public DeliverGoods(Actor self)
 {
     trader = self.Trait<Trader>();
     traderInfo = self.Info.Traits.Get<TraderInfo>();
     move = self.Trait<IMove>();
     pathFinder = self.World.WorldActor.Trait<IPathFinder>();
 }
Exemplo n.º 2
0
 public override void Initialise()
 {
     base.Initialise();
     _playerPathFinderCache = GameMainReferences.Instance.PlayerCharacter.Entity.EntityPathFinder;
     _rotTime = Random.Range(0f, 2000f);
     _player = GameMainReferences.Instance.PlayerCharacter.transform;
 }
Exemplo n.º 3
0
        /// <summary>
        /// Gets a path from the startPoint to the endPoint. Or null if there are no possible points
        /// </summary>
        /// <param name="startPoint"></param>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public static Stack<MapCoordinate> GetPath(MapCoordinate startPoint, MapCoordinate endPoint)
        {
            if (pathFinder == null)
            {
                if (nodes == null)
                {
                    GameState.LocalMap.GeneratePathfindingMap();
                    nodes = GameState.LocalMap.PathfindingMap;
                }

                //Create the new pathfinder with the map - add the settings
                pathFinder = new PathFinderFast(nodes);

                pathFinder.Formula = HeuristicFormula.Manhattan;
                pathFinder.Diagonals = false;
                pathFinder.HeavyDiagonals = false;
                pathFinder.HeuristicEstimate = 2;
                pathFinder.PunishChangeDirection = true;
                pathFinder.TieBreaker = false;
                pathFinder.SearchLimit = 5000;
            }

            List<PathFinderNode> path = pathFinder.FindPath(new Point(startPoint.X, startPoint.Y), new Point(endPoint.X, endPoint.Y));

            Stack<MapCoordinate> coordStack = new Stack<MapCoordinate>();

            if (path == null)
            {
                Console.WriteLine("No path found :(");
                return null;
            }

            //Check that all points are valid
            foreach (var point in path)
            {
                if (nodes[point.X, point.Y] > 100)
                {
                    Console.WriteLine("No path found :( ");
                    return null;

                }
            }

            foreach (PathFinderNode node in path)
            {
                coordStack.Push(new MapCoordinate(node.X, node.Y, 0, startPoint.MapType));
            }

            if (coordStack.Count == 0)
            {
                return null;
            }
            else
            {
                coordStack.Pop(); //remove the start node
                return coordStack;
            }
        }
Exemplo n.º 4
0
        internal FileSystem(ILogger logger, FileSystemFactory factory, IProcessStarter starter)
        {
            ThrowHelper.IfNullThenThrow(() => factory);

            _logger = logger;
            _factory = factory;
            _pathFinder = _factory.PathFinder(this);
            _starter = starter;
        }
Exemplo n.º 5
0
 public FindResources(Actor self)
 {
     harv = self.Trait<Harvester>();
     harvInfo = self.Info.Traits.Get<HarvesterInfo>();
     mobile = self.Trait<Mobile>();
     mobileInfo = self.Info.Traits.Get<MobileInfo>();
     resLayer = self.World.WorldActor.Trait<ResourceLayer>();
     territory = self.World.WorldActor.TraitOrDefault<ResourceClaimLayer>();
     pathFinder = self.World.WorldActor.Trait<IPathFinder>();
 }
Exemplo n.º 6
0
    public StupidEnemyCarHandling(GameObject enemy, VehicleBase currentVehicle)
    {
        HandlingObject  = enemy;
        _currentVehicle = currentVehicle;
        _pathFinder     = new StupidPathFinder();
        _prevPosition   = HandlingObject.transform.position;
        SetSpecifications();

        UpdateHandling();
        CurrentCondition = HandlingCondition.OnGround;
    }
Exemplo n.º 7
0
        public void RunPathFinder()
        {
            if (ChkUseFastPathFinder.Checked)
            {
                if (!(mPathFinder is PathFinderFast))
                {
                    if (mPathFinder != null)
                    {
                        mPathFinder.PathFinderDebug -= new PathFinderDebugHandler(PathFinderDebug);
                    }

                    mPathFinder = new PathFinderFast(PnlGUI.Matrix);
                    mPathFinder.PathFinderDebug += new PathFinderDebugHandler(PathFinderDebug);
                }
            }
            else
            {
                if (!(mPathFinder is PathFinder))
                {
                    if (mPathFinder != null)
                    {
                        mPathFinder.PathFinderDebug -= new PathFinderDebugHandler(PathFinderDebug);
                    }

                    mPathFinder = new PathFinder(PnlGUI.Matrix);
                    mPathFinder.PathFinderDebug += new PathFinderDebugHandler(PathFinderDebug);
                }
            }

            mPathFinder.Formula               = PnlGUI.Formula;
            mPathFinder.Diagonals             = ChkDiagonals.Checked;
            mPathFinder.HeavyDiagonals        = ChkHeavyDiagonals.Checked;
            mPathFinder.HeuristicEstimate     = (int)NumUpDownHeuristic.Value;
            mPathFinder.PunishChangeDirection = ChkPunishChangeDirection.Checked;
            mPathFinder.TieBreaker            = ChkTieBraker.Checked;
            mPathFinder.SearchLimit           = (int)NumSearchLimit.Value;
            mPathFinder.DebugProgress         = ChlShowProgress.Checked;
            mPathFinder.ReopenCloseNodes      = ChkReopenCloseNodes.Checked;
            mPathFinder.DebugFoundPath        = true;

            List <PathFinderNode> path = mPathFinder.FindPath(PnlGUI.Start, PnlGUI.End);

            UpdateTimeLabel(mPathFinder.CompletedTime);

            if (path == null)
            {
                MessageBox.Show("Path Not Found");
            }

            if (BtnStartStop.Text == STOP)
            {
                BtnStartStop_Click(null, EventArgs.Empty);
            }
        }
Exemplo n.º 8
0
 public FindAndDeliverResources(Actor self, Actor deliverActor = null)
 {
     harv              = self.Trait <Harvester>();
     harvInfo          = self.Info.TraitInfo <HarvesterInfo>();
     mobile            = self.Trait <Mobile>();
     locomotorInfo     = mobile.Info.LocomotorInfo;
     claimLayer        = self.World.WorldActor.Trait <ResourceClaimLayer>();
     pathFinder        = self.World.WorldActor.Trait <IPathFinder>();
     domainIndex       = self.World.WorldActor.Trait <DomainIndex>();
     this.deliverActor = deliverActor;
 }
Exemplo n.º 9
0
    private void Start()
    {
        _finder = new AStarPathFinder(_map, 500, false);

        _path = _finder.FindPath(3, 3, 6, 5);

        for (var i = 0; i < _path.GetLength(); i++)
        {
            //print("X: " + _path.GetStep(i).GetX() + " Y: " + _path.GetStep(i).GetY());
        }
    }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Game"/> class.
        /// </summary>
        /// <param name="logger">A reference to the logger in use.</param>
        /// <param name="applicationContext">A reference to the application context.</param>
        /// <param name="mapDescriptor">A reference to the map descriptor in use.</param>
        /// <param name="map">A reference to the map.</param>
        /// <param name="creatureManager">A reference to the creature manager in use.</param>
        /// <param name="itemFactory">A reference to the item factory in use.</param>
        /// <param name="creatureFactory">A reference to the creature factory in use.</param>
        /// <param name="containerManager">A reference to the container manager in use.</param>
        /// <param name="pathFinderAlgo">A reference to the path finding algorithm in use.</param>
        /// <param name="predefinedItemSet">A reference to the predefined item set declared.</param>
        /// <param name="monsterSpawnsLoader">A reference to the monster spawns loader.</param>
        /// <param name="scheduler">A reference to the global scheduler instance.</param>
        public Game(
            ILogger logger,
            IApplicationContext applicationContext,
            IMapDescriptor mapDescriptor,
            IMap map,
            ICreatureManager creatureManager,
            IItemFactory itemFactory,
            ICreatureFactory creatureFactory,
            IContainerManager containerManager,
            IPathFinder pathFinderAlgo,
            IPredefinedItemSet predefinedItemSet,
            IMonsterSpawnLoader monsterSpawnsLoader,
            IScheduler scheduler)
        {
            logger.ThrowIfNull(nameof(logger));
            applicationContext.ThrowIfNull(nameof(applicationContext));
            mapDescriptor.ThrowIfNull(nameof(mapDescriptor));
            map.ThrowIfNull(nameof(map));
            creatureManager.ThrowIfNull(nameof(creatureManager));
            itemFactory.ThrowIfNull(nameof(itemFactory));
            creatureFactory.ThrowIfNull(nameof(creatureFactory));
            containerManager.ThrowIfNull(nameof(containerManager));
            pathFinderAlgo.ThrowIfNull(nameof(pathFinderAlgo));
            predefinedItemSet.ThrowIfNull(nameof(predefinedItemSet));
            monsterSpawnsLoader.ThrowIfNull(nameof(monsterSpawnsLoader));
            scheduler.ThrowIfNull(nameof(scheduler));

            this.logger             = logger.ForContext <Game>();
            this.applicationContext = applicationContext;
            this.mapDescriptor      = mapDescriptor;
            this.map               = map;
            this.creatureManager   = creatureManager;
            this.itemFactory       = itemFactory;
            this.creatureFactory   = creatureFactory;
            this.containerManager  = containerManager;
            this.pathFinder        = pathFinderAlgo;
            this.predefinedItemSet = predefinedItemSet;
            this.scheduler         = scheduler;

            // Initialize game vars.
            this.worldInfo = new WorldInformation()
            {
                Status     = WorldState.Loading,
                LightColor = (byte)LightColors.White,
                LightLevel = (byte)LightLevels.World,
            };

            // Load the spawns
            this.monsterSpawns = monsterSpawnsLoader.LoadSpawns();

            // Hook some event handlers.
            this.scheduler.EventFired += this.ProcessFiredEvent;
            this.map.WindowLoaded     += this.OnMapWindowLoaded;
        }
Exemplo n.º 11
0
 public GraphServices(
     IMind mind,
     IConnectionManager connectionManager,
     IPathFinder pathFinder,
     INodeManager nodeManager)
 {
     _mind = mind;
     _connectionManager = connectionManager;
     _pathFinder = pathFinder;
     _nodeManager = nodeManager;
 }
Exemplo n.º 12
0
 //The usage of onValidate function is very effective instead of keep polling in while true loop
 private void OnValidate()
 {
     if (useDijkstra)
     {
         pathFinder = new Dijkstra <Vector3Int>();
     }
     else
     {
         pathFinder = new BFS <Vector3Int>();
     }
 }
Exemplo n.º 13
0
        /// <summary>Adds a path finder to an item.</summary>
        /// <param name="itemType">The type to add the finder to.</param>
        /// <param name="finder">The finder to add.</param>
        public static void RemoveFinder(Type itemType, IPathFinder finder)
        {
            lock (Instance)
            {
                logger.DebugFormat("Removing finder {0} for type {1}", finder, itemType);

                List <IPathFinder> newFinders = new List <IPathFinder>(GetFinders(itemType));
                newFinders.Remove(finder);
                Instance[itemType] = newFinders.ToArray();
            }
        }
Exemplo n.º 14
0
Arquivo: Unit.cs Projeto: gormel/rts
 public Unit(Game.Game game, IPathFinder pathFinder, Vector2 position)
 {
     Game          = game;
     PathFinder    = pathFinder;
     Destignation  = Position = position;
     mIntelligence = ExtendLogic(BTree.Build()
                                 .Sequence(b => b
                                           .Leaf(new TrySetOrderLeaf(this))
                                           .Leaf(new OrderLeaf(this))
                                           .Leaf(new RemoveOrderLeaf(this)))).Build();
 }
Exemplo n.º 15
0
    private AlgorithmData FindPath(IPathFinder pathFinder)
    {
        AlgorithmData alg = new AlgorithmData();

        float startTime = Time.realtimeSinceStartup;

        alg.path = pathFinder.FindPath(grid, grid[startX, startY], grid[endX, endY], out alg.checkedNodesCount, out alg.name)?.ToList();
        alg.time = (Time.realtimeSinceStartup - startTime) * 1000;

        return(alg);
    }
        protected override void TraitEnabled(Actor self)
        {
            // PERF: Avoid all AIs reevaluating assignments on the same tick, randomize their initial evaluation delay.
            scanForIdleMinersTicks = world.LocalRandom.Next(0, Info.MinimumScanDelay);

            pathfinder    = world.WorldActor.Trait <IPathFinder>();
            domainIndex   = world.WorldActor.Trait <DomainIndex>();
            resourceLayer = world.WorldActor.TraitOrDefault <UndergroundResourceLayer>();

            requestUnitProduction = player.PlayerActor.TraitsImplementing <IBotRequestUnitProduction>().ToArray();
        }
Exemplo n.º 17
0
        /// <summary>Adds a path finder to an item.</summary>
        /// <param name="itemType">The type to add the finder to.</param>
        /// <param name="finder">The finder to add.</param>
        public static void PrependFinder(Type itemType, IPathFinder finder)
        {
            lock (Instance)
            {
                logger.DebugFormat("Prepending finder {0} for type {1}", finder, itemType);

                List <IPathFinder> newFinders = new List <IPathFinder>(GetFinders(itemType));
                newFinders.Insert(0, finder);
                Instance[itemType] = newFinders.ToArray();
            }
        }
Exemplo n.º 18
0
 public FindResources(Actor self)
 {
     harv        = self.Trait <Harvester>();
     harvInfo    = self.Info.TraitInfo <HarvesterInfo>();
     mobile      = self.Trait <Mobile>();
     mobileInfo  = self.Info.TraitInfo <MobileInfo>();
     resLayer    = self.World.WorldActor.Trait <ResourceLayer>();
     territory   = self.World.WorldActor.TraitOrDefault <ResourceClaimLayer>();
     pathFinder  = self.World.WorldActor.Trait <IPathFinder>();
     domainIndex = self.World.WorldActor.Trait <DomainIndex>();
 }
Exemplo n.º 19
0
 public SpawnerHarvesterHarvest(Actor self)
 {
     harv        = self.Trait <SpawnerHarvesterMaster>();
     harvInfo    = self.Info.TraitInfo <SpawnerHarvesterMasterInfo>();
     mobile      = self.Trait <Mobile>();
     mobileInfo  = self.Info.TraitInfo <MobileInfo>();
     deploy      = self.Trait <GrantConditionOnDeploy>();
     claimLayer  = self.World.WorldActor.TraitOrDefault <ResourceClaimLayer>();
     pathFinder  = self.World.WorldActor.Trait <IPathFinder>();
     domainIndex = self.World.WorldActor.Trait <DomainIndex>();
     tranforms   = self.Trait <Transforms>();
 }
Exemplo n.º 20
0
 private void SetCurrentPathFinderFromStateName(string stateName)
 {
     if (stateName.StartsWith("not_greedy"))
     {
         currentPathFinder = new My_NotGreedyPathFinder();
     }
     else
     {
         currentPathFinder = new My_GreedyPathFinder();
     }
     WritePathFinderTypeToControlsTexts();
 }
Exemplo n.º 21
0
        protected override void TraitEnabled(Actor self)
        {
            pathfinder  = world.WorldActor.Trait <IPathFinder>();
            domainIndex = world.WorldActor.Trait <DomainIndex>();
            resLayer    = world.WorldActor.TraitOrDefault <ResourceLayer>();
            claimLayer  = world.WorldActor.TraitOrDefault <ResourceClaimLayer>();

            // Avoid all AIs scanning for idle harvesters on the same tick, randomize their initial scan delay.
            scanForIdleHarvestersTicks = world.LocalRandom.Next(Info.ScanForIdleHarvestersInterval, Info.ScanForIdleHarvestersInterval * 2);

            scanForEnoughHarvestersTicks = Info.ProduceHarvestersInterval;
        }
Exemplo n.º 22
0
 public virtual void DoInit(ActorObj actor)
 {
     actorObj = actor;
     if (pathFinder == null)
     {
         pathFinder = new WayPointPathFinder();
     }
     if (null != actorObj)
     {
         actorObj.AutoPathFind = false;
     }
 }
Exemplo n.º 23
0
    private void LeftMouseClick(long l)
    {
        lst2.Clear();
        Rect rect = new Rect();

        rect.width  = GridSize;
        rect.height = GridSize;
        rect.x      = GridSize;
        rect.y      = GridSize;
        lst2.Add(rect);

        Start = new Point2D(1, 1);

        //获得屏幕坐标
        Vector3 p = Input.mousePosition;
        int     x = ((int)p.x / (int)(GridSize * 100));
        int     y = ((int)p.y / (int)(GridSize * 100));

        End = new Point2D(x, y);  //计算终点坐标
        Debug.Log("mouse:" + p + " x/GridSize:" + x + " y/GridSize:" + y);

        lst4.Clear();
        lst4.Add(IndexConvertToRect(x, y));

        PathFinder             = new PathFinderFast(Matrix);
        PathFinder.Formula     = HeuristicFormula.Manhattan;          //使用我个人觉得最快的曼哈顿A*算法
        PathFinder.SearchLimit = 2000;                                //即移动经过方块(20*20)不大于2000个(简单理解就是步数)

        List <PathFinderNode> path = PathFinder.FindPath(Start, End); //开始寻径

        if (path == null)
        {
            Debug.Log("路径不存在!");
        }
        else
        {
            string output = string.Empty;
            for (int i = path.Count - 1; i >= 0; i--)
            {
                output = string.Format(output
                                       + "{0}"
                                       + path[i].X.ToString()
                                       + "{1}"
                                       + path[i].Y.ToString()
                                       + "{2}",
                                       "(", ",", ") ");


                lst2.Add(IndexConvertToRect(path[i].X, path[i].Y));
            }
            Debug.Log("路径坐标分别为:" + output);
        }
    }
Exemplo n.º 24
0
        public ComputationGraph(Graph.Graph graph, IPathFinder pathFinder, Vertex startVertex, Vertex endVertex)
        {
            _pathes = new List <List <DestroyableElement> >();
            _units  = new Dictionary <IGraphUnit, DestroyableElement>();


            // Заполняем словарь элементами
            foreach (var vertex in graph.Vertex)
            {
                _units.Add(vertex, new DestroyableElement(vertex));

                foreach (var edge in vertex.Edges)
                {
                    if (!_units.ContainsKey(edge))
                    {
                        _units.Add(edge, new DestroyableElement(edge));
                    }
                }
            }

            Pathes = pathFinder.FindAllPathes(graph, startVertex, endVertex);

            // На основе путей, составляем пути из DestroyableElements, так же добавляя
            // ребра между вершинами, потому что они тоже могут отказывать
            foreach (var path in Pathes)
            {
                var dPath = new List <DestroyableElement>();

                for (int i = 0; i < path.Count - 1; i++)
                {
                    var v1   = path[i];
                    var v2   = path[i + 1];
                    var edge = graph.GetEdge(v1, v2);   // Ребро гарантированно существует

                    var vUnit = _units[v1];
                    var vEdge = _units[edge];

                    vUnit.EncountsCount++;
                    vEdge.EncountsCount++;

                    dPath.Add(vUnit);
                    dPath.Add(vEdge);
                }

                // Добавляем последнюю вершину
                var unit = _units[path[path.Count - 1]];
                unit.EncountsCount++;
                dPath.Add(unit);

                _pathes.Add(dPath);
            }
        }
Exemplo n.º 25
0
 public ActionResult JavascriptBundle()
 {
     _path = new PathFinder(HttpContext, new UrlHelper(this.ControllerContext.RequestContext));
      string content;
      if (HttpContext.IsDebuggingEnabled) {
     content = ReadApplicationScript("~/scripts/main.js");
     return Content(content, "application/javascript");
      }
      else {
     content = ReadApplicationScript("~/scripts/Built/main.js");
     return Content(content, "application/javascript");
      }
 }
Exemplo n.º 26
0
        void ComputeRouteMatrix()
        {
            // prepare matrix
            if (routeMatrix == null)
            {
                needRefreshRouteMatrix = true;
                routeMatrix            = new int[_cellColumnCount * _cellRowCount];
            }

            if (!needRefreshRouteMatrix)
            {
                return;
            }

            needRefreshRouteMatrix = false;

            // Compute route
            for (int j = 0; j < _cellRowCount; j++)
            {
                int jj = j * _cellColumnCount;
                for (int k = 0; k < _cellColumnCount; k++)
                {
                    int cellIndex = jj + k;
                    if (cells [cellIndex].canCross && cells [cellIndex].visible)                        // set navigation bit
                    {
                        routeMatrix [cellIndex] = cells [cellIndex].group;
                    }
                    else                                        // clear navigation bit
                    {
                        routeMatrix [cellIndex] = 0;
                    }
                }
            }

            if (finder == null)
            {
                if ((_cellColumnCount & (_cellColumnCount - 1)) == 0)                   // is power of two?
                {
                    finder = new PathFinderFast(cells.ToArray(), _cellColumnCount, _cellRowCount);
                }
                else
                {
                    finder = new PathFinderFastNonSQR(cells.ToArray(), _cellColumnCount, _cellRowCount);
                }
            }
            else
            {
                finder.SetCalcMatrix(cells.ToArray());
            }
            needRefreshRouteMatrix = false;
        }
Exemplo n.º 27
0
 /// <summary>
 /// Instantiates each class which manipulates the EnvTile matrix with the relevant parameters
 /// </summary>
 /// <param name="mapScale">size of the map</param>
 /// <param name="mapDifficulty">number of randomly placed env blocks</param>
 /// <param name="exitCount">number of exits</param>
 /// <param name="guardAgentCount">number of guards</param>
 /// <param name="parentDictionary">Dictionary of gameobjects in hierarchy</param>
 /// <param name="mapCreationTolerance">number of times the algorithm should attempt to produce the map</param>
 /// <param name="hasMiddleTiles">determines if the map should have the middle tiles (corridors)</param>
 public TileLogicBuilder(int mapScale, int mapDifficulty, int exitCount, int guardAgentCount,
     Dictionary<ParentObject, GameObject> parentDictionary, int mapCreationTolerance = 500,
     bool hasMiddleTiles = true)
 {
     var matrixSize = MapScaleToMatrixSize(mapScale);
     _tileMatrixProducer =
         new TileMatrixProducer(parentDictionary[ParentObject.TopParent].transform.position, matrixSize);
     _spyTileLogic = new SpyTileLogic(matrixSize);
     _envTileLogic = new EnvTileLogic(matrixSize, mapDifficulty, hasMiddleTiles);
     _pathFinder = new PathFinder();
     _exitTileLogic = new ExitTileLogic(matrixSize, exitCount);
     _guardTileLogic = new GuardTileLogic(mapScale, matrixSize, guardAgentCount);
     _mapCreationTolerance = mapCreationTolerance;
 }
Exemplo n.º 28
0
        public void SetUp()
        {
            var grid = new byte[0x100, 0x100];

            for (int x = 100; x < 200; x++)
            {
                for (int y = 100; y < 200; y++)
                {
                    grid[x, y] = 10;
                }
            }

            this.pathFinder = new PathFinder(new GridNetwork(grid, true));
        }
Exemplo n.º 29
0
 public TileLogicSetup(ITileMatrixProducer tileMatrixProducer, ISpyTileLogic spyTileLogic,
                       IEnvTileLogic envTileLogic, IGuardTileLogic guardTileLogic, IExitTileLogic exitTileLogic,
                       IPathFinder pathFinder,
                       int mapCreationTolerance = 500, bool hasMiddleTiles = true)
 {
     _tileMatrixProducer   = tileMatrixProducer;
     _tileMatrix           = _tileMatrixProducer.Tiles;
     _spyTileLogic         = spyTileLogic;
     _envTileLogic         = envTileLogic;
     _guardTileLogic       = guardTileLogic;
     _pathFinder           = pathFinder;
     _exitTileLogic        = exitTileLogic;
     _mapCreationTolerance = mapCreationTolerance;
 }
Exemplo n.º 30
0
        public MoveAdjacentTo(Actor self, Target target)
        {
            Target = target;

            mobile = self.Trait<Mobile>();
            pathFinder = self.World.WorldActor.Trait<IPathFinder>();
            domainIndex = self.World.WorldActor.Trait<DomainIndex>();
            movementClass = (uint)mobile.Info.GetMovementClass(self.World.TileSet);

            if (target.IsValidFor(self))
                targetPosition = self.World.Map.CellContaining(target.CenterPosition);

            repath = true;
        }
Exemplo n.º 31
0
        public void RunPathFinder()
        {
            if (ChkUseFastPathFinder.Checked)
            {
                if (!(mPathFinder is PathFinderFast))
                {
                    if (mPathFinder != null)
                    {
                        mPathFinder.PathFinderDebug -= new PathFinderDebugHandler(PathFinderDebug);
                    }

                    mPathFinder = new PathFinderFast(matrix_Base.Matrix);
                    mPathFinder.PathFinderDebug += new PathFinderDebugHandler(PathFinderDebug);
                }
            }
            else
            {
                if (!(mPathFinder is PathFinder))
                {
                    if (mPathFinder != null)
                    {
                        mPathFinder.PathFinderDebug -= new PathFinderDebugHandler(PathFinderDebug);
                    }

                    mPathFinder = new PathFinder(matrix_Base.Matrix);
                    mPathFinder.PathFinderDebug += new PathFinderDebugHandler(PathFinderDebug);
                }
            }

            mPathFinder.Formula           = matrix_Base.Formula;
            mPathFinder.Diagonals         = ChkDiagonals.Checked;
            mPathFinder.HeuristicEstimate = (int)NumUpDownHeuristic.Value;
            mPathFinder.ReopenCloseNodes  = ChkReopenCloseNodes.Checked;
            mPathFinder.DebugFoundPath    = true;

            List <PathFinderNode> path = mPathFinder.FindPath(matrix_Base.Start, matrix_Base.End);

            UpdateTimeLabel(mPathFinder.CompletedTime);

            if (path == null)
            {
                MessageBox.Show("Path Not Found");
            }

            if (runSearch.Text == STOP)
            {
                BtnStartStop_Click(null, EventArgs.Empty);
            }
        }
Exemplo n.º 32
0
        public MoveAdjacentTo(Actor self, Target target)
        {
            Target = target;

            Mobile      = self.Trait <Mobile>();
            pathFinder  = self.World.WorldActor.Trait <IPathFinder>();
            domainIndex = self.World.WorldActor.Trait <DomainIndex>();

            if (target.IsValidFor(self))
            {
                targetPosition = self.World.Map.CellContaining(target.CenterPosition);
            }

            repath = true;
        }
Exemplo n.º 33
0
 public void ClearData()
 {
     _Matrix         = null;
     _PathFinder     = null;
     _Character      = null;
     _TargetPos      = Vector3.zero;
     _FinalTargetPos = Vector3.zero;
     if (_PathList != null)
     {
         _PathList.Clear();
         _PathList = null;
     }
     _LastStepPoses.Clear();
     _IsInSteer = false;
 }
Exemplo n.º 34
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Create a new board and init with blocks
            GridGenerator gen  = new GridGenerator(this.generatorOptions);
            var           grid = gen.Generate();

            this.pathfinderOptions.Grid = grid;

            this.board.Initialize(pathfinderOptions);
            IPathFinder path = PathFactory();

            path.Initialize(pathfinderOptions);
            path.Finished += (b) =>
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    this.go.Content = "Go";
                    this.go.Click  += Button_Click;
                }));
            };
            path.Log += (msg) =>
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    this.tb.AppendText(msg);
                    Debug.WriteLine(msg);
                }));
            };
            path.NodeVisited += (p) => System.Threading.Thread.Sleep(pathfinderOptions.StepDelayInMs);

            this.go.Content = "Cancel";
            this.go.Click  -= Button_Click;
            this.go.Click  += (s, e2) => path.Cancel();

            Task.Run(() =>
            {
                // Create a grid and traverse
                path.NodeVisited += delegate(Point p)
                {
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        Log($"{p}\r\n");
                        board.AddVisited(p);
                    }));
                };
                path.FindPath(new Point(0, 0), new Point(grid.GetLength(0) - 1, grid.GetLength(1) - 1));
            });
        }
Exemplo n.º 35
0
 public MercuryFacade(
     IValidator validator,
     IPathFinder pathFinder,
     IResourceLoader resourceLoader,
     ITemplateProcessor templateProcessor,
     IEmailer emailer,
     IOptions <MercurySettings> options)
 {
     this.resourceLoader    = resourceLoader.ThrowIfNull(nameof(resourceLoader));
     this.templateProcessor = templateProcessor.ThrowIfNull(nameof(templateProcessor));
     this.emailer           = emailer.ThrowIfNull(nameof(emailer));
     this.pathFinder        = pathFinder.ThrowIfNull(nameof(pathFinder));
     this.validator         = validator.ThrowIfNull(nameof(validator));
     settings = options.ThrowIfNull(nameof(options)).Value;
     settings.ThrowIfNull(nameof(settings));
 }
Exemplo n.º 36
0
        public MoveAdjacentTo(Actor self, Target target)
        {
            Target = target;

            mobile        = self.Trait <Mobile>();
            pathFinder    = self.World.WorldActor.Trait <IPathFinder>();
            domainIndex   = self.World.WorldActor.Trait <DomainIndex>();
            movementClass = (uint)mobile.Info.GetMovementClass(self.World.Map.Rules.TileSet);

            if (target.IsValidFor(self))
            {
                targetPosition = self.World.Map.CellContaining(target.CenterPosition);
            }

            repath = true;
        }
Exemplo n.º 37
0
        public AGSWalkComponent(IPathFinder pathFinder, IObjectFactory objFactory, IGame game)
        {
            _incomingInstructions = new ConcurrentQueue <WalkInstruction>();
            _state      = game.State;
            _cutscene   = _state.Cutscene;
            _events     = game.Events;
            _pathFinder = pathFinder;
            _objFactory = objFactory;

            _debugPath = new List <IObject>();
            AdjustWalkSpeedToScaleArea = true;
            MovementLinkedToAnimation  = true;
            WalkStep = new PointF(8f, 8f);

            _events.OnRepeatedlyExecute.Subscribe(onRepeatedlyExecute);
        }
Exemplo n.º 38
0
        private void ProcessUserInput()
        {
            if (building == null)
            {
                return;
            }

            Console.Write("Enter which room you are currently at: ");
            var roomFromInput = int.TryParse(Console.ReadLine(), out int sourceRoomNumber);

            Console.Write("Enter which room you would like to go to: ");
            var roomInput = int.TryParse(Console.ReadLine(), out int destinationRoomNumber);

            Console.Write("Choose the finding strategy: ");
            var         strategyInput = int.TryParse(Console.ReadLine(), out int findingStrategy);
            IPathFinder pathFinder    = null;

            switch (findingStrategy)
            {
            case 1:
                Console.Write("You picked up a transition dependent finding strategy," +
                              " please choose the transition types to avoid, separated by comma and space: ");
                var avoidedTransitionType = Console.ReadLine().Split(", ");
                pathFinder = new TransitionDependentPathFinder(building, avoidedTransitionType);
                break;

            case 2:
                Console.WriteLine("You picked up a least effort room finding strategy.");
                pathFinder = new LeastEffortPathFinder(building);
                break;

            case 3:
                Console.WriteLine("You picked up a lift based room finding strategy");
                pathFinder = new LiftMovingPathFinder(building);
                break;

            default:
                Console.WriteLine("Finding strategy not supported.");
                break;
            }

            if (pathFinder == null)
            {
                return;
            }
            pathFinder.PrintPath(sourceRoomNumber, destinationRoomNumber);
        }
Exemplo n.º 39
0
		public AGSWalkBehavior(IObject obj, IPathFinder pathFinder, IFaceDirectionBehavior faceDirection, 
                               IHasOutfit outfit, IObjectFactory objFactory, IGame game, IGLUtils glUtils)
		{
            _state = game.State;
            _cutscene = _state.Cutscene;
            _events = game.Events;
			_obj = obj;
			_pathFinder = pathFinder;
			_faceDirection = faceDirection;
			_outfit = outfit;
			_objFactory = objFactory;
            _glUtils = glUtils;

			_debugPath = new List<IObject> ();
			_walkCompleted = new TaskCompletionSource<object> ();
			_walkCompleted.SetResult(null);
            AdjustWalkSpeedToScaleArea = true;
            MovementLinkedToAnimation = true;
            WalkStep = new PointF(8f, 8f);

            _events.OnRepeatedlyExecute.Subscribe(onRepeatedlyExecute);
		}
Exemplo n.º 40
0
        public void CreateSolver(AlgorithmType algoType, IIndexedPathfindingMap map, double heuristic, 
            out IPathFinder<Vector2i> pathFinder, out IPathFindingListener<Vector2i> listener)
        {
            switch (algoType)
            {
                case AlgorithmType.AStar:
                    listener = new AStarListener();
                    pathFinder = new AStar<Vector2i>(map.GetNeighbors, map.DistanceEstimate, heuristic)
                    {
                        Listener = (IAStarListener<Vector2i>)listener
                    };
                    return;
                case AlgorithmType.Dijkstra:
                    listener = new DijkstraListener();
                    pathFinder = new Dijkstra<Vector2i>(map.GetNeighbors, map.DistanceEstimate)
                    {
                        Listener = listener
                    };
                    return;
            }

            throw new Exception($"Unrecognized algorithm type: {algoType}");
        }
Exemplo n.º 41
0
 public ActionResult JavascriptFile(String scriptName)
 {
     _path = new PathFinder(HttpContext, new UrlHelper(this.ControllerContext.RequestContext));
      string content;
      if (HttpContext.IsDebuggingEnabled) {
     content = ReadApplicationScript(string.Format("~/scripts/{0}", scriptName));
     return Content(content, "application/javascript");
      }
      else {
     content = ReadApplicationScript(string.Format("~/scripts/Built/{0}", scriptName));
     return Content(content, "application/javascript");
      }
 }
Exemplo n.º 42
0
 public ShortestPathTool(GPSMainForm parent)
     : base(parent)
 {
     pathFinder = new AStarPathFinder();
 }
Exemplo n.º 43
0
 public PathFinderCacheDecorator(IPathFinder pathFinder, ICacheStorage<List<CPos>> cacheStorage)
 {
     this.pathFinder = pathFinder;
     this.cacheStorage = cacheStorage;
 }
Exemplo n.º 44
0
 public string[,] FindAllPaths(string[,] matrix, IPathFinder pathFinderStrategy)
 {
     var clonedMatrix = (string[,])matrix.Clone();
     var resultMatrix = pathFinderStrategy.FindAllPaths(clonedMatrix);
     return resultMatrix;
 }
Exemplo n.º 45
0
 public AdminController(ISchemaExportEngine schemaExportEngine, INutrientRecommendationImporter nutrientRecommendationImporter, IIngredientImporterEngine ingredientImporterEngine, IInitialDataValuesExportEngine initialDataValuesExportEngine, IPathFinder pathFinder)
     : this(schemaExportEngine, nutrientRecommendationImporter, ingredientImporterEngine, initialDataValuesExportEngine)
 {
     this.pathFinder = pathFinder;
 }
Exemplo n.º 46
0
        private void map_LeftMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (_navigationEnabled == false || _mapinfo.HasNavCoordinates == false)
                return;

            Point p = e.GetPosition(this);
            Coordinate clickCoordinate = MapToWorld(new Coordinate((float)p.X, (float)p.Y, 0));
            System.Diagnostics.Debug.Print(clickCoordinate.X + "," + clickCoordinate.Y);

            GC.Collect();

            if (_mapArr != null)
            {
                CoordinateInt startIndex = _mapArr.GetClosestIndex(_user.Coordinate);
                CoordinateInt endIndex = _mapArr.GetClosestIndex(clickCoordinate);

                _pathFinder = new PathFinderFast(_mapArr.MapArr)
                {
                    Formula = HeuristicFormula.Manhattan,
                    Diagonals = true,
                    HeavyDiagonals = false,
                    HeuristicEstimate = (int)2,
                    PunishChangeDirection = false,
                    TieBreaker = true,
                    SearchLimit = (int)9000000,
                    DebugProgress = false,
                    DebugFoundPath = false
                };

                _selectedPath = _pathFinder.FindPath(new System.Drawing.Point(startIndex.X, startIndex.Y), new System.Drawing.Point(endIndex.X, endIndex.Y));

                _mapArr.Save(startIndex, endIndex);

                _selectedPathCoords = new List<Coordinate>();

                if (_selectedPath == null)
                {
                    MessageBox.Show("No Path Found");
                    return;
                }

                _selectedPath.Reverse();

                for (int i = 0; i < _selectedPath.Count; i += 1)
                {

                    Coordinate pnt1 =
                        WorldToMap(new Coordinate(_selectedPath[i].X / _mapArr.ArrScale + _mapArr.Min.X,
                                                  _selectedPath[i].Y / _mapArr.ArrScale + _mapArr.Min.Y, 0));

                    _selectedPathCoords.Add(pnt1);

                }

                GC.Collect();

            }
        }
    void Awake()
    {
        tiles = new SpriteRenderer[(int)gridSize.x, (int)gridSize.y];
        grid = new Grid2D((int)gridSize.x, (int)gridSize.y);

        switch (searchEngine)
        {
            case Engine.Fringe:
                pathFinder = new Fringe(Grid2D.HeuristicManhattan2);
                break;
            case Engine.AStar:
                pathFinder = new AStar(Grid2D.HeuristicManhattan2);
                break;
        }
    }
Exemplo n.º 48
0
		private bool testPathFinder(IPathFinder pathFinder, bool[][] array, float fromX, float fromY, float toX, float toY)
		{
			if (array != null) pathFinder.Init(array);
			AGSLocation from = new AGSLocation (fromX, fromY);
			AGSLocation to = new AGSLocation (toX, toY);
			IEnumerable<ILocation> points = pathFinder.GetWalkPoints(from, to);
			if (!points.Any()) return false;
			foreach (ILocation point in points)
			{
				Assert.IsTrue(array[(int)point.X][(int)point.Y]);
			}
			return true;
		}
Exemplo n.º 49
0
 public static void SetMap(byte[,] map)
 {
     pathfinder = new PathFinderFast(map);
     pathfinder.Diagonals = false;
 }
Exemplo n.º 50
0
		public HackyAI(HackyAIInfo info, ActorInitializer init)
		{
			Info = info;
			World = init.World;

			if (World.Type == WorldType.Editor)
				return;

			domainIndex = World.WorldActor.Trait<DomainIndex>();
			resLayer = World.WorldActor.Trait<ResourceLayer>();
			territory = World.WorldActor.TraitOrDefault<ResourceClaimLayer>();
			pathfinder = World.WorldActor.Trait<IPathFinder>();

			isEnemyUnit = unit =>
				Player.Stances[unit.Owner] == Stance.Enemy
					&& !unit.Info.HasTraitInfo<HuskInfo>()
					&& unit.Info.HasTraitInfo<ITargetableInfo>();

			unitCannotBeOrdered = a => a.Owner != Player || a.IsDead || !a.IsInWorld;

			foreach (var decision in info.PowerDecisions)
				powerDecisions.Add(decision.OrderName, decision);
		}
Exemplo n.º 51
0
        public void RunPathFinder()
        {
            CollisionPlane CP = PnlGUI.CurrentPlane;
            if (CP == null) return;
            if (ChkUseFastPathFinder.Checked)
            {
                if (!(mPathFinder is PathFinderFasting))
                {
                    if (mPathFinder != null)
                        mPathFinder.PathFinderDebug -= new PathFinderDebugHandler(PathFinderDebug);

                    CP.EnsureUpdated();

                    mPathFinder = new PathFinderFasting(CP.ByteMatrix);
                    mPathFinder.PathFinderDebug += new PathFinderDebugHandler(PathFinderDebug);
                }
            }
            else
            {
                if (!(mPathFinder is PathFinder))
                {
                    if (mPathFinder != null)
                        mPathFinder.PathFinderDebug -= new PathFinderDebugHandler(PathFinderDebug);

                    CP.EnsureUpdated();

                    mPathFinder = new PathFinder(CP.ByteMatrix);
                    mPathFinder.PathFinderDebug += new PathFinderDebugHandler(PathFinderDebug);
                }
            }

            mPathFinder.Formula = PnlGUI.Formula;
            mPathFinder.Diagonals = ChkDiagonals.Checked;
            mPathFinder.HeavyDiagonals = ChkHeavyDiagonals.Checked;
            mPathFinder.HeuristicEstimate = (int)NumUpDownHeuristic.Value;
            mPathFinder.PunishChangeDirection = ChkPunishChangeDirection.Checked;
            mPathFinder.TieBreaker = ChkTieBraker.Checked;
            mPathFinder.SearchLimit = (int)NumSearchLimit.Value;
            mPathFinder.DebugProgress = ChlShowProgress.Checked;
            mPathFinder.ReopenCloseNodes = ChkReopenCloseNodes.Checked;
            mPathFinder.DebugFoundPath = true;

            List<PathFinderNode> path = mPathFinder.FindPath(PnlGUI.Start, PnlGUI.End);
            UpdateTimeLabel(mPathFinder.CompletedTime);

            if (path == null)
                MessageBox.Show("Path Not Found");

            PnlGUI.DrawPath(path);

            if (BtnStartStop.Text == STOP)
                BtnStartStop_Click(null, EventArgs.Empty);
        }
Exemplo n.º 52
0
 /// <summary>
 /// Configures the Web Resources Path.
 /// </summary>
 /// <param name="finder"></param>
 public void Configure(IPathFinder finder)
 {
     Value = finder.GetPath();
     IsConfigured = true;
 }