Ejemplo n.º 1
0
        public void ReturnsEmptySetIfNothingFound()
        {
            var search = new AStarSearch <int>(EqualityComparer <int> .Default, _ => Enumerable.Empty <(int, float)>());
            var result = search.FindAll(0, x => false, GrowHeuristic);

            Assert.AreEqual(0, result.Count);
        }
Ejemplo n.º 2
0
        public void FindsInitialNode()
        {
            var search = new AStarSearch <int>(
                EqualityComparer <int> .Default,
                _ => Enumerable.Empty <(int, float)>());

            var result = search.FindAll(33, x => true, GrowHeuristic);

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(0, result[0].Length);
            Assert.AreEqual(1, result[0].Steps.Length);
            Assert.AreEqual(33, result[0].Steps[0]);
        }
Ejemplo n.º 3
0
        public void FindShortestPath_ShouldFindShortestPathWithoutObstacles()
        {
            var graph = GraphFactory.CreateRectangularGraph(3, 3, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);

            // Cube coordinates are not so intuitive when it comes to visualizing them in your head, so let's use
            // offset ones and convert them to cube. Cube coordinate are used by the algorythm because it's
            // much easier to operate them when in comes to actual algorythms

            // From bottom right
            var start = new Coordinate2D(2, 2, OffsetTypes.OddRowsRight).To3D();
            // To top left
            var goal = new Coordinate2D(0, 0, OffsetTypes.OddRowsRight).To3D();

            var expectedPath = new List <Coordinate3D>
            {
                // From 2, 2 we move to 1,1, which is central
                new Coordinate2D(1, 1, OffsetTypes.OddRowsRight).To3D(),
                // From 1,1 we move to 1,0, since there is no direct connection between 1,1 and 0,0
                new Coordinate2D(1, 0, OffsetTypes.OddRowsRight).To3D(),
                goal
            };

            // For the simplest test we assume that all cells have type ground, as well as a unit
            var path = AStarSearch.FindShortestPath(graph, start, goal, MovementTypesFixture.Walking);

            Assert.That(path, Is.EqualTo(expectedPath));
        }
        public void TC_SearchResults()
        {
            var problem    = new Planner.SAS.Problem(new SASInputData(GetFilePath("TC_SearchResults.sas")));
            var heuristic  = new PDBHeuristic(problem);
            var problem2   = new Planner.SAS.Problem(new SASInputData(GetFilePath("TC_SearchResults2.sas")));
            var heuristic2 = new PDBHeuristic(problem2);
            var heap       = new RegularBinaryHeap();

            var search1   = new AStarSearch(problem, heuristic, heap);
            var solution1 = search1.Start();

            Assert.AreEqual(ResultStatus.SolutionFound, solution1);
            Assert.IsNotNull(search1.GetSolutionPlan());

            var search2   = new AStarSearch(problem2, heuristic2, heap);
            var solution2 = search2.Start();

            Assert.AreEqual(ResultStatus.NoSolutionFound, solution2);
            Assert.IsNull(search2.GetSolutionPlan());

            var search3   = new AStarSearch(problem, heuristic, heap, false, new TimeSpan(0), 5000);
            var solution3 = search3.Start();

            Assert.AreEqual(ResultStatus.TimeLimitExceeded, solution3);
            Assert.IsNull(search3.GetSolutionPlan());

            var search4   = new AStarSearch(problem, heuristic, heap, false, new TimeSpan(0, 1, 0), 0);
            var solution4 = search4.Start();

            Assert.AreEqual(ResultStatus.MemoryLimitExceeded, solution4);
            Assert.IsNull(search4.GetSolutionPlan());
        }
Ejemplo n.º 5
0
    void OnMouseDown()
    {
        //if it's a right click, cycle between passable, out of bounds and tree
        if (AStarSearch.ms_rmbDown)
        {
            Debug.Log("MouseButtonOneIsDown");
            AStarSearch.ReplaceTile(this);
            return;
        }


        if (ms_startingPosition == null)
        {
            ms_startingPosition = AStarSearch.GetAStarTileByWorldTile(this);
            ms_startingPosition.StartLerping();
        }
        else if (ms_endingPosition == null)
        {
            ms_endingPosition = AStarSearch.GetAStarTileByWorldTile(this);
            ms_endingPosition.StartLerping();
        }

        if (ms_startingPosition != null && ms_endingPosition != null)
        {
            ms_startingPosition.StopLerping();
            ms_endingPosition.StopLerping();

            AStarSearch.PerformSearch(ms_startingPosition, ms_endingPosition);

            ms_startingPosition = null;
            ms_endingPosition   = null;
        }
    }
Ejemplo n.º 6
0
        static void testPatterns(bool[] isSelected, int selectedCount, int position, int limit, Problem d, System.IO.StreamWriter writer)
        {
            if (selectedCount == limit)
            {
                if (TestResult.currentID < TestResult.IDStart)
                {
                    TestResult.currentID++;
                    return;
                }

                HashSet <int> pattern            = new HashSet <int>();
                bool          intersectsWithGoal = false;
                for (int i = 0; i < isSelected.Length; i++)
                {
                    if (isSelected[i])
                    {
                        pattern.Add(i);
                        if (d.GoalConditions.IsVariableConstrained(i))
                        {
                            intersectsWithGoal = true;
                        }
                    }
                }
                if (!intersectsWithGoal)
                {
                    TestResult.currentID++;
                    return;
                }

                DateTime     buildingStarted = DateTime.Now;
                PDBHeuristic h = new PDBHeuristic(d, true, new List <HashSet <int> > {
                    pattern
                });
                DateTime    buildingEnded = DateTime.Now;
                AStarSearch ast           = new AStarSearch(d, h);
                DateTime    searchStarted = DateTime.Now;
                ast.Start();
                DateTime searchEnded = DateTime.Now;
                writer.WriteLine(TestResult.currentID + "\t" + pattern.Count + "\t" + String.Format("{0:0.##}", (buildingEnded - buildingStarted).TotalSeconds) +
                                 "\t" + String.Format("{0:0.##}", (searchEnded - searchStarted).TotalSeconds) + "\t" + h.Statistics.HeuristicCallsCount);
                //res.Add(new TestResult(d, pattern, (buildingEnded - buildingStarted).TotalSeconds, (searchEnded - searchStarted).TotalSeconds, nodes));
                TestResult.currentID++;

                return;
            }
            if (selectedCount < limit - (isSelected.Length - position))
            {
                return;
            }

            if (position >= isSelected.Length)
            {
                return;
            }

            isSelected[position] = true;
            testPatterns(isSelected, selectedCount + 1, position + 1, limit, d, writer);
            isSelected[position] = false;
            testPatterns(isSelected, selectedCount, position + 1, limit, d, writer);
        }
Ejemplo n.º 7
0
        private static double Search(IProblem problem)
        {
            var searchEngine = new AStarSearch(problem, new StripsHeuristic(problem), new RegularBinaryHeap());

            searchEngine.Start();
            return(searchEngine.GetSolutionCost());
        }
