protected override void Update(GameTime gameTime)
        {
            Time.Update(gameTime);
            InputManager.Update();
            if (InputManager.IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            if (InputManager.IsKeyPressed(Keys.Space))
            {
                while (!(search.Start = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
                {
                    ;
                }
                while (!(search.End = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
                {
                    ;
                }
                search.Search();
                path.Clear();
                AStarNode current = search.End;
                while (current != null)
                {
                    path.Insert(0, current.Position);
                    current = current.Parent;
                }
            }
            base.Update(gameTime);
        }
Esempio n. 2
0
        public Node <int> Search(ContactEntity GoalContact)
        {
            var Search = new AStarSearch <int>();
            var Root   = Adaptor();

            return(Search.Search(Root, ContactToNode(GoalContact)));
        }
Esempio n. 3
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);
    }
Esempio n. 4
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);
    }
        /// <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);
        }
Esempio n. 6
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();
        }
Esempio n. 7
0
        protected override void Update(GameTime gameTime)
        {
            Time.Update(gameTime);
            InputManager.Update();

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            if (InputManager.IsKeyPressed(Keys.Space))
            {
                search.Start = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)];
                search.End   = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)];

                while (!(search.Start = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
                {
                    ;
                }
                while (!(search.End = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
                {
                    ;
                }

                search.Search();
                path.Clear();
                AStarNode current = search.End;
                while (current != null)
                {
                    path.Insert(0, current.Position);
                    current = current.Parent;
                }
            }
            base.Update(gameTime);
        }
Esempio n. 8
0
        public void TestPathFinding()
        {
            Initialize("5x5");
            AStarSearch search = new AStarSearch(map);

            search.Search(new Location(0, 0), new Location(2, 2));
            search.PrintResult();
        }
    public static void WalkToDestination(Character selectedPlayer, Tile destinationTile)
    {
        Tile playerTile = Map.position[(int)selectedPlayer.transform.position.x, (int)selectedPlayer.transform.position.y];

        selectedPlayer.GetComponent <Character>().Move(AStarSearch.Search(playerTile, destinationTile));
        playerTile.content                  = null;
        destinationTile.content             = selectedPlayer;
        StateMachineController.currentState = States.characterWalking;
    }
Esempio n. 10
0
        IEnumerator FindPath()
        {
            var         graphMaker = FindObjectOfType <GraphMaker>();
            var         nodes      = graphMaker.nodes;
            var         edges      = graphMaker.edges;
            List <Node> bestPath   = new List <Node>();

            yield return(aStarSearch.StartCoroutine(aStarSearch.Search(nodes, edges, startNode, endNode, bestPath)));

            path       = bestPath;
            nextTarget = path[0];
            seekBehaviour.targetTransform = nextTarget.transform;
        }
Esempio n. 11
0
    static public PathInfo.PathRoute returnToFlag(Map.MapNode[,] grid, Vector3 playerPos, Vector3 ourFlag, PathInfo.PathRoute path, List <Map.MapNode> openList, List <Map.MapNode> closedList)
    {
        if (path.Index == path.PathSize)
        {
            float distToOurFlag = Vector2.Distance(playerPos, ourFlag);
            if (distToOurFlag > 1.0f)
            {
                path = AStarSearch.Search(grid, playerPos, ourFlag, path, openList, closedList);
            }
        }

        return(path);
    }
Esempio n. 12
0
        public ReturnedPath GetPath(Vector2D startNode, Vector2D endNode)
        {
            var indexStart = pathfinding.GetClosestNode(startNode);
            var indexEnd   = pathfinding.GetClosestNode(endNode);
            var aStar      = new AStarSearch();
            var path       = new ReturnedPath();

            if (aStar.Search(pathfinding, indexStart, indexEnd))
            {
                path = aStar.GetPath();
            }
            return(path);
        }
Esempio n. 13
0
    static public PathInfo.PathRoute Escort(Map.MapNode[,] grid, PathInfo.PathRoute path, Vector3 playerPos, GameObject personToEscort, Blackboard board, List <Map.MapNode> openList, List <Map.MapNode> closedList, Rigidbody rb)
    {
        //we will need to get the agents path and calculate where they might be by the time we can get to their position.


        if (path.Index == path.PathSize)
        {
            var       temp        = personToEscort.GetComponent <AI>().Path;
            Vector3[] EscortsPath = temp.PathList;
            int       pathSize    = temp.PathSize;

            Vector3 playerEscortPos = personToEscort.transform.position;
            float   dist            = Vector2.Distance(playerPos, playerEscortPos);
            float   halfDist        = dist / 2;

            int   bestIndex = 0;
            float tempDif   = Mathf.Abs(Vector2.Distance(playerPos, EscortsPath[0]) - halfDist);

            for (int i = 1; i < pathSize; i++)
            {
                float pathDist = Vector2.Distance(playerPos, EscortsPath[i]);
                float dif      = Mathf.Abs(pathDist - halfDist);
                if (dif < tempDif)
                {
                    bestIndex = i;
                    tempDif   = dif;
                }
            }

            if (dist < 3.0f)
            {
                var b = board.getBoard();
                b.seek = false;
                b.stop = true;
                board.setBoard(b);
            }
            else
            {
                var b = board.getBoard();
                b.seek = true;
                b.stop = false;
                board.setBoard(b);
                path = AStarSearch.Search(grid, playerPos, EscortsPath[bestIndex], path, openList, closedList);
            }
        }
        return(path);
    }
Esempio n. 14
0
        void FindRandomPath()
        {
            while (!(search.Start = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
            {
                ;
            }
            while (!(search.End = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
            {
                ;
            }
            search.Search();
            path.Clear();
            AStarNode current = search.End;

            while (current != null)
            {
                path.Insert(0, current.Position);
                current = current.Parent;
            }
        }
        public void ShouldFail()
        {
            var states = new Dictionary <string, DummyProblemState>
            {
                ["A"]        = new DummyProblemState(0, "A"),
                ["B from A"] = new DummyProblemState(2, "B"),
                ["E from A"] = new DummyProblemState(3, "E"),
                ["C from B"] = new DummyProblemState(4, "C"),
                ["D from C"] = new DummyProblemState(3, "D")
            };

            SetPaths(states);

            var problem = new DummyProblem(states["A"]);

            var astar = new AStarSearch <DummyProblemState>(new NoHeuristicFunction <DummyProblemState>());

            var result = astar.Search(problem).ToList();

            Assert.Empty(result);
        }
Esempio n. 16
0
    static public PathInfo.PathRoute NeedHealth(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 healthpack 'safest'
        {
            List <Vector3> healthPack      = new List <Vector3>();
            var            detectedObjects = GameObject.FindGameObjectsWithTag("HealthPack");

            foreach (var detectedObject in detectedObjects)
            {
                if (detectedObject.GetComponent <Renderer>().enabled == true) // need to make sure it's active
                {
                    healthPack.Add(detectedObject.transform.position);
                }
            }

            if (healthPack.Count == 0) //if one isnt avaiable. Go to one anyway once we have got there we'll recalculate to actually collect one
            {
                return(path = AStarSearch.Search(grid, playerPos, GameObject.Find("HealthPack").transform.position, path, openList, closedList));
            }

            int   bestHealthPack       = 0;
            float DistFromFlag         = 300.0f;
            float DistToNearestBox     = 300.0f;
            float tempDistFromFlag     = 0.0f;
            float tempDistToNearestBox = 0.0f;
            for (int i = 0; i < healthPack.Count; i++)
            {
                tempDistFromFlag     = Vector2.Distance(playerPos, ourFlag);
                tempDistToNearestBox = Vector2.Distance(playerPos, healthPack[i]);
                if ((tempDistFromFlag + tempDistToNearestBox) < (DistFromFlag + DistToNearestBox))
                {
                    DistFromFlag     = tempDistFromFlag;
                    DistToNearestBox = tempDistToNearestBox;
                    bestHealthPack   = i;
                }
            }
            path = AStarSearch.Search(grid, playerPos, healthPack[bestHealthPack], path, openList, closedList);
        }
        return(path);
    }
Esempio n. 17
0
    public Queue <Vector2> Search(Vector2 a, Vector2 b)
    {
        Location start = TerrainBoard.transformPositionToGrid(a);

        Location goal = TerrainBoard.transformPositionToGrid(b);

        SearchAlgorithm.Search(start, goal);

        Queue <Vector2> targets = new Queue <Vector2>();

        foreach (Location l in SearchAlgorithm.GetResult())
        {
            targets.Enqueue(TerrainBoard.transformGridToPosition(l.x, l.y));
        }
        return(targets);

        //TerrainBoard.ResetColor();
        //foreach (Location i in TerrainBoard.AStar.GetExploredList())
        //{
        //  TerrainBoard.SetColor(i.x,i.y,Color.red);
        //}
    }
Esempio n. 18
0
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            time.Update(gameTime);
            InputManager.Update();

            if (InputManager.IsKeyPressed(Keys.Space))
            {
                search = new AStarSearch(size, size);
                foreach (AStarNode node in search.Nodes)
                {
                    if (random.NextDouble() < 0.2)
                    {
                        search.Nodes[random.Next(size), random.Next(size)].Passable = false;
                    }
                }

                search.Start          = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)];
                search.Start.Passable = true;
                search.End            = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)];
                search.End.Passable   = true;

                search.Search();

                path = new List <Vector3>();
                AStarNode current = search.End;
                while (current != null)
                {
                    path.Insert(0, current.Position);
                    current = current.Parent;
                }
            }

            base.Update(gameTime);
        }
Esempio n. 19
0
        public void RandomPathFinding()
        {
            Random random = new Random();

            while (!(search.Start = search.Nodes[random.Next(search.Cols), random.Next(search.Rows)]).Passable)
            {
                ;
            }
            search.End = search.Nodes[search.Cols / 2, search.Rows / 2];
            search.Search();
            path = new List <Vector3>();
            AStarNode current = search.End;
            var       count   = 0;

            while (current != null)
            {
                path.Insert(0, current.Position);
                current = current.Parent;
            }

            count        = 0;
            currentIndex = 0;
        }
Esempio n. 20
0
        public override Intent Search(params Point[] prohibitedPoints)
        {
            //問題は、二回目以降の探索を行うときに起こる

            //Agent agent = new Agent();
            Field field = Game.Field.Clone(true, true, true);

            int    startTeam, startEnemy, beforeTeam, beforeEnemy, nextTeam, nextEnemy;
            int    needTurn;
            double delta;

            startTeam  = field.EvaluateMap(TeamEnum);
            startEnemy = field.EvaluateMap(EnemyEnum);

            //良いとされるルートを保持
            Node[] betterRoute = new Node[1];

            //敵の存在する確率を求めるクラスを保持
            var calculateExistenceProbability = new CalculateExistenceProbability(1);
            //Listで敵エージェントがそこに存在する確率を保持することで、オーバーヘッドを軽減
            List <double[, ]> agentsProbabilities = new List <double[, ]>();


            BetterRoute    = new Node[1];
            BetterRoute[0] = new Node();

            BetterEfficiency = double.MinValue;

            AStarSearch.Nodes.ForEach((r, n) =>
            {
                //エージェントの位置以外探索
                //おもすぎるので、相対位置が--の場合に変えるかも?

                if (n.Point != Agent.Position)
                {
                    AStarSearch.ResetResult();
                    AStarSearch.StartNode = AStarSearch.Nodes[Agent.Position.Y, Agent.Position.X];
                    AStarSearch.EndNodes  = new Node[] { n };

                    //禁止領域は予めクローズすることで対応
                    foreach (var p in prohibitedPoints)
                    {
                        AStarSearch.Nodes[p.Y, p.X].Status = NodeStatus.Closed;
                    }


                    //探索開始
                    AStarSearch.Search((c) =>
                    {
                        Point p = c.Point;
                        //まだ敵エージェントが存在する確率を計算していない
                        if (c.Turn >= agentsProbabilities.Count)
                        {
                            agentsProbabilities.Add(
                                calculateExistenceProbability.MapPossibilities(Enemy.Agent1.Position, Enemy.Agent2.Position, Game.Field.Width, Game.Field.Height, c.Turn)
                                );
                        }

                        //Score計算
                        ICell cell = Game.Field.GetCell(p);

                        //移動成功確率をセルに保持。移動成功確率は前の成功確率とこの移動ができる確率の積
                        c.SuccessProbability = (1.0 - agentsProbabilities[c.Turn - 1][p.Y, p.X]) * c.Parent.SuccessProbability;


                        //移動に伴うコストは、盤面の平均値とする
                        //要改善、失敗確率の累積を考えていない
                        //敵のタイル情報で場合分け
                        switch (cell.GetState(EnemyEnum))
                        {
                        case CellState.Occupied:
                            c.Turn++;     //敵のセルがある場合は、ターンが余計にかかるので、その分
                            agentsProbabilities.Add(
                                calculateExistenceProbability.MapPossibilities(Enemy.Agent1.Position, Enemy.Agent2.Position, Game.Field.Width, Game.Field.Height, c.Turn)
                                );
                            //2ターン必要ということで、成功確率も減る
                            c.SuccessProbability *= (1.0 - agentsProbabilities[c.Turn - 1][p.Y, p.X]);

                            return(16 - cell.Score * c.SuccessProbability + 2 * averageScore);

                        case CellState.InRegion:
                            return(16 - cell.Score * c.SuccessProbability + 1 * averageScore);
                        }
                        //自チームのタイル状況で場合分け
                        switch (cell.GetState(TeamEnum))
                        {
                        case CellState.None:
                            return(16 - cell.Score * c.SuccessProbability + 1 * averageScore);

                        case CellState.Occupied:
                            return(16 + 0 * c.SuccessProbability + 1 * averageScore);

                        case CellState.InRegion:
                            //取るとかえって損なセルがある
                            if (cell.Score >= 0)
                            {
                                return(16 + 0 * c.SuccessProbability + 1 * averageScore);
                            }
                            else
                            {
                                return(16 - cell.Score * c.SuccessProbability + 1 * averageScore);
                            }

                        default:
                            //ここに来ることはありえない
                            return(16 - cell.Score * c.SuccessProbability + 1 * averageScore);
                        }
                    }, (c) =>
                    {
                        //HeuristicScore計算
                        Point pos       = c.Point - Agent.Position;
                        double minSteps = Math.Max(Math.Abs(pos.X), Math.Abs(pos.Y));
                        return((int)((16 - averageScore + 1) * minSteps));
                    });

                    //実際に移動させてみて得点がどうなるかを見る
                    field = Game.Field.Clone(true, true, true);

                    field.AutoEvaluate = false;

                    nextTeam  = beforeTeam = startTeam;
                    nextEnemy = beforeEnemy = startEnemy;

                    needTurn = 0;
                    delta    = 0;

                    //一つづつチェック
                    foreach (var node1 in AStarSearch.BestWayNodes)
                    {
                        if (field.Map[node1.Point.Y, node1.Point.X].GetState(TeamEnum) != CellState.Occupied)
                        {
                            field.Map[node1.Point.Y, node1.Point.X].SetState(TeamEnum, CellState.Occupied);
                            //値の変化を見る
                            nextTeam = field.EvaluateMap(TeamEnum);
                        }
                        //相手に占有されていたらその分ターンが必要なので
                        if (field.Map[node1.Point.Y, node1.Point.X].GetState(EnemyEnum) == CellState.Occupied)
                        {
                            needTurn++;
                            field.Map[node1.Point.Y, node1.Point.X].SetState(EnemyEnum, CellState.None);
                            nextEnemy = field.EvaluateMap(EnemyEnum);
                        }



                        delta += ((nextTeam - beforeTeam) - (nextEnemy - beforeEnemy)) * node1.SuccessProbability;

                        beforeTeam  = nextTeam;
                        beforeEnemy = nextEnemy;

                        needTurn++;//必要ターン加算
                    }

                    //よりよい経路が見つかったら
                    if (BetterEfficiency < delta / needTurn)
                    {
                        betterRoute = AStarSearch.BestWayNodes.ToArray();
                        //最後のノードに推定能率を保持
                        BetterEfficiency = delta / needTurn;
                        NeedTurn         = needTurn;
                    }
                }
            });
            //結果を保存
            BetterRoute = betterRoute;

            //得られた結果をWayクラスに変換
            Way = new Way(Agent, BetterRoute.Select(node2 => node2.Point).ToArray());
            Point agentNextPos;

            //次を取り出す
            Way.Peep(out agentNextPos, out Direction direction);


            return(Game.GetIntent(Agent, direction));
        }
Esempio n. 21
0
 public int2[] GetPath(int2 start, int2 goal)
 {
     defaultGraph.SetGoal(goal);
     return(pathfinder.Search(start, goal));
 }
Esempio n. 22
0
        public void EightPuzzleTest()
        {
            // Number of trials to run
            int N = 100;

            // Maximum depth of the solution
            int dmax = 10;

            // Now we define the search algorithm and the type of node expansion.  Russell & Norvig discuss
            // two type of expansion strategies: tree search and graph search.  One will avoid cycles in the search
            // space and the other will not.
            //
            // They state that a tree search was used to generate Figure 4.8;
            var expander   = new InstrumentedNodeExpander <Direction, EightPuzzleBoard, EightPuzzleNode, IntegerCost>(new EightPuzzleNodeExpander());
            var treeSearch = new TreeSearch <Direction, EightPuzzleBoard, EightPuzzleNode, IntegerCost>(expander);

            var ids     = new IterativeDeepeningSearch <Direction, EightPuzzleBoard, EightPuzzleNode, IntegerCost>(treeSearch, dmax);
            var aStarH1 = new AStarSearch <Direction, EightPuzzleBoard, EightPuzzleNode, IntegerCost>(treeSearch, () => new QueueAdapter <EightPuzzleNode, IntegerCost>());
            var aStarH2 = new AStarSearch <Direction, EightPuzzleBoard, EightPuzzleNode, IntegerCost>(treeSearch, () => new QueueAdapter <EightPuzzleNode, IntegerCost>());

            // Depth runs from 0 to dmax
            int[,] d = new int[dmax + 1, 3];
            int[,] n = new int[dmax + 1, 3];

            for (int _d = 1; _d <= dmax; _d++)
            {
                for (int i = 0; i < N; i++)
                {
                    // Invoke the search on the problem with a particular starting state. Scramble creates a new instance
                    var initialState = EightPuzzleBoard.GOAL.Scramble(_d);

                    {
                        expander.ClearMetrics();
                        var solution = ids.Search(problem_none, new EightPuzzleBoard(initialState));
                        var depth    = solution.Count() - 1;

                        System.Diagnostics.Trace.WriteLine("IDS Solution has depth " + depth + " and expanded " + expander[IntrumentedParameters.NODES_EXPANDED] + " nodes");
                        d[depth, 0] += 1;
                        n[depth, 0] += expander[IntrumentedParameters.NODES_EXPANDED];
                    }

                    {
                        expander.ClearMetrics();
                        var solution = aStarH1.Search(problem_h1, new EightPuzzleBoard(initialState));
                        var depth    = solution.Count() - 1;

                        System.Diagnostics.Trace.WriteLine("A* (h1) Solution has depth " + depth + " nodes and expanded " + expander[IntrumentedParameters.NODES_EXPANDED] + " nodes");
                        d[depth, 1] += 1;
                        n[depth, 1] += expander[IntrumentedParameters.NODES_EXPANDED];

                        // PrintSolution(solution);
                    }

                    {
                        expander.ClearMetrics();
                        var solution = aStarH2.Search(problem_h2, new EightPuzzleBoard(initialState));
                        var depth    = solution.Count() - 1;

                        System.Diagnostics.Trace.WriteLine("A* (h2) Solution has depth " + depth + " nodes and expanded " + expander[IntrumentedParameters.NODES_EXPANDED] + " nodes");
                        d[depth, 2] += 1;
                        n[depth, 2] += expander[IntrumentedParameters.NODES_EXPANDED];

                        // PrintSolution(solution);
                    }
                }
            }
            Trace.WriteLine("|         Search Cost                Branching Factor       |");
            Trace.WriteLine("+--+---------+--------+--------++---------+--------+--------+");
            Trace.WriteLine("| d|   IDS   | A*(h1) | A*(h2) ||   IDS   | A*(h1) | A*(h2) |");
            Trace.WriteLine("+--+---------+--------+--------++---------+--------+--------+");

            for (int i = 1; i <= dmax; i++)
            {
                var bf0 = ComputeBranchingFactor((float)n[i, 0] / (float)d[i, 0], i);
                var bf1 = ComputeBranchingFactor((float)n[i, 1] / (float)d[i, 1], i);
                var bf2 = ComputeBranchingFactor((float)n[i, 2] / (float)d[i, 2], i);

                Trace.WriteLine(String.Format("|{0,2}|{1,-8} |{2,7} |{3,7} ||{4,8:0.00} |{5,7:0.00} |{6,7:0.00} |", i,
                                              n[i, 0] / Math.Max(d[i, 0], 1), n[i, 1] / Math.Max(d[i, 1], 1), n[i, 2] / Math.Max(d[i, 2], 1), bf0, bf1, bf2));
            }

            Trace.WriteLine("+--+---------+--------+--------++---------+--------+--------+");
        }
Esempio n. 23
0
    static public PathInfo.PathRoute findSafePosition(PathInfo.PathRoute path, Map.MapNode[,] grid, Vector3 position, Vector3 ourflag, List <Map.MapNode> openList, List <Map.MapNode> closedList, Rigidbody rb, bool goingToSafeSpot, GameObject Player, string TeamColour)
    {
        //for this behaviour we need to find a good position to hold

        //we need to do a raycast to each direction and see what is the furthest


        //float rayDistance = 0.0f;
        if (goingToSafeSpot == false)
        {
            if (path.Index == path.PathSize)
            {
                if (TeamColour == "Red")
                {
                    Vector3 safe = new Vector3(4.75f, -17.75f, -1.0f);
                    path = AStarSearch.Search(grid, Player.transform.position, safe, path, openList, closedList);
                }
                else if (TeamColour == "Blue")
                {
                    Vector3 safe = new Vector3(25.75f, -12.75f, -1.0f);
                    path = AStarSearch.Search(grid, Player.transform.position, safe, path, openList, closedList);
                }
                Player.GetComponent <AI>().AtSafeSpot = true;


                // Was going to try and raycast to the next safe location, but for a easy cheap fix just hardcoded the locations for now


                //Ray[] rays = new Ray[4];
                //rays[0] = new Ray(ourflag, Vector3.up * 30);
                //rays[1] = new Ray(ourflag, Vector3.left * 30);
                //rays[2] = new Ray(ourflag, Vector3.right * 30);
                //rays[3] = new Ray(ourflag, Vector3.down * 30);

                //Vector3[] direction = new Vector3[4];
                //direction[0] = (Vector3.up);
                //direction[1] = (Vector3.left);
                //direction[2] = (Vector3.right);
                //direction[3] = (Vector3.down);

                //RaycastHit hit;
                //Vector3 bestReyPos = new Vector3(0, 0, 0);
                //Vector3 bestDirection = new Vector3(0,0,0);
                //for (int i = 0; i < 4; i++)
                //{
                //    if (Physics.Raycast(rays[i], out hit))
                //    {
                //        if (hit.distance > rayDistance)
                //        {
                //            rayDistance = hit.distance;
                //            bestReyPos = hit.point;
                //            bestDirection = direction[i];
                //        }
                //    }
                //}

                ////once we have found the furthest away. Then we will check for the closest wall. This should be a nice corner to sit until the flag is back.



                //Debug.DrawLine(ourflag, bestReyPos - bestDirection, Color.red, 10.0f);

                //Vector3 flagToBestRay = bestReyPos;
                //float shortestDist = 1000.0f;

                //rays[0] = new Ray(bestReyPos, Vector3.up * 30);
                //rays[1] = new Ray(bestReyPos, Vector3.left * 30);
                //rays[2] = new Ray(bestReyPos, Vector3.right * 30);
                //rays[3] = new Ray(bestReyPos, Vector3.down * 30);
                //for (int i = 0; i < 4; i++)
                //{
                //    if (Physics.Raycast(rays[i], out hit))
                //    {
                //        if (hit.distance > 0.50f)
                //        {
                //            if (hit.distance < shortestDist)
                //            {
                //                shortestDist = hit.distance;
                //                bestReyPos = hit.point;
                //                bestDirection = direction[i];
                //               // Debug.DrawLine(flagToBestRay, bestReyPos, Color.black, 10.0f);
                //            }
                //        }
                //    }
                //}
                //Debug.DrawLine(flagToBestRay, bestReyPos, Color.red, 10.0f);

                //Vector3 dest = bestReyPos - bestDirection;
                //float dist = Vector3.Distance(position, bestReyPos);
                //if (dist >= 3.0f)
                //{
                //    path = AStarSearch.search(grid, position, dest, path, openList, closedList);
                //    Player.GetComponent<AI>().goingToSafeSpot = true;
                //}
            }
        }
        return(path);
    }
Esempio n. 24
0
    static public PathInfo.PathRoute CaptureFlag(Map.MapNode[,] grid, Vector3 position, Vector3 objPos, Vector3 ourFlag, PathInfo.PathRoute path, bool hasFlag, List <Map.MapNode> openList, List <Map.MapNode> closedList, string Team, Rigidbody rb, bool goingToSafeSpot, GameObject player)
    {
        if (hasFlag == false)
        {
            if (path.Index == path.PathSize)
            {
                float dist = Vector3.Distance(position, objPos); //has the flag already been taken, if so go back to base
                if (dist > 1.0f)
                {
                    path = AStarSearch.Search(grid, position, objPos, path, openList, closedList);
                }
                else
                {
                    path = returnToFlag(grid, position, ourFlag, path, openList, closedList);
                }
            }
        }

        else if (hasFlag == true) //if we have the flag we need to check if we are back at the flag and if we are then we need to find a nice position near where our flag and wait for it to be returned
        {
            if (goingToSafeSpot == false)
            {
                if (path.Index == path.PathSize)
                {
                    float distance = Vector2.Distance(position, ourFlag);
                    if (distance > 1.0f)
                    {
                        path = returnToFlag(grid, position, ourFlag, path, openList, closedList);
                    }

                    else // we are near our flag, is it there?
                    {
                        distance = Vector2.Distance(ourFlag, GameObject.Find(Team + "Flag").transform.position);
                        if (distance > 1.0f) //someone has our flag, so find a nice spot
                        {
                            if (goingToSafeSpot == false)
                            {
                                findSafePosition(path, grid, position, ourFlag, openList, closedList, rb, goingToSafeSpot, player, Team);
                            }
                        }
                    }
                }
            }
            else if (goingToSafeSpot)
            {
                float DistAgentAndSafePos;
                if (path.PathSize > 0)
                {
                    DistAgentAndSafePos = Vector3.Distance(position, path.PathList[path.PathSize - 1]); //dist agent and safe spot
                }

                else
                {
                    DistAgentAndSafePos = 0.001f;
                }                                      //temp fix so we dont get an index error
                if (DistAgentAndSafePos < 0.1f)
                {
                    DistAgentAndSafePos = Vector3.Distance(ourFlag, GameObject.Find(Team + "Flag").transform.position); //if we are in a safe location is our flag back
                    if (DistAgentAndSafePos < 0.1f)
                    {
                        player.GetComponent <AI>().AtSafeSpot = false;
                        var temp = player.GetComponent <AI>().Board.getBoard();
                        temp.seek = true;
                        player.GetComponent <AI>().Board.setBoard(temp);
                        player.GetComponent <AI>().resetPath();
                    }
                    else
                    {
                        Stop(rb);
                        var temp = player.GetComponent <AI>().Board.getBoard();
                        temp.seek = false;
                        player.GetComponent <AI>().Board.setBoard(temp);
                    }
                }
                else if (path.Index == path.PathSize)
                {
                    player.GetComponent <AI>().AtSafeSpot = false;
                    var temp = player.GetComponent <AI>().Board.getBoard();
                    temp.seek = true;
                    player.GetComponent <AI>().Board.setBoard(temp);
                    path = returnToFlag(grid, position, ourFlag, path, openList, closedList);
                }
            }
        }
        return(path);
    }
Esempio n. 25
0
 public void SearchForPathBetweenNodes()
 {
     Assert.IsTrue(aStar.Search(graph, 0, 2));
     Assert.IsTrue(aStar.Search(graph, 1, 5));
     Assert.IsFalse(aStar.Search(graph, 5, 2));
 }