public void BasicSearchAllTest()
        {
            DPNProblemContext   ctx     = GenerateProblemContext();
            DiscreteTimeAdapter adapter = new DiscreteTimeAdapter(ctx.StartTime, ctx.EndTime, 1);
            var graph = new BasicTravelHyperNetwork(ctx, adapter);

            graph.Build();

            var list = DepthFirstSearcher.FindAllPaths(graph,
                                                       new TravelHyperNode()
            {
                Time = 0, Station = ctx.Wor.Net.StationCollection.First(), Price = 0
            },
                                                       new TravelHyperNode()
            {
                Time = adapter.Horizon + 1440, Station = ctx.Wor.Net.StationCollection.Last(), Price = 0
            });

            foreach (var path in list)
            {
                Console.WriteLine(string.Join(",", path));
            }
            Assert.AreEqual(30, list.Count);
            //路径集
            TravelPath p = new TravelPath(graph, list[1]);

            Assert.AreEqual(ctx.Wor.Net.StationCollection.First(), p.StartStation);
        }
    public void LoadEnemies(Game game)
    {
        foreach (EnemyData enemyData in game.enemyData)
        {
            GameObject go;

            if (enemyData.enemyType > enemyPrefabs.Count)
            {
                Debug.LogWarning("Trying to load an enemy type that doesn't exist!");
                go = Instantiate(enemyPrefabs[0]);
            }
            else
            {
                go = Instantiate(enemyPrefabs[enemyData.enemyType]);
            }

            TravelPath path  = go.GetComponent <TravelPath>();
            Enemy      enemy = go.GetComponent <Enemy>();

            enemy.SetHealth(enemyData.health);
            enemy.transform.position = enemyData.position;
            enemy.transform.rotation = Quaternion.Euler(enemyData.rotation);

            path.pathNum = enemyData.pathNumber;
            path.i       = enemyData.headingToNode;

            path.pathGO       = paths[path.pathNum].gameObject;
            path.pathToFollow = paths[path.pathNum].nodes;

            spawnedEnemies.Add(go);
        }

        Debug.Log("Spawned enemies!");
    }
Exemple #3
0
        public void cheapestFirePathTest()
        {
            TravelWorld world = new TravelWorld();

            world.AddPlaces(1, 2, 3, 4);
            world.AddWay(1, 2, 10);
            world.AddWay(2, 3, 5);
            world.AddWay(4, 3, 5);
            world.SetFire(1, 2);
            world.SetFire(4, 3);
            var paths = world.findCheapestFirePaths(2).ToArray();

            if (paths.Count() != 2)
            {
                Assert.Fail();
            }

            var path1    = paths[0];
            var path2    = paths[1];
            var resPath1 = new TravelPath();

            resPath1.Add(1, 10);
            var resPath2 = new TravelPath();

            resPath2.Add(3, 5);
            resPath2.Add(4, 5);
            Assert.IsTrue(
                path1.Equals(resPath1) && path2.Equals(resPath2) ||
                path1.Equals(resPath2) && path2.Equals(resPath1));
        }
Exemple #4
0
        public void cheapestWaterPathWithFire()
        {
            TravelWorld world = new TravelWorld();

            world.AddPlaces(1, 2, 3, 4);
            world.AddWay(1, 2, 10);
            world.AddWay(2, 3, 1);
            world.AddWay(4, 3, 1);
            world.PutWater(1, 4);
            world.SetFire(2, 3);
            world.SetFire(4, 3);


            var paths = world.findCheapestWaterPaths(2);

            if (paths.Count() != 1)
            {
                Assert.Fail();
            }
            var path    = paths.First();
            var resPath = new TravelPath();

            resPath.Add(1, 10);
            Assert.AreEqual(path, resPath);
        }
Exemple #5
0
    // Use this for initialization
    IEnumerator Start()
    {
        while (!GameManager.S.shipsReady)
        {
            yield return(null);
        }

        AIManager.debugMode = true;

        this.comShipMovement = gameObject.GetComponentInChildren <ShipMovement>();

        //TODO: Stop doing this
        this.playerShipMovement = GameObject.Find("Player1").GetComponentInChildren <ShipMovement>();

        this.navigationPointPrefab = Resources.Load <GameObject>("Prefabs/NavigationPoint");

        this.grid = new List <NavigationPoint>();
        this.currentlyTravellingPath = new TravelPath();

        //Determine point separation based on the longer side (horizontal length)
        this.pointSeparation = Mathf.Abs(this.comShipMovement.viewportMaxX - this.comShipMovement.viewportMinX) / this.gridLength;

        this.BuildGrid();
        this.BuildBorders();
        this.PopulateAdjacentPoints();

        this.shipScanLayerMask = 1 << LayerMask.NameToLayer("NavigationPoint");
    }