Ejemplo n.º 8
0
 public override void Update()
 {
     if (Input.KeyPressed(Key.D))
     {
         var search = new DFS <NearbyTiles, MoveAction>(_graphSearch);
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, _graphSearch));
     }
     else if (Input.KeyPressed(Key.B))
     {
         var graphSearchBFS = new GraphSearchBFS <NearbyTiles, MoveAction>();
         var search         = new BFS <NearbyTiles, MoveAction>(graphSearchBFS);
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, graphSearchBFS));
     }
     else if (Input.KeyPressed(Key.G))
     {
         var search = new GreedySearch <NearbyTiles, MoveAction>(_graphSearch,
                                                                 node => Math.Abs(21 - node.State.Center.X) + Math.Abs(20 - node.State.Center.Y));
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, _graphSearch));
     }
     else if (Input.KeyPressed(Key.A))
     {
         var search = new AStarSearch <NearbyTiles, MoveAction>(_graphSearch,
                                                                node => Math.Abs(21 - node.State.Center.X) + Math.Abs(20 - node.State.Center.Y));
         Game.SwitchScene(new LabyrinthScene <NearbyTiles, MoveAction>(_problem, search, _graphSearch));
     }
 }
Ejemplo n.º 9
0
        public void testAIMA3eFigure3_15()
        {
            Map romaniaMap = new SimplifiedRoadMapOfPartOfRomania();
            IProblem <string, MoveToAction> problem = new GeneralProblem <string, MoveToAction>(
                SimplifiedRoadMapOfPartOfRomania.SIBIU,
                MapFunctions.createActionsFunction(romaniaMap),
                MapFunctions.createResultFunction(),
                SimplifiedRoadMapOfPartOfRomania.BUCHAREST.Equals,
                MapFunctions.createDistanceStepCostFunction(romaniaMap));

            ISearchForActions <string, MoveToAction> search
                = new AStarSearch <string, MoveToAction>(
                      new GraphSearch <string, MoveToAction>(),
                      MapFunctions.createSLDHeuristicFunction(
                          SimplifiedRoadMapOfPartOfRomania.BUCHAREST,
                          romaniaMap));
            SearchAgent <string, MoveToAction> agent = new SearchAgent <string, MoveToAction>(problem, search);

            ICollection <MoveToAction> actions = agent.getActions();

            Assert.AreEqual(
                "[Action[name==moveTo, location==RimnicuVilcea], Action[name==moveTo, location==Pitesti], Action[name==moveTo, location==Bucharest]]",
                actions.ToString());
            Assert.AreEqual("278",
                            search.getMetrics().get(QueueSearch <string, MoveToAction> .METRIC_PATH_COST));
        }
Ejemplo n.º 10
0
    public async Task FindConnectedPortals(
        Location location,
        MapTile tile,
        Dictionary <Portal, float> seeds
        )
    {
        var portals = mesh.Values.Where(portal => portal.tile1 == tile || portal.tile2 == tile);

        // track path tasks for awaiting
        var pathTasks = new List <Task>();
        // determine which portals are connected
        int tot = portals.Count();

        foreach (var portal in portals)
        {
            // compute the path cost to each neighbor border
            var newTask = Task.Run(() => {
                var aStar = new AStarSearch();
                // perform the search, and record the cost with the neighbors
                aStar.ComputePath(location, portal.Center, tile, (success, path, cost) => {
                    // path finding was a success, store this portal
                    if (success)
                    {
                        seeds[portal] = cost;
                    }
                });
            });
            // track the pathfinding tasks
            pathTasks.Add(newTask);
        }

        await Task.WhenAll(pathTasks);
    }
        /// <summary>
        /// A* forward search for a plan that satisfies the given goal.
        /// </summary>
        /// <returns>Returns null if a plan could not be found, or a list of the
        /// actions that must be performed, in order.</returns>
        public static Queue <ITransition> Plan(
            GoapAgent agent,
            WorldGoal goal)
        {
            var worldState = WorldState.Borrow();

            worldState[agent] = agent.GetState();
            var regressiveSearchGoal = RegressiveSearchWorldGoal.Borrow(goal);

            DebugUtils.Assert(worldState[agent].ContainsKey("x") &&
                              worldState[agent].ContainsKey("y") &&
                              worldState[agent].ContainsKey("z"),
                              "Agent's state must contain his position as 'x' and 'y' keys");

            var path = AStarSearch.Search(agent, regressiveSearchGoal, worldState, true);

            worldState.ReturnSelf();

            GoapAction.WithContext.ReportLeaks();
            State.ReportLeaks();
            WorldState.ReportLeaks();
            WorldGoal.ReportLeaks();
            RegressiveSearchWorldGoal.ReportLeaks();
            WorldEffects.ReportLeaks();

            return(path);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            allSheets      = new List <Tuple <Texture2D, string> >();
            kObjectFactory = new ObjectFactory();
            kSceneManager  = new SceneManager();
            start          = new Node();
            goal           = new Node();
            blocked        = new Node();



            search = new AStarSearch();

            nodeArray = new Node[256];

            for (int i = 0; i < 256; i++)
            {
                nodeArray[i]         = new Node();
                nodeArray[i].element = i;
            }
            base.Initialize();
            this.IsMouseVisible = true;
        }
Ejemplo n.º 13
0
    void Start()
    {
        snakeLogic = gameObject.GetComponent <Snake>();

        snake = gameObject.transform;
        head  = snake.GetChild(0);

        player = GameLogic.snake;

        mapX = GameLogic.mapX + 1;
        mapY = GameLogic.mapY + 1;

        snake.name = "enemy";
        SetRandomPos();

        pathFinder = new AStarSearch(GenMapGrid());
        exit       = null;
        stepped    = 0;
        timeLeft   = Random.Range(25, 60);

        if (GenEnemySpwnCoord() == null)
        {
            Debug.Log("coordintes not found..");
        }
    }
Ejemplo n.º 14
0
    // Use this for initialization
    protected override void Start()
    {
        Sight    = GetComponent <FieldOfView>();
        Search   = GetComponent <AStarSearch>();
        Path     = GetComponent <ASPathFollower>();
        Wander   = GetComponent <Wander>();
        Flee     = GetComponent <Flee>();
        Face     = GetComponent <Face>();
        Agent    = GetComponent <Agent>();
        Animator = GetComponent <Animator>();

        Terrain     = GameObject.Find("Terrain");
        SearchAgent = GetComponent <ASAgent>();
        herdCentre  = GameObject.Find("HerdCentre").gameObject;

        Path.enabled = true;
        Path.path    = new ASPath();
        Path.enabled = false;

        State = new FiniteStateMachine <Ankylosaurus>(this);
        State.Change(Idle.Instance);

        collision_time = 0.0f;
        health_time    = 0.0f;
        hunger_time    = 0.0f;
        thirst_time    = 0.0f;

        base.Start();
    }
Ejemplo n.º 15
0
    // Use this for initialization
    void Start()
    {
        graph = new AGraph();

        buildExample();

        BFS bfs = new BFS();

        bfs.setGraph(graph);
        AStarSearch aStar = new AStarSearch();

        aStar.setGraph(graph);

        //List<int> path = bfs.findPath (source, target, true);
        List <int> path = aStar.findPath(source, target, true);

        if (path != null)
        {
            String p = "";
            for (int i = 0; i < path.Count; i++)
            {
                if (i > 0)
                {
                    p += ", ";
                }
                p += path[i];
            }
            Debug.Log("Path found: " + p);
        }
        else
        {
            Debug.Log("No path found");
        }
    }
Ejemplo n.º 16
0
    static public PathInfo.PathRoute needAmmo(Map.MapNode[,] grid, PathInfo.PathRoute path, Vector3 playerPos, Vector3 ourFlag, List <Map.MapNode> openList, List <Map.MapNode> closedList)
    {
        if (path.Index == path.PathSize) //we need to calculate which ammo box is the 'safest'
        {
            List <Vector3> ammoBox         = new List <Vector3>();
            var            detectedObjects = GameObject.FindGameObjectsWithTag("AmmoBox");

            foreach (var detectedObject in detectedObjects)
            {
                if (detectedObject.GetComponent <Renderer>().enabled)
                {
                    ammoBox.Add(detectedObject.transform.position);
                }
            }

            int   bestAmmoBox          = 0;
            float DistFromFlag         = 300.0f;
            float DistToNearestBox     = 300.0f;
            float tempDistFromFlag     = 0.0f;
            float tempDistToNearestBox = 0.0f;
            for (int i = 0; i < ammoBox.Count; i++)
            {
                tempDistFromFlag     = Vector3.Distance(playerPos, ourFlag);
                tempDistToNearestBox = Vector3.Distance(playerPos, ammoBox[i]);
                if ((tempDistFromFlag + tempDistToNearestBox) < (DistFromFlag + DistToNearestBox))
                {
                    DistFromFlag     = tempDistFromFlag;
                    DistToNearestBox = tempDistToNearestBox;
                    bestAmmoBox      = i;
                }
            }
            path = AStarSearch.Search(grid, playerPos, ammoBox[bestAmmoBox], path, openList, closedList);
        }
        return(path);
    }
Ejemplo n.º 17
0
        public void testAStarSearch()
        {
            // added to narrow down bug report filed by L.N.Sudarshan of
            // Thoughtworks and Xin Lu of UCI

            // EightPuzzleBoard extreme = new EightPuzzleBoard(new int[]
            // {2,0,5,6,4,8,3,7,1});
            // EightPuzzleBoard extreme = new EightPuzzleBoard(new int[]
            // {0,8,7,6,5,4,3,2,1});
            EightPuzzleBoard board = new EightPuzzleBoard(new int[]
                                                          { 7, 1, 8, 0, 4, 6, 2, 3, 5 });
            //EightPuzzleBoard board = new EightPuzzleBoard(new int[]
            //{ 1, 0, 2, 3, 4, 5, 6, 7, 8 });

            IProblem <EightPuzzleBoard, IAction>          problem = new BidirectionalEightPuzzleProblem(board);
            ISearchForActions <EightPuzzleBoard, IAction> search
                = new AStarSearch <EightPuzzleBoard, IAction>(
                      new GraphSearch <EightPuzzleBoard, IAction>(),
                      EightPuzzleFunctions.createManhattanHeuristicFunction());
            SearchAgent <EightPuzzleBoard, IAction> agent
                = new SearchAgent <EightPuzzleBoard, IAction>(problem, search);

            Assert.AreEqual(23, agent.getActions().Size());
            Assert.AreEqual("1133", // "926" GraphSearchReduced Frontier
                            agent.getInstrumentation().getProperty("nodesExpanded"));
            Assert.AreEqual("676",  // "534" GraphSearchReduced Frontier
                            agent.getInstrumentation().getProperty("queueSize"));
            Assert.AreEqual("677",  // "535" GraphSearchReduced Frontier
                            agent.getInstrumentation().getProperty("maxQueueSize"));
        }
Ejemplo n.º 18
0
    static public PathInfo.PathRoute Roaming(Rigidbody rb, Map.MapNode[,] Map, PathInfo.PathRoute path, List <Vector3> validpath, List <Map.MapNode> openList, List <Map.MapNode> closedList, bool seenEnemy, GameObject Enemy)
    {
        //this behaviour scouts around the areas until they find an enemy. Once they have they will continue to attack them until the enemy is dead or themselves are dead

        if (!seenEnemy)
        {
            if (path.Index == path.PathSize)
            {
                var           seed = (int)System.DateTime.Now.Ticks;
                System.Random rnd  = new System.Random(seed);

                int ran = rnd.Next(1, validpath.Count - 1);


                path = AStarSearch.Search(Map, rb.transform.position, validpath[ran], path, openList, closedList);
            }
        }

        else if (seenEnemy)
        {
            if (path.Index == path.PathSize)
            {
                if (Enemy == null)
                {
                    seenEnemy = false;
                }
                else
                {
                    path = AStarSearch.Search(Map, rb.transform.position, Enemy.transform.position, path, openList, closedList);
                }
            }
        }
        return(path);
    }
Ejemplo n.º 19
0
        public void testAIMA3eFigure3_24()
        {
            Map romaniaMap = new SimplifiedRoadMapOfPartOfRomania();
            IProblem <string, MoveToAction> problem = new GeneralProblem <string, MoveToAction>(
                SimplifiedRoadMapOfPartOfRomania.ARAD,
                MapFunctions.createActionsFunction(romaniaMap),
                MapFunctions.createResultFunction(),
                SimplifiedRoadMapOfPartOfRomania.BUCHAREST.Equals,
                MapFunctions.createDistanceStepCostFunction(romaniaMap));

            ISearchForActions <string, MoveToAction> search = new AStarSearch <string, MoveToAction>(new TreeSearch <string, MoveToAction>(),
                                                                                                     MapFunctions.createSLDHeuristicFunction(SimplifiedRoadMapOfPartOfRomania.BUCHAREST, romaniaMap));
            SearchAgent <string, MoveToAction> agent = new SearchAgent <string, MoveToAction>(problem, search);

            Assert.AreEqual(
                "[Action[name==moveTo, location==Sibiu], Action[name==moveTo, location==RimnicuVilcea], Action[name==moveTo, location==Pitesti], Action[name==moveTo, location==Bucharest]]",
                agent.getActions().ToString());
            Assert.AreEqual(4, agent.getActions().Size());
            Assert.AreEqual("5",
                            agent.getInstrumentation().getProperty("nodesExpanded"));
            Assert.AreEqual("10",
                            agent.getInstrumentation().getProperty("queueSize"));
            Assert.AreEqual("11",
                            agent.getInstrumentation().getProperty("maxQueueSize"));
        }