Exemple #6
0
        static void Main(string[] args)
        {
            ServiceProvider serviceProvider = Setup();

            if (args.Length != 1)
            {
                throw new Exception("A solução deve receber somente um parametro, com o caminho para o arquivo de input");
            }

            String pathFile = args[0];

            IValidationBusiness  validationBusiness = serviceProvider.GetService <IValidationBusiness>();
            ITravelPathBusiness  travelPathBusiness = serviceProvider.GetService <ITravelPathBusiness>();
            IAirportBusiness     airportBusiness    = serviceProvider.GetService <IAirportBusiness>();
            IReadDestinationFile fileReader         = serviceProvider.GetService <IReadDestinationFile>();

            airportBusiness.Initialize(pathFile, fileReader);

            while (true)
            {
                Console.WriteLine("Por favor, entre a rota no formato AAA-BBB:");
                String strLine = Console.ReadLine();
                validationBusiness.ValidateInput(strLine, airportBusiness.GetAirportList());
                TravelPath path = travelPathBusiness.FindBestPath(strLine, airportBusiness.GetAirportList());
                Console.WriteLine(travelPathBusiness.GenerateOutput(path));
            }
        }
Exemple #7
0
        protected override void DoEnter(WowPlayer Entity)
        {
            //if travel path is not defined then generate from location points
            if (TravelPath == null)
            {
                //get current and destination as ppather locations
                var currentLocation     = new Location(Entity.Location.X, Entity.Location.Y, Entity.Location.Z);
                var destinationLocation = new Location(Destination.X, Destination.Y, Destination.Z);
                //calculate and store travel path
                TravelPath = ProcessManager.Caronte.CalculatePath(currentLocation, destinationLocation);
                //TravelPath.locations = new List<Location>(TravelPath.locations.Distinct<Location>());
            }

            //if there are locations then set first waypoint
            if (TravelPath.locations.Count > 0)
            {
                CurrentWaypoint = TravelPath.RemoveFirst();

                //Entity.Face(new Vector3D(CurrentWaypoint.X, CurrentWaypoint.Y, CurrentWaypoint.Z));
                _LastDistance = WaypointVector3DHelper.Vector3DToLocation(Entity.Location).GetDistanceTo(CurrentWaypoint);

                //if the distance to the next waypoint is less then 1f, use the get next waypoint method
                if (_LastDistance < 3f)
                {
                    CurrentWaypoint = GetNextWayPoint();
                    _LastDistance   =
                        WaypointVector3DHelper.Vector3DToLocation(Entity.Location).GetDistanceTo(CurrentWaypoint);
                }
            }
        }
Exemple #8
0
        public String GenerateOutput(TravelPath path)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append($"{path.ToString()}");

            return(sb.ToString());
        }
Exemple #9
0
    public override void OnInspectorGUI()
    {
        TravelPath path = (TravelPath)target;

        base.OnInspectorGUI();

        GUILayout.Label("Generate Path");
        numPoints = EditorGUILayout.IntField(numPoints);
    }
Exemple #10
0
        public JsonResult FindBestPath(string origin, string destination)
        {
            string filePath = configuration.GetSection("BexsTestConfig:InputFileLocation").Value.ToString();

            airportBusiness.Initialize(filePath, fileReader);
            TravelPath path = travelPathBusiness.FindBestPath(origin, destination, airportBusiness.GetAirportList());


            return(new JsonResult(Newtonsoft.Json.JsonConvert.SerializeObject(path)));
        }
Exemple #11
0
        public void TestOutput()
        {
            ServiceProvider serviceProvider = Setup();

            ITravelPathBusiness  travelPathBusiness = serviceProvider.GetService <ITravelPathBusiness>();
            IAirportBusiness     airportBusiness    = serviceProvider.GetService <IAirportBusiness>();
            IReadDestinationFile fileReader         = serviceProvider.GetService <IReadDestinationFile>();

            airportBusiness.Initialize("", fileReader);

            TravelPath test1 = travelPathBusiness.FindBestPath("A-B", airportBusiness.GetAirportList());

            Assert.AreEqual("Caminho A -> 0 B -> 10 Custo Total - 10", travelPathBusiness.GenerateOutput(test1));
        }