Ejemplo n.º 20
0
        protected override void Initialize()
        {
            Time.Initialize();
            InputManager.Initialize();
            ScreenManager.Initialize(graphics);

            search = new AStarSearch(20, 20);

            foreach (AStarNode node in search.Nodes)
            {
                if (random.NextDouble() < 0.2)
                {
                    search.Nodes[random.Next(20), random.Next(20)].Passable = false;
                }
            }

            search.Start          = search.Nodes[0, 0];
            search.Start.Passable = true;
            search.End            = search.Nodes[size - 1, size - 1];
            search.End.Passable   = true;

            search.Search(); // A search is made here.

            path = new List <Vector3>();
            AStarNode current = search.End;

            while (current != null)
            {
                path.Insert(0, current.Position);
                current = current.Parent;
            }
            base.Initialize();
        }
Ejemplo n.º 21
0
        public List <NodeWithCost <Vector3Int> > FindPathFrom(Vector3Int fromTile, Vector3Int targetTile)
        {
            AStarSearch search = new AStarSearch(LevelManager.Instance.grid,
                                                 fromTile, targetTile);

            return(search.FindPath());
        }
Ejemplo n.º 22
0
	public void testAStarSearch() {
		// added to narrow down bug report filed by L.N.Sudarshan of
		// Thoughtworks and Xin Lu of UCI
		try {
			// EightPuzzleBoard extreme = new EightPuzzleBoard(new int[]
			// {2,0,5,6,4,8,3,7,1});
			// EightPuzzleBoard extreme = new EightPuzzleBoard(new int[]
			// {0,8,7,6,5,4,3,2,1});
			EightPuzzleBoard board = new EightPuzzleBoard(new int[] { 7, 1, 8,
					0, 4, 6, 2, 3, 5 });

			Problem problem = new Problem(board, EightPuzzleFunctionFactory
					.getActionsFunction(), EightPuzzleFunctionFactory
					.getResultFunction(), new EightPuzzleGoalTest());
			Search search = new AStarSearch(new GraphSearch(),
					new ManhattanHeuristicFunction());
			SearchAgent agent = new SearchAgent(problem, search);
			Assert.assertEquals(23, agent.getActions().size());
			Assert.assertEquals("926", agent.getInstrumentation().getProperty(
					"nodesExpanded"));
			Assert.assertEquals("534", agent.getInstrumentation().getProperty(
					"queueSize"));
			Assert.assertEquals("535", agent.getInstrumentation().getProperty(
					"maxQueueSize"));
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail("Exception thrown");
		}
	}
Ejemplo n.º 23
0
        public static void AStar()
        {
            var grid = new SquareGrid(10, 10);

            for (var x = 1; x < 4; x++)
            {
                for (var y = 7; y < 9; y++)
                {
                    grid.Walls.Add(new Location(x, y));
                }
            }
            grid.Forests = new HashSet <Location>
            {
                new Location(3, 4), new Location(3, 5),
                new Location(4, 1), new Location(4, 2),
                new Location(4, 3), new Location(4, 4),
                new Location(4, 5), new Location(4, 6),
                new Location(4, 7), new Location(4, 8),
                new Location(5, 1), new Location(5, 2),
                new Location(5, 3), new Location(5, 4),
                new Location(5, 5), new Location(5, 6),
                new Location(5, 7), new Location(5, 8),
                new Location(6, 2), new Location(6, 3),
                new Location(6, 4), new Location(6, 5),
                new Location(6, 6), new Location(6, 7),
                new Location(7, 3), new Location(7, 4),
                new Location(7, 5)
            };

            // Run A*
            var astar = new AStarSearch(grid, new Location(1, 4), new Location(8, 5));

            DrawGrid(grid, astar);
        }
Ejemplo n.º 24
0
        public void UpdateConnectionsForStation(Station station)
        {
            if (Stations.Count <= 1)
            {
                return;
            }

            foreach (Station otherStation in Stations)
            {
                if (station == otherStation)
                {
                    continue;
                }

                AStarSearch aStarSearch = new AStarSearch(worldMap, station.Tile, otherStation.Tile, GetNeighborsWithTracks);

                if (!aStarSearch.reachedDestination)
                {
                    continue;
                }

                station.connectedStations.Add(otherStation);

                Debug.Log("Station Added - " + otherStation.Tile.Position);
            }
        }
 void PaintMap(SquareGrid graph, AStarSearch astar)
 {
     for(int i = 0; i < graph.height; i++)
     {
         for(int j = 0; j < graph.width; j++)
         {
             Position id = new Position(i, j);
             Position ptr = id;
             if(!astar.cameFrom.TryGetValue(id, out ptr))
             {
                 ptr = id;
                 if (graph.walls.Contains(id))
                 {
                     GetImage((graph.height * i) + j).color = Color.green;
                 }
                 else
                 {
                     var go = mapGroup.transform.GetChild((graph.height * ptr.x) + ptr.y).gameObject;
                     go.GetComponent<Image>().color = Color.grey;
                 }
             }
             else
             {
                 var go = mapGroup.transform.GetChild((graph.height * ptr.x) + ptr.y).gameObject;
                 go.GetComponent<Image>().color = Color.red;
             }
         }
     }
 }
Ejemplo n.º 26
0
    /// <summary>
    /// Adds a pedestrian to the simulation
    /// </summary>
    public void AddPedestrian()
    {
        // Yes, it is a hack. Deal with it
        if (!mPedestriansParent)
        {
            mPedestriansParent      = new GameObject();
            mPedestriansParent.name = "Pedestrians";
        }

        GameObject pedestrian = GameObject.Instantiate(PedestrianPrefab);

        pedestrian.name = "AIPedestrian_" + mAgents.Count;
        pedestrian.transform.SetParent(mPedestriansParent.transform);
        Vector3 position = AStarSearch.GetRandomWaypoint(WaypointsExample.PedestriansGraph);

        position.y = 0.0f;
        pedestrian.transform.position = position;

        // Init the pedestrian behaviour
        pedestrian.GetComponent <PedestrianBehavior>().Init();
        pedestrian.GetComponent <NN.NeuralNetwork>().Init();

        if (mNNController == null)
        {
            mNNController = GameObject.FindGameObjectWithTag("Neural Network Controller").GetComponent <NN.NeuralNetwork>();
            mNNController.Init();
        }

        pedestrian.GetComponent <NN.NeuralNetwork>().SetConnectionWeights(mNNController.GetConnectionWeights());
        mAgents.Add(pedestrian.GetComponent <PedestrianBehavior>());
    }
Ejemplo n.º 27
0
    /// <summary>
    /// STEP 4 - connect all remaing borders internally, completing
    /// the border mesh
    /// </summary>
    public async Task AssembleInternalBorderMesh()
    {
        var pathTasks = new List <Task>();

        foreach (var b1 in borders)
        {
            foreach (var b2 in borders.Where(b => !b.Equals(b1)))
            {
                pathTasks.Add(
                    Task.Run(() => {
                    // get border's central location and search from it
                    var loc1  = b1.Center;
                    var loc2  = b2.Center;
                    var aStar = new AStarSearch();

                    // perform the search, and record the cost with the neighbors
                    aStar.ComputePath(loc1, loc2, this, (successful, path, cost) => {
                        if (successful)
                        {
                            b1.AddNeighbor(b2, cost, path);
                            b2.AddNeighbor(b1, cost, path);
                        }
                    });
                })
                    );
            }
        }
        // wait for the pathfinding to complete
        await Task.WhenAll(pathTasks);
    }
Ejemplo n.º 28
0
        [Test] //Partial vertical block
        public void PathFoundIsTheShortest_WhenPathIsPartiallyBlocked()
        {
            var grid = new PathfindingGrid(6, 5, Allocator.Persistent);

            SetArea(grid, 6, 5, 1, 1);
            grid.SetClearance(3, 0, 0);
            grid.SetClearance(3, 1, 0);
            grid.SetClearance(3, 2, 0);
            grid.SetClearance(3, 3, 0);

            NativeList <int> resultPath = new NativeList <int>(Allocator.Persistent);
            var pathFound = AStarSearch.TryGetPath(grid,
                                                   2, 0,
                                                   5, 4,
                                                   1, 1, Allocator.Persistent, resultPath);

            Assert.AreEqual(true, pathFound);
            Assert.AreEqual(2, resultPath[0]);
            Assert.AreEqual(8, resultPath[1]);
            Assert.AreEqual(14, resultPath[2]);
            Assert.AreEqual(20, resultPath[3]);
            Assert.AreEqual(27, resultPath[4]);
            Assert.AreEqual(28, resultPath[5]);

            grid.Dispose();
            resultPath.Dispose();
        }
Ejemplo n.º 29
0
        public void TestGetCorrectPoint()
        {
            AStarSearch.SetMesh(OneWall);
            var correctPoint = AStarSearch.TryGetCorrectPoint(new Point(1, 1));

            Assert.AreEqual(correctPoint, new Point(0, 0));
        }
Ejemplo n.º 30
0
        public Node <int> Search(ContactEntity GoalContact)
        {
            var Search = new AStarSearch <int>();
            var Root   = Adaptor();

            return(Search.Search(Root, ContactToNode(GoalContact)));
        }
Ejemplo n.º 31
0
        public void FindShortestPath_ShouldFindShortestPath_WhenThereArePenaltiesAndObstacles()
        {
            // Now let's make 1,1 water and block 1,2
            var graph = GraphFactory.CreateRectangularGraph(3, 3, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);

            graph.BlockCells(new Coordinate2D(1, 2, OffsetTypes.OddRowsRight).To3D());
            graph.SetCellsTerrainType(new Coordinate2D(1, 1, OffsetTypes.OddRowsRight).To3D(),
                                      MovementTypesFixture.Water);

            var start = new Coordinate2D(2, 2, OffsetTypes.OddRowsRight).To3D();
            var goal  = new Coordinate2D(0, 0, OffsetTypes.OddRowsRight).To3D();

            // Now we have two shortest paths - 1,1, 1,0, 0,0 costs 4, since there is a penalty on 1,1
            // And 2,1, 2,0, 1,0 0,0, costs 4 too. It's 1 cell longer, but there is no penalties.
            // We are expecting to take path 1 because of the heuristics - it's leades to our goal a bit more stright.
            var expectedPath = new List <Coordinate3D>
            {
                new Coordinate2D(1, 1, OffsetTypes.OddRowsRight).To3D(),
                new Coordinate2D(1, 0, OffsetTypes.OddRowsRight).To3D(),
                goal
            };

            var path = AStarSearch.FindShortestPath(graph, start, goal, MovementTypesFixture.Walking);

            Assert.That(path, Is.EqualTo(expectedPath));
        }
Ejemplo n.º 32
0
        private void RunSearch()
        {
            var grid = new PathfindingGrid(GridWidth, GridHeight, Allocator.Persistent);

            for (var i = 0; i < Cells.Length; ++i)
            {
                var cell = Cells[i];
                grid.SetClearance(cell.GridX, cell.GridY, cell.Clearance);
                grid.SetFlag(cell.GridX, cell.GridY, cell.Capabilities);
            }

            NativeList <int> path = new NativeList <int>(Allocator.Persistent);
            var pathFound         = AStarSearch.TryGetPath(grid,
                                                           SelectedCell1.GridX, SelectedCell1.GridY,
                                                           SelectedCell2.GridX, SelectedCell2.GridY,
                                                           UnitSize, UnitCapabilities,
                                                           Allocator.Persistent, path);

            foreach (var index in path)
            {
                Cells[index].SetCellColor(SelectedColor);
            }

            if (path.IsCreated)
            {
                path.Dispose();
            }

            grid.Dispose();
        }
Ejemplo n.º 33
0
		public void Initialize()
		{
			aStar = new AStarSearch();
			graph = new Graph(6);
			graph.Connect(0, 1);
			graph.Connect(0, 2);
			graph.Connect(1, 3);
			graph.Connect(1, 4);
			graph.Connect(4, 5, 1, false);
			graph.AdjacentLinks[0][0].IsActive = false;
		}
    void Start()
    {
        var graph = new SquareGrid(5, 5);
        for(int i = 0; i < 4; i++)
        {
            graph.walls.Add(new Position(i, 1));
        }

        ResetMapGroup(graph);

        var astar = new AStarSearch(graph, new Position(0, 0), new Position(0, 2));

        PaintMap(graph, astar);
    }
Ejemplo n.º 35
0
        public void Test_Hard_AStar()
        {
            IState init = new Square(new[] { 1, 2, 3, 4, 5, 6, 7, 0, 8 });

            AStarSearch strategy = new AStarSearch()
            {
                Heuristic = s => s.Heuristic()
            };

            SimpleSearch a = new SimpleSearch(strategy);
            var solution = a.Find(init);
            if (solution) PrintSolution(a.Solution);
            Assert.IsTrue(solution);
        }
Ejemplo n.º 36
0
    // Use this for initialization
    void Start()
    {
        if (debug) {

            AStarSearch astar = new AStarSearch(starttile, endtile);
            Debug.Log("Start!");
            int count = 0;
            foreach (IAStarNode node in astar.Route) {
                Debug.Log(string.Format("[{0}]: ",count++)+node.Position+ ", Rechable: " + astar.reachableTo(node, 2));
            }

            Debug.Log("End!");

        }
    }
Ejemplo n.º 37
0
    public bool GetSuccessors(AStarSearch astarsearch, PuzzleState parentState)
    {
      SticksNode parent_node = parentState as SticksNode;

      Coordinate pcoord = parent_node == null ? new Coordinate(-1,-1) : parent_node._coord;
      Coordinate ncoord;

      // push each possible move except allowing the search to go backwards
      int[] xx = { 0, 1, 1, 0, -1, -1 };
      int[] yy = { 1, 0, -1, -1, 0, 1 };
      for (int i = 0; i < xx.Length; i++)
      {
        ncoord = _coord.Xform(xx[i], yy[i]);
        if (pcoord != ncoord && _map.ContainsKey(ncoord) && GetCost(ncoord) < 9)
        {
          astarsearch.AddSuccessor(new SticksNode(_map, ncoord, _unit));
        }
      }
      return true;
    }