Exemple #12
0
        private ActionType actionToStopFire(TravelWorld currWorld)
        {
            if (_firePath == null)
            {
                _firePath = findFirePath(currWorld);
            }

            if (_firePath != null && _firePath.Count > 0)
            {
                int nextPlace = _firePath.TakeNextStep();
                return(new ActionType(world => { return drive(world, nextPlace); }));
            }
            else
            {
                return(noOpertion);
            }
        }
Exemple #13
0
        public double Run(TravelGameState state)
        {
            if (state.locations[_player] == _goal)
            {
                return(0);
            }
            TravelWorld world           = state.ToWorld();
            TravelPath  cheapPath       = world.findCheapestPath(state.locations[_player], _goal);
            var         closeToPenality = (_MaxMoves - state.totalMoves[_player]) - cheapPath.Count;
            var         res             = -cheapPath.Cost();

            if (closeToPenality <= 0)
            {
                res += 100;
            }
            return(res);
        }
Exemple #14
0
        protected override void DoExecute(WowPlayer Entity)
        {
            //on execute, first verify we have a waypoit to follow, else exit
            if (CurrentWaypoint == null)
            {
                Exit(Entity); return;
            }

            //verify we are moving, if we aren't then start moving
            if (!Entity.IsMoving())
            {
                Entity.MoveForward();
            }

            //get distances to waypoint
            float fDistance = MathFuncs.GetDistance(
                WaypointVector3DHelper.LocationToVector3D(CurrentWaypoint),
                Entity.Location, false);

            //if distance is growing instead of shrinking them face again
            if (fDistance > _LastDistance)
            {
                Entity.Face(new Vector3D(CurrentWaypoint.X, CurrentWaypoint.Y, CurrentWaypoint.Z));
            }

            //if distance to current waypoint is less then / equal to our tolerance, then move to the next waypoint if it exists, else stop/finish.
            if (fDistance <= Tolerance)
            {
                //if another waypoint exists, then switch to it
                if (TravelPath.GetFirst() != null)
                {
                    CurrentWaypoint = TravelPath.RemoveFirst();
                    Entity.Face(new Vector3D(CurrentWaypoint.X, CurrentWaypoint.Y, CurrentWaypoint.Z));
                }
                else
                {
                    Exit(Entity);
                    Finish(Entity);
                }
            }



            _LastDistance = fDistance;
        }
Exemple #15
0
        public override ActionType GetNextAction(TravelWorld world)
        {
            if (CurrentLocation == _targetPlace)
            {
                return(noOpertion);
            }

            TravelPath path = world.ShortestClearPath(CurrentLocation, _targetPlace);

            if (path == null || path.Count() == 0)
            {
                return(noOpertion);
            }

            int nextPlace = path.First();

            return(new ActionType(w => drive(w, nextPlace)));
        }
Exemple #16
0
        public void TestPaths()
        {
            ServiceProvider serviceProvider = Setup();


            ITravelPathBusiness  travelPathBusiness = serviceProvider.GetService <ITravelPathBusiness>();
            IAirportBusiness     airportBusiness    = serviceProvider.GetService <IAirportBusiness>();
            IReadDestinationFile fileReader         = serviceProvider.GetService <IReadDestinationFile>();

            airportBusiness.Initialize("", fileReader);

            TravelPath test1 = travelPathBusiness.FindBestPath("A-B", airportBusiness.GetAirportList());
            TravelPath test2 = travelPathBusiness.FindBestPath("A-C", airportBusiness.GetAirportList());
            TravelPath test3 = travelPathBusiness.FindBestPath("A-E", airportBusiness.GetAirportList());

            Assert.AreEqual("Caminho A -> 0 B -> 10 Custo Total - 10", test1.ToString());
            Assert.AreEqual("Caminho A -> 0 B -> 10 C -> 10 Custo Total - 20", test2.ToString());
            Assert.AreEqual("Caminho A -> 0 B -> 10 C -> 10 E -> 10 Custo Total - 30", test3.ToString());
        }
Exemple #17
0
        public void ClearPathTest()
        {
            TravelWorld world = new TravelWorld();

            world.AddPlaces(1, 2, 3, 4, 5);
            for (int i = 1; i <= 4; i++)
            {
                world.AddWay(i, i + 1, 1);
            }
            world.AddWay(5, 1, 1);
            world.SetFire(1, 2);
            var path    = world.ShortestClearPath(1, 3);
            var resPath = new TravelPath();

            resPath.Add(5, 1);
            resPath.Add(4, 1);
            resPath.Add(3, 1);

            Assert.IsTrue(resPath.Equals(path));
        }