Ejemplo n.º 38
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Maze Solver!");
            Console.WriteLine("1) for small maze");
            Console.WriteLine("2) for large maze");

            Maze maze;

            var key = Console.ReadKey();
            if (key.KeyChar == '1') {
                maze = new Maze(GetMazeData(mazeDefinition), Tuple.Create(1, 1), Tuple.Create(13, 4));
            }
            else if (key.KeyChar == '2') {
                maze = new Maze(GetMazeData(mazeDefinition2), Tuple.Create(1, 1), Tuple.Create(35, 21));
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("Fine, I didn't want to solve a maze, anyway...");
                return;
            }

            AStarSearch strategy = new AStarSearch();
            strategy.Heuristic = s => s.Heuristic();
            var search = new SimpleSearch(strategy);
            search.Find(maze);

            Console.WriteLine("Initial");
            Console.WriteLine(maze);

            int moves = 0;
            foreach(var s in search.Solution)
            {
                Console.WriteLine($"{s.Action} ({++moves})");
                Console.WriteLine(s.State);
            }

            Console.WriteLine($"Solved in {moves} moves");
        }
Ejemplo n.º 39
0
    public static List<Vector2> searchEmptySpace(Vector2 centerpos, ItemBasis src)
    {
        List<Vector2> space = new List<Vector2>();
        for (int y = 0; y < 5; y++)
        {
            for (int x = 0; x < 5; x++)
            {
                Vector2 target = centerpos + new Vector2(x - 2, y - 2);
                List<Collider2D> hits = new List<Collider2D>(Physics2D.OverlapPointAll(target, searchmask));
                if (hits.Count == 0) space.Add(target);
                if (hits.Count == 1)
                {
                    if (hits[0].transform.tag.Equals(TagList.Item) && src != null)
                    {
                        if (hits[0].gameObject.GetComponent<ItemEntity>().Object == src) space.Add(target);
                    }
                }
            }
        }
        space.Sort((a, b) => (int)((a - centerpos).sqrMagnitude - (b - centerpos).sqrMagnitude));
        //Debug.Log("SpaceL: " + space.Count);
        Debug.Log("Pos:" + centerpos);
        var c2d = Physics2D.OverlapPoint(centerpos, TagList.getLayerMask(TagList.Road));
        List<Vector2> ret = new List<Vector2>();
        if (c2d != null) {
            TileEntity srctile = c2d.gameObject.GetComponent<TileEntity>();

            foreach (Vector2 dst in space)
            {
                c2d = Physics2D.OverlapPoint(dst, TagList.getLayerMask(TagList.Road));
                //Debug.Log("C2D: "+c2d);
                TileEntity dsttile = c2d != null ? c2d.gameObject.GetComponent<TileEntity>() : null;
                //Debug.Log("Dst: " + dsttile);
                if (dsttile != null)
                {
                    AStarSearch astar = new AStarSearch(srctile, dsttile);
                    //Debug.Log(astar.reachableWith(3));
                    //Debug.Log("TatalCost: "+AStarSearch.getTotalCost(astar.EndNode));
                    if (astar.reachableWith(3)) ret.Add(dst);

                }
            }
            ret.Sort((a, b) => (int)((a - centerpos).sqrMagnitude - (b - centerpos).sqrMagnitude));
            //Debug.Log("RetL: "+ret.Count);
        }

        return ret;
    }
Ejemplo n.º 40
0
 void Start()
 {
     eventManager = gameObject.GetComponent<EventManager> ();
     aStarSearch = GameObject.Find ("BlocksWorld").GetComponent<AStarSearch> ();
     objSelector = GameObject.Find ("BlocksWorld").GetComponent<ObjectSelector> ();
     macros = GameObject.Find ("BehaviorController").GetComponent<Macros> ();
 }
Ejemplo n.º 41
0
 public void newMilestonesFromAStar(Vector2 start, Vector2 end)
 {
     //Debug.LogFormat("{0} is Start AStar!",CharacterController.name);
     //Debug.LogFormat("S:{0},E:{1}",start,end);
     CurrentGoalPosition = end;
     if (Vector2.Distance(start, end) <= 1)
     {
         if (CharacterController.canMoveNextPosition(end))
         {
             newMileStones(new Vector2[] { end });
         }
         return;
     }
     int mask = TagList.getLayerMask(TagList.Wall, TagList.Road);
     Debug.logger.Log(CharacterController.name, string.Format("S:{0} E:{1}", start, end));
     var st = Physics2D.OverlapPoint(start,mask).GetComponent<TileEntity>();
     var et = Physics2D.OverlapPoint(end, mask).GetComponent<TileEntity>();
     //Debug.LogFormat("ST:{0},ET:{1}",st.Position,et.Position);
     isOpenRouteFunc isopenroutefunc = isOpenRoute;
     //calcSpecialNodeCostFunc caclspecialnodecostfunc = calcSpecialCost;
     AStarSearch search = new AStarSearch(st, et, SpecialNodeCoseCalculater,null,isopenroutefunc,calcScoreHeuristic);
     var route = new List<Vector2>(search.getRoutePositions(start,end));
     newMileStones(route.ToArray());
     Debug.logger.Log(CharacterController.name, showMileStones());
     //if(MilestonesIncludingEndPosition) route.Add(end);
     //Debug.LogFormat("{0} AStar End:{1},{2},{3}", CharacterController.name, start, end,route[0]);
 }
Ejemplo n.º 42
0
    private void OnPathRequest(Event<PathRequestEventPayload> eventArg)
    {
        if (searchSpace == null)
        {
            return;
        }

        PathRequestEventPayload request = eventArg.EventData;
        if (request.gameObject != searchSpace.gameObject)
        {
            return; // request not for us
        }

        MovingEntity movingEntity = request.gameObject.GetComponent<MovingEntity>();
        Vector2 requestorPosition2D = (movingEntity != null && movingEntity.enabled) ? movingEntity.Position2D : request.gameObject.transform.position.To2D();

        int source = searchSpace.GetClosestNodeToPosition(requestorPosition2D);

        if (source != Node.INVALID_NODE_INDEX)
        {
            // Requestor may be inside or too close to obstruction
            // so let's find the closest node to warp to
            source = searchSpace.GetClosestNodeToPosition(requestorPosition2D, true);
            if (source == SearchSpace.NO_CLOSEST_NODE_FOUND)
            {
                return; // screwed
            }
        }

        int target = searchSpace.GetClosestNodeToPosition(request.destination);
        if (target == SearchSpace.NO_CLOSEST_NODE_FOUND)
        {
            ////TODO: should we instead move the target to closest valid node??
            return;
        }

        var currentSearch = new AStarSearch(searchSpace.Graph, source, target);

        var path = new Path(
                this,
                searchSpace.gameObject,
                requestorPosition2D,
                request.destination,
                currentSearch.GetPathToTarget(),
                searchSpace.Graph);

        PathReadyEventPayload result =
            new PathReadyEventPayload(request.gameObject, path);
        EventManager.Instance.Enqueue<PathReadyEventPayload>(Events.PathReady, result);
    }