Exemple #18
0
        protected override void DoEnter(WowPlayer Entity)
        {
            //if travel path is not defined then generate from location points
            if (TravelPath == null)
            {
                //get current and destination as ppather locations
                Location currentLocation     = new Location(Entity.Location.X, Entity.Location.Y, Entity.Location.Z);
                Location destinationLocation = new Location(Destination.X, Destination.Y, Destination.Z);
                //calculate and store travel path
                TravelPath = ProcessManager.Caronte.CalculatePath(currentLocation, destinationLocation);
            }

            //if there are locations then set first waypoint
            if (TravelPath.locations.Count > 0)
            {
                CurrentWaypoint = TravelPath.RemoveFirst();

                Entity.Face(new Vector3D(CurrentWaypoint.X, CurrentWaypoint.Y, CurrentWaypoint.Z));
                _LastDistance = WaypointVector3DHelper.Vector3DToLocation(Entity.Location).GetDistanceTo(CurrentWaypoint);
            }
        }
Exemple #19
0
    private IEnumerator EvadeAttacks()
    {
        while (this.currentAIState == AIState.Evasive)
        {
            TravelPath chosenPath = this.currentlyTravellingPath;

            PolarCoordinate oppositeDirection = new PolarCoordinate(this.sphereCastMagnitude, -this.currentlyTravellingPath.pathVector);
            this.startingAngle = oppositeDirection.angle + (Random.Range(-30f, 30f) * Mathf.Deg2Rad);
            this.endingAngle   = this.startingAngle + (360 * Mathf.Deg2Rad);

            Debug.DrawRay(this.comShipMovement.gameObject.transform.position, oppositeDirection.PolarToCartesian().normalized *this.sphereCastMagnitude, Color.green);

            //Scan from startAngle to endAngle
            for (float i = this.startingAngle; i < this.endingAngle; i += this.shipScanDegreeSeparation)
            {
                PolarCoordinate scanDirection   = new PolarCoordinate(this.sphereCastMagnitude, i);
                PolarCoordinate offsetPosition  = /*new PolarCoordinate(3 * this.sphereCastRadius, i);*/ new PolarCoordinate(this.sphereCastRadius, Vector3.zero);
                RaycastHit[]    detectedObjects = Physics.SphereCastAll(this.comShipMovement.gameObject.transform.position + offsetPosition.PolarToCartesian(),
                                                                        this.sphereCastRadius, scanDirection.PolarToCartesian().normalized, this.sphereCastMagnitude, this.shipScanLayerMask);
                TravelPath currentCheckedPath = new TravelPath();

                Debug.DrawRay(this.comShipMovement.gameObject.transform.position + offsetPosition.PolarToCartesian(), scanDirection.PolarToCartesian(), Color.red);

                currentCheckedPath.pathVector  = scanDirection.PolarToCartesian();
                currentCheckedPath.dangerScore = this.CompositeTotalDangerScore(detectedObjects);

                //Replace chosen direction if it's determined to be safer
                if (currentCheckedPath.dangerScore < this.currentlyTravellingPath.dangerScore)
                {
                    chosenPath.pathVector  = currentCheckedPath.pathVector;
                    chosenPath.dangerScore = currentCheckedPath.dangerScore;
                }
            }

            this.nextDirection = chosenPath.pathVector;

            yield return(new WaitForFixedUpdate());
        }
    }
Exemple #20
0
        public void cheapestFirePathTest2()
        {
            TravelWorld world = new TravelWorld();

            world.AddPlaces(1, 2, 3, 4);
            world.AddWay(1, 2, 10);
            world.AddWay(2, 3, 5);
            world.AddWay(4, 3, 5);
            world.SetFire(1, 2);
            var paths = world.findCheapestFirePaths(2).ToArray();

            if (paths.Count() != 1)
            {
                Assert.Fail();
            }

            var path1    = paths.First();
            var resPath1 = new TravelPath();

            resPath1.Add(1, 10);
            Assert.AreEqual(path1, resPath1);
        }
    public void SaveEnemies(ref Game game)
    {
        foreach (GameObject go in spawnedEnemies)
        {
            if (go != null)
            {
                EnemyData enemyData = new EnemyData();

                TravelPath path  = go.GetComponent <TravelPath>();
                Enemy      enemy = go.GetComponent <Enemy>();

                enemyData.enemyType     = enemy.enemyType;
                enemyData.health        = enemy.GetCurrentHealth();
                enemyData.pathNumber    = path.pathNum;
                enemyData.headingToNode = path.i;
                enemyData.position      = path.transform.position;
                enemyData.rotation      = path.transform.rotation.eulerAngles;

                game.enemyData.Add(enemyData);
            }
        }
    }