Ejemplo n.º 43
0
    static void astar(String[] args)
    {
      XmlDocument doc = new XmlDocument();
      doc.Load("c:/njones/src/SkippingRock/weewar.net/map.xml");
      WeewarMap map = new WeewarMap(doc.DocumentElement);
      AStarSearch astarsearch = new AStarSearch();
      bool[] path = new bool[map.Height * map.Width];
      Unit u = new Unit();
      u.Type = UnitType.Trooper;
      List<Terrain> bases = map.getTerrainsByType(TerrainType.Base);
      Coordinate cs = bases[0].Coordinate;
      Coordinate ce = bases[bases.Count-1].Coordinate;

      SticksNode start = new SticksNode(map, cs, u);
      SticksNode end = new SticksNode(map, ce, u);

      astarsearch.SetStartAndGoalStates(start, end);

      SearchState searchState;
      uint searchSteps = 0;

      do
      {
        searchState = astarsearch.SearchStep();
        searchSteps++;
      }
      while (searchState == SearchState.Searching);

      if (searchState == SearchState.Succeeded)
      {
        Console.WriteLine("Search found goal state");
        SticksNode node = astarsearch.GetSolutionStart() as SticksNode;

        Console.WriteLine( "Displaying solution");
        int steps = 0;
        for (; ; )
        {
          node = astarsearch.GetSolutionNext() as SticksNode;
          if (node == null)
          {
            break;
          }

          
          path[node.Coordinate.Y * map.Height + node.Coordinate.X] = true;
          //node.PrintNodeInfo();
          steps++;
        };
        for (int y = 0; y < map.Height; y++)
        {
          if (y % 2 == 1) Console.Write(" ");
          for (int x = 0; x < map.Width; x++)
          {
            if (x == start.Coordinate.X &&
              y == start.Coordinate.Y)
              Console.Write("S");
            else if (x == end.Coordinate.X &&
              y == end.Coordinate.Y)
              Console.Write("G");
            else
              Console.Write(path[y * map.Height + x] ? "x" : "o");
          }
          Console.WriteLine();
        }
        Console.WriteLine("Solution steps {0}", steps);
        // Once you're done with the solution you can free the nodes up
        astarsearch.FreeSolutionNodes();
      }
      else if (searchState == SearchState.Failed)
      {
        Console.WriteLine("Search terminated. Did not find goal state");

      }

      // Display the number of loops the search went through
      Console.WriteLine("searchSteps : " + searchSteps);

    }
Ejemplo n.º 44
0
    // Main


    public static int main(string[] args)
    {

      Console.WriteLine("STL A* Search implementation\n(C)2001 Justin Heyes-Jones");

      // Our sample problem defines the world as a 2d array representing a terrain
      // Each element contains an integer from 0 to 5 which indicates the cost 
      // of travel across the terrain. Zero means the least possible difficulty 
      // in travelling (think ice rink if you can skate) whilst 5 represents the 
      // most difficult. 9 indicates that we cannot pass.

      // Create an instance of the search class...

      AStarSearch astarsearch = new AStarSearch();
      bool[] path = new bool[MAP_HEIGHT * MAP_WIDTH];

      // Create a start state
      MapSearchNode nodeStart = new MapSearchNode();
      nodeStart.x = 0;
      nodeStart.y = 0;

      // Define the goal state
      MapSearchNode nodeEnd = new MapSearchNode();
      nodeEnd.x = 19;
      nodeEnd.y = 19;

      // Set Start and goal states

      astarsearch.SetStartAndGoalStates(nodeStart, nodeEnd);

      SearchState searchState;
      uint searchSteps = 0;

      do
      {
        searchState = astarsearch.SearchStep();
        searchSteps++;
      }
      while (searchState == SearchState.Searching);

      if (searchState == SearchState.Succeeded)
      {
        Console.Write("Search found goal state");
        MapSearchNode node = astarsearch.GetSolutionStart() as MapSearchNode;

        Console.WriteLine( "Displaying solution");
        int steps = 0;
        node.PrintNodeInfo();
        for (; ; )
        {
          node = astarsearch.GetSolutionNext() as MapSearchNode;
          if (node == null)
          {
            break;
          }

          path[node.y * MAP_HEIGHT + node.x] = true;
          //node.PrintNodeInfo();
          steps++;
        };
        for (int y = 0; y < MAP_HEIGHT; y++)
        {
          for (int x = 0; x < MAP_WIDTH; x++)
          {
            Console.Write(path[y * MAP_HEIGHT + x] ? "x" : "o");
          }
          Console.WriteLine();
        }
        Console.WriteLine("Solution steps {0}", steps);
        // Once you're done with the solution you can free the nodes up
        astarsearch.FreeSolutionNodes();
      }
      else if (searchState == SearchState.Failed)
      {
        Console.WriteLine("Search terminated. Did not find goal state");

      }

      // Display the number of loops the search went through
      Console.WriteLine("searchSteps : " + searchSteps);

      return 0;
    }
Ejemplo n.º 45
0
      // This generates the successors to the given Node. It uses a helper function called
      // AddSuccessor to give the successors to the AStar class. The A* specific initialisation
      // is done for each node internally, so here you just set the state information that
      // is specific to the application
      public bool GetSuccessors(AStarSearch astarsearch, PuzzleState parentState)
      {
        MapSearchNode parent_node = parentState as MapSearchNode;

        int parent_x = -1;
        int parent_y = -1;

        if (parent_node != null)
        {
          parent_x = (int)parent_node.x;
          parent_y = (int)parent_node.y;
        }


        MapSearchNode NewNode;

        // push each possible move except allowing the search to go backwards

        if ((GetMap(x - 1, y) < 9)
          && !((parent_x == x - 1) && (parent_y == y))
          )
        {
          NewNode = new MapSearchNode(x - 1, y);
          astarsearch.AddSuccessor(NewNode);
        }

        if ((GetMap(x, y - 1) < 9)
          && !((parent_x == x) && (parent_y == y - 1))
          )
        {
          NewNode = new MapSearchNode(x, y - 1);
          astarsearch.AddSuccessor(NewNode);
        }

        if ((GetMap(x + 1, y) < 9)
          && !((parent_x == x + 1) && (parent_y == y))
          )
        {
          NewNode = new MapSearchNode(x + 1, y);
          astarsearch.AddSuccessor(NewNode);
        }


        if ((GetMap(x, y + 1) < 9)
          && !((parent_x == x) && (parent_y == y + 1))
          )
        {
          NewNode = new MapSearchNode(x, y + 1);
          astarsearch.AddSuccessor(NewNode);
        }

        return true;
      }
    private bool reachableTest(List<Room> rooms)
    {
        //var rooms = mapgenerator.GeneratingFloor.Rooms;
        List<TileEntity> tiles = new List<TileEntity>();
        foreach (Room r in rooms)
        {
            Vector2 pos = r.CenterToInt;
            TileEntity tile = Physics2D.OverlapPoint(pos, TagList.getLayerMask(TagList.Road)).GetComponent<TileEntity>();
            tiles.Add(tile);
        }
        TileEntity start = tiles[0];
        TileEntity end = tiles[1];
        AStarSearch astar = new AStarSearch(start, end);
        bool rechable = astar.reachableTo(end, Int32.MaxValue);
        if (rechable)
        {
            for (int i = 2; i < tiles.Count; i++)
            {
                end = tiles[i];
                astar.routeRenew(end);
                rechable = rechable && astar.reachableTo(end, Int32.MaxValue);
                if (!rechable) return false;
            }

            return true;
        }
        return false;
    }