Exemple #22
0
        private ActionType actionToFindWater(TravelWorld currWorld)
        {
            if (currWorld.HaveWater(CurrentLocation))
            {
                return(new ActionType(world => { return pickupWater(world); }));
            }

            if (_waterPath == null || _waterPath.Count() == 0 || currWorld.isPathClear(_waterPath))
            {
                _waterPath = findWaterPath(currWorld);
            }


            if (_waterPath != null && _waterPath.Count > 0)
            {
                int nextPlace = _waterPath.TakeNextStep();
                return(new ActionType(world => { return drive(world, nextPlace); }));
            }
            else
            {
                return(noOpertion);
            }
        }
Exemple #23
0
        protected Location GetNextWayPoint()
        {
            Location Next = null;

            //get the next waypoint
            // The only criteria is that the next waypoint be at least 3 yards away from current
            // if all fail then skip to end
            while (TravelPath.GetFirst() != null)
            {
                //get next waypoint and remove it from the list at the same time
                Next = TravelPath.RemoveFirst();

                //check distance to the waypoint
                float distance = CurrentWaypoint.GetDistanceTo(Next);

                //if distance greater then 3f then return this waypoint
                if (distance > 10f)
                {
                    break;
                }
            }

            return(Next);
        }
        public double takeWaterHuristic(TravelSearchState state)
        {
            if (state.CarryWatter)
            {
                return(0);
            }
            TravelWorld world = state.ToWorld();

            if (world.HaveWater(state.CurrentLocation))
            {
                return(1);
            }

            var paths = world.findCheapestWaterPaths(state.CurrentLocation);

            if (paths == null || paths.Count() == 0)
            {
                return(double.MaxValue);
            }

            TravelPath path = paths.First();

            return(path.Cost());
        }
        public void LRxPathSearchTest()
        {
            DPNProblemContext   ctx      = GenerateProblemContext();
            CustomerArrival     customer = new CustomerArrival();
            DiscreteTimeAdapter adapter  = new DiscreteTimeAdapter(ctx.StartTime, ctx.EndTime, 1);

            TravelPath p     = new TravelPath();
            var        graph = new LRxTravelHyperNetwork(ctx, adapter,
                                                         ObjectNetworkFactory.Create("", ctx, adapter),
                                                         customer,
                                                         new Dictionary <CustomerArrival, List <TravelPath> >()//path dict
            {
                { customer, new List <TravelPath>()
                  {
                      p
                  } }
            },
                                                         new Dictionary <IServiceSegment, decimal>()//rho
            {
                { ctx.Wor.RailwayTimeTable.Trains.First().ServiceSegments.First(), 0 },
                { ctx.Wor.RailwayTimeTable.Trains.First().ServiceSegments.Last(), 0 },
                { ctx.Wor.RailwayTimeTable.Trains.Last().ServiceSegments.First(), 0 }
            },
                                                         new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >()
            {
                { customer, new Dictionary <TravelPath, decimal>()
                  {
                      { p, 1 }
                  } }
            },//mu
                                                         new Dictionary <IEdge <TravelHyperNode>, decimal>());

            graph.Build();

            DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>(graph,
                                                                                                             new TravelHyperNode()
            {
                Time = 0, Station = ctx.Wor.Net.StationCollection.First(), Price = 0
            });

            Assert.IsTrue(dijkstra.HasPathTo(new TravelHyperNode()
            {
                Time = adapter.Horizon + 1440, Station = ctx.Wor.Net.StationCollection.Last(), Price = 0
            }) == true);

            var desNode = new TravelHyperNode()
            {
                Time = adapter.Horizon + 1440, Station = ctx.Wor.Net.StationCollection.Last(), Price = 0
            };
            var pathToC      = string.Empty;
            var shortestPath = dijkstra.ShortestPathTo(desNode);

            foreach (var node in shortestPath)
            {
                pathToC = String.Format("{0}({1}) -> ", pathToC, node);
            }

            pathToC = pathToC.TrimEnd(new char[] { ' ', '-', '>' });
            Console.WriteLine("Shortest path to Station 'C': " + pathToC + "\r\n");
            Assert.AreEqual(202m, Math.Round(dijkstra.DistanceTo(desNode)));
        }