Ejemplo n.º 47
0
    protected override void ProcessGame(Game detailed)
    {
      Console.WriteLine();
      Console.WriteLine("Game: " + detailed.Name + " (" + detailed.Id + ")");
      Console.WriteLine("  Getting Map info: " + detailed.MapId);
      WeewarMap wmap = eliza.GetMap(detailed.MapId);
      //Console.WriteLine(  "  Getting Map info: "+wmap.Terrains);
      Faction f = detailed.GetFactionByPlayerName(eliza.User);
      Console.WriteLine("  .. moving my dudes. ");
      foreach (Unit unit in f.Units)
      {
        Console.WriteLine("-----------------------------------------------------------------------------");
        Console.WriteLine("     " + unit.Type + "(" + unit.Quantity + ") on " + unit.Coordinate);

        // repair if quantity below 5
        if (!unit.Finished && unit.Quantity < 5)
        {
          String m = eliza.Repair(detailed.Id, unit.Coordinate);
          Console.WriteLine("     " + ".. repairing => " + m);
          unit.Finished = true;
          continue;
        }

        //
        // request movement coordinates
        List<Coordinate> possibleMovementCoordinates = eliza.GetMovementCoords(detailed.Id, unit.Coordinate, unit.Type);
        Util.Shuffle(possibleMovementCoordinates);
        possibleMovementCoordinates.Insert(0, unit.Coordinate);

        // check if there is a capturable base in range
        if (!unit.Finished && unit.CanCapture())
        {
          Coordinate c = MatchFreeBase(possibleMovementCoordinates, wmap, detailed, f);
          if (c != null)
          {
            String m = eliza.MoveAttackCapture(detailed.Id, unit.Coordinate, c, null, true);
            unit.Coordinate = c;
            Console.WriteLine("     " + ".. moving to " + c + " and capturing =>" + m);
            unit.Finished = true;
          }
        }
        List<Coordinate> targets = getTargets(detailed, wmap, f);
        int minDistance = MinDistance(unit.Coordinate, targets);

        int n = 5;

        if (minDistance <= 5 && !unit.Finished)
        {

          // Different moving spots that will be evaluated
          // check for possible attack targets from one of the targets
          for (int i = 0; i < n && i < possibleMovementCoordinates.Count; i++)
          {
            Coordinate c = possibleMovementCoordinates[i];
            Console.WriteLine("     " + ".. checking movement Option :" + c + " ");
            Coordinate a = getAttackCoordinate(detailed, unit, c);
            Console.WriteLine("     " + "..  attack coord :" + a + " ");
            if (a != null && detailed.getUnit(c) == null)
            {
              String m = eliza.MoveAttackCapture(detailed.Id, unit.Coordinate, c, a, false);
              Console.WriteLine("     " + ".. moving to " + c + " attacking " + a + " =>" + m);
              if (c != null)
                unit.Coordinate = c;
              unit.Finished = true;
              break;
            }
          }
        }

        if (!unit.Finished && possibleMovementCoordinates.Count > 1)
        {
          List<Coordinate> cities = getEnemyCities(detailed, wmap, f);
          AStarSearch s = new AStarSearch();
          s.SetStartAndGoalStates(new SticksNode(wmap, unit), new SticksNode(wmap, cities[0], unit));
          SearchState searchState;
          do
          {
            searchState = s.SearchStep();
          }
          while (searchState == SearchState.Searching);
          if (searchState == SearchState.Succeeded)
          {
          }

          Util.Shuffle(targets);
          Util.Shuffle(cities);
          possibleMovementCoordinates.RemoveAt(0);

          while (possibleMovementCoordinates.Count > 5) possibleMovementCoordinates.RemoveAt(5);
          while (cities.Count > 3) cities.RemoveAt(3);
          while (targets.Count > 3) targets.RemoveAt(3);

          bool cnt = true;
          while (cnt)
          {
            Console.WriteLine("     " + ".. possible movement options: " + Coordinate.ToString(possibleMovementCoordinates));
            Console.WriteLine("     " + ".. possible Targets: " + Coordinate.ToString(targets));
            Coordinate c;

            if (unit.Type == UnitType.Trooper)
              c = getClosest(possibleMovementCoordinates, cities);
            else
            {
              c = getClosest(possibleMovementCoordinates, targets);
              if (c.Equals(unit.Coordinate) && targets.Count == 0 && possibleMovementCoordinates.Count > 1)
                c = possibleMovementCoordinates[1];
            }

            if (!c.Equals(unit.Coordinate) && detailed.getUnit(c) == null)
            {
              String m = eliza.MoveAttackCapture(detailed.Id, unit.Coordinate, c, null, false);
              Console.WriteLine("     " + ".. moving to " + c + " =>" + m);
              unit.Coordinate = c;
              cnt = false;
            }
            else
              possibleMovementCoordinates.Remove(c);
            cnt = cnt && possibleMovementCoordinates.Count > 0;
          }
        }

        //Thread.sleep( 300 );
      }

      if (f.Units.Count * 3 < (detailed.GetUnitCount() * 2) || f.Units.Count < 15)
      {
        Console.WriteLine("     Terrains :" + Terrain.ToString(f.Terrains));
        if (f.Credits > 75)
        {
          foreach (Terrain terrain in f.Terrains)
          {
            Console.WriteLine("     " + terrain.Type + " on " + terrain.Coordinate + " finished:" + terrain.Finished + " unit: " + (detailed.getUnit(terrain.Coordinate) != null));
            if (!terrain.Finished && detailed.getUnit(terrain.Coordinate) == null)
            {
              Console.WriteLine("     " + terrain.Type + " on " + terrain.Coordinate);
              List<UnitType> options = buildOptions[terrain.Type];
              UnitType buildType;
              do
              {
                int nd = dice(options.Count);
                buildType = options[nd - 1];
              } while (f.Credits < Unit.GetCost(buildType));
              String x = eliza.Build(detailed.Id, terrain.Coordinate, buildType);
              Console.WriteLine("     .... building " + buildType + " " + x);
              f.Credits = (f.Credits - Unit.GetCost(buildType));
            }
          }
        }
      }
      if (eliza.EndTurn(detailed.Id))
        Console.WriteLine(" .. finished turn.");
      else
        Console.WriteLine(" .. failed to finish turn [" + eliza.GetLastResult() + "]");
    }