Esempio n. 1
0
 public GameField(byte[,] theArray, bool diagonalAllowed)
 {
     _currentField = theArray;
     _diagonal = diagonalAllowed;
     _astarSolver = new AStarSolver<GameField>(diagonalAllowed, AStarHeuristicType.ExperimentalSearch, this,
         theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);
 }
Esempio n. 2
0
 public GameField(byte[,] theArray, bool diagonalAllowed)
 {
     currentField = theArray;
     diagonal = diagonalAllowed;
     this._newEntries = new Queue<GametileUpdate>();
     astarSolver = new AStarSolver<GameField>(diagonalAllowed, AStarHeuristicType.EXPERIMENTAL_SEARCH, this, theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);
 }
Esempio n. 3
0
        public GameField(byte[,] theArray, bool diagonalAllowed)
        {
            this.currentField = theArray;
            this.diagonal = diagonalAllowed;
            this.astarSolver = new AStarSolver<GameField>(diagonalAllowed, AStarHeuristicType.EXPERIMENTAL_SEARCH, this, theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);

        }
Esempio n. 4
0
 public GameField(byte[,] theArray, bool diagonalAllowed)
 {
     _currentField = theArray;
     _diagonal     = diagonalAllowed;
     _astarSolver  = new AStarSolver <GameField>(diagonalAllowed, AStarHeuristicType.ExperimentalSearch, this,
                                                 theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);
 }
Esempio n. 5
0
        private static void CheckResultsOptimality()
        {
            int iterations              = 4;
            int optimalBfsLenghtCount   = 0;
            int optimalAStarLenghtCount = 0;

            var pathLengthCalculator = new PathLengthCalculator();

            Parallel.For(0, iterations, _ =>
            {
                Board board = new RandomBoardGenerator().Generate(Board.FinalBoard, 1000);

                var bfsResult     = new BfsSolver().Solve(board);
                var aStarResult   = new AStarSolver().Solve(board);
                var optimalResult = new AStarWithoutLoopsSolver().Solve(board);

                int bfsResultLenght     = pathLengthCalculator.CalculatePathLenght(bfsResult.FinalState);
                int aStarResultLenght   = pathLengthCalculator.CalculatePathLenght(aStarResult.FinalState);
                int optimalResultLenght = pathLengthCalculator.CalculatePathLenght(optimalResult.FinalState);

                if (bfsResultLenght == optimalResultLenght)
                {
                    Interlocked.Increment(ref optimalBfsLenghtCount);
                }

                if (aStarResultLenght == optimalResultLenght)
                {
                    Interlocked.Increment(ref optimalAStarLenghtCount);
                }
            });

            Console.WriteLine($"Iterations: {iterations}");
            Console.WriteLine($"Optimal results from BFS: {optimalBfsLenghtCount}");
            Console.WriteLine($"Optimal results from AStar: {optimalAStarLenghtCount}");
        }
Esempio n. 6
0
 public GameField(byte[,] theArray, bool diagonalAllowed)
 {
     _currentField = theArray;
     _diagonal     = diagonalAllowed;
     _newEntries   = new Queue <FieldUpdate>();
     _astarSolver  = new AStarSolver <GameField>(diagonalAllowed, AStarHeuristicType.EXPERIMENTAL_SEARCH, this, theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);
 }
Esempio n. 7
0
    void Awake()
    {
        aS = GameObject.Find("SoundManager").GetComponent <AudioSource>();
        StartCoroutine(fadeOut());
        manoMapa.gameObject.SetActive(false);
        manoPath.gameObject.SetActive(false);
        manoCombustible.gameObject.SetActive(false);
        foreach (GameObject go in cartelesTutorial)
        {
            go.gameObject.SetActive(false);
        }
        indTutorial = 0;

        nivel = GameObject.Find("Nivel").gameObject;

        //Se inicializan los atributos para el A*
        mapa = new int[alto, ancho];
        int it = 0;

        for (int i = 0; i < alto; i++)
        {
            for (int j = 0; j < ancho; j++)
            {
                if (nivel.transform.GetChild(it).gameObject.layer == 8)
                {
                    mapa[i, j] = 20;
                }
                else
                {
                    mapa[i, j] = 1;
                }
                it++;
            }
        }
        //Descomentar para escribir el mapa por consola.
        #region EscribirMapa

        /*
         * string s = "";
         * for(int i = 0; i< alto; i++)
         * {
         *   for(int j = 0; j < ancho; j++)
         *   {
         *       s += mapa[i, j].ToString() + " ";
         *   }
         *   //Debug.Log(s);
         *   s += "\n";
         * }
         * Debug.Log(s);
         */
        #endregion

        solver = new AStarSolver(ancho, alto);                                      //Se inicializa el solver.
        solver.ActualizaMapa(mapa);
        meta.x = Mathf.FloorToInt(metaO.transform.position.x); meta.y = Mathf.FloorToInt(-metaO.transform.position.y);
    }
Esempio n. 8
0
    private IEnumerator AnimateSolution()
    {
        Edge[] path  = null;
        int    Found = 1;

        while (!done)
        {
            path = AStarSolver.Solve(g, currentNode, matrix[xEnd, yEnd], myHeuristics[(int)heuristicToUse]);
            // check if there is a solution
            if (path.Length == 0)
            {
                EndButton.SetActive(true);
                EndButton.GetComponentInChildren <Text>().text = "Sorry, No solution left\nScore: " + Score.text;
                done = true;
            }
            else
            {
                delay = Found * (startingDelay / acceleration) * (path[0].weight - heightLevels + 5) / 2;
                yield return(new WaitForSeconds(delay));

                if (!blockList.Contains(path[0].to))
                {
                    Found      = 1;
                    Score.text = "" + (int.Parse(Score.text) + 1);
                    totalPath.Add(path[0]);
                    OutlinePath(totalPath.ToArray(), trackMaterial, trackMaterial, npcMaterial);
                    currentNode = path[0].to;
                }
                else
                {
                    Found = 0;
                }

                if (path[0].to == matrix[xEnd, yEnd])
                {
                    EndButton.SetActive(true);
                    EndButton.GetComponentInChildren <Text>().text = "Sorry, End of the Run\nScore: " + Score.text;
                    done = true;
                }
                else if (boostList.Contains(path[0].to))
                {
                    StartCoroutine(ChangeOfSpeedCoroutine(1, 1.6f));
                    boostList.Remove(path[0].to);
                }
                else if (freezeList.Contains(path[0].to))
                {
                    StartCoroutine(ChangeOfSpeedCoroutine(2, 1 / 1.6f));
                    freezeList.Remove(path[0].to);
                }
            }
        }
    }
        public static void Main()
        {
            var arr = new int[3, 3] {
                { 0, 5, 6 }, { 3, 7, 1 }, { 2, 8, 4 }
            };

            var board = new Board(arr);

            Console.WriteLine("solving 8 tile puzzle:\n");

            var startingState = new State(board, null, null, 0);

            var astar = new AStarSolver();

            astar.Solve(startingState);


            Console.ReadLine();
        }
Esempio n. 10
0
        private static float SortDistance(
            Unit unit,
            int[,] map,
            Point currentDestination,
            float sortDistance,
            ref List <Point> route)
        {
            List <Point> currentRoute = AStarSolver.FindPath(
                map,
                unit.Position,
                currentDestination);

            // Будем искать первую точку, ближайшую к назначению.
            if (currentRoute != null && sortDistance >
                currentDestination.GetDistanceTo(unit.Destination.Value))
            {
                route        = currentRoute;
                sortDistance = currentDestination.GetDistanceTo(unit.Destination.Value);
            }

            return(sortDistance);
        }
Esempio n. 11
0
        private List <Point> GetNearestRoute(Unit unit)
        {
            int[,] map = GetWorldMap(unit);

            List <Point> route = AStarSolver.FindPath(
                map,
                unit.Position,
                unit.Destination.Value);

            int   levelAround  = 1;
            float sortDistance = float.MaxValue;

            while (route == null && levelAround < _worldSize)
            {
                int levelSide = (levelAround * 2 + 1);

                Point startPoint = unit.Destination.Value - new Point(levelAround, levelAround);
                for (int i = 0; i < levelSide; i++)
                {
                    Point currentDestination = new Point(startPoint.X + i, startPoint.Y);
                    sortDistance = SortDistance(unit, map, currentDestination, sortDistance, ref route);

                    currentDestination = new Point(startPoint.X + i, startPoint.Y + levelSide - 1);
                    sortDistance       = SortDistance(unit, map, currentDestination, sortDistance, ref route);

                    currentDestination = new Point(startPoint.X, startPoint.Y + i);
                    sortDistance       = SortDistance(unit, map, currentDestination, sortDistance, ref route);

                    currentDestination = new Point(startPoint.X + levelSide - 1, startPoint.Y + i);
                    sortDistance       = SortDistance(unit, map, currentDestination, sortDistance, ref route);
                }

                levelAround++;
            }

            return(route);
        }
Esempio n. 12
0
 public GameField(byte[,] theArray, bool diagonalAllowed)
 {
     currentField = theArray;
     diagonal     = diagonalAllowed;
     astarSolver  = new AStarSolver <GameField>(diagonalAllowed, AStarHeuristicType.EXPERIMENTAL_SEARCH, this, theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);
 }
Esempio n. 13
0
    /// <summary>
    /// Uses the A* algorithm to find a route from start to end.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="start"></param>
    /// <param name="end"></param>
    /// <param name="GetHScore"></param>
    /// <param name="GetWScore"></param>
    /// <param name="GetAdjacent"></param>
    /// <returns></returns>
    public static IEnumerable <T> FindRoute <T>(T start, T end, Func <T, T, float> GetHScore, Func <T, T, float> GetWScore, Func <T, IEnumerable <T> > GetAdjacent) where T : class
    {
        AStarSolver <T> solver = new AStarSolver <T>(GetHScore, GetWScore, GetAdjacent);

        return(solver.Solve(start, end));
    }
Esempio n. 14
0
        public List <AStarNodeSimpleBehaviour> FindPathTo(AStarNodeSimpleBehaviour goal)
        {
            List <IAStarNode <AStarNodeSimpleBehaviour> > result = AStarSolver <AStarNodeSimpleBehaviour> .SolveSimple(this, goal);

            return(result.ConvertAll(o => (AStarNodeSimpleBehaviour)o));
        }
Esempio n. 15
0
 public void FindPathTo(AStarNodeSimpleBehaviour goal, List <IAStarNode <AStarNodeSimpleBehaviour> > result)
 {
     AStarSolver <AStarNodeSimpleBehaviour> .SolveSimple(this, goal, result);
 }
Esempio n. 16
0
 public RoomBattleBallGameField(GameTeam[,] theArray)
 {
     this.currentField = theArray;
     this.astarSolver  = new AStarSolver <RoomBattleBallGameField>(true, AStarHeuristicType.EXPERIMENTAL_SEARCH, this, theArray.GetUpperBound(1) + 1, theArray.GetUpperBound(0) + 1);
 }
Esempio n. 17
0
    private IEnumerator AnimateSolution()
    {
        Edge[] path  = null;
        int    count = 0;

        while (!done)
        {
            if (path != null && (count < path.Length || path.Length == 0))
            {
                Debug.Log(currentNode.description);
                if (path.Length == 0)
                {
                    Debug.Log("Lunghezza zero");
                    EndButton.SetActive(true);
                    EndButton.GetComponentInChildren <Text>().text = "Enemy stuck!\nScore: " + Score.text;
                    Cursor.visible = true;
                    done           = true;
                }
                else
                {
                    delay         = startingDelay * ((path[count].weight - heightLevels + 1) / (1 + acceleration)) / 1.5f;
                    acceleration *= 1.1f;
                    Debug.Log("Nuovo nodo");

                    if (path[count].to == matrix[xEnd, yEnd])
                    {
                        if (Vector3.Distance(startMaterial.transform.position, endMaterial.transform.position) < 3f && endMaterial.GetComponent <CharacterController>().moving)
                        {
                            endMaterial.GetComponent <Rigidbody>().AddForce(new Vector3((endMaterial.transform.position - startMaterial.transform.position).normalized.x, .5f, (endMaterial.transform.position - startMaterial.transform.position).normalized.z) * 50);
                            Score.text = "" + 0;
                            StartCoroutine(playerStopMoving());
                        }
                        yield return(new WaitForSeconds(delay));

                        sawTheEnd = true;
                        path      = null;
                    }

                    else if (boostList.Contains(path[count].to))
                    {
                        StartCoroutine(ChangeOfSpeedCoroutine(1, 1.6f));
                        boostList.Remove(path[count].to);
                    }
                    else if (freezeList.Contains(path[count].to))
                    {
                        StartCoroutine(ChangeOfSpeedCoroutine(2, 1 / 1.6f));
                        freezeList.Remove(path[count].to);
                    }

                    if (path != null && !blockList.Contains(path[count].to) && path[count].to != matrix[xEnd, yEnd])
                    {
                        totalPath.Add(path[count]);
                        previousNode = currentNode;
                        currentNode  = path[count].to;
                        timeElapsed  = 0;
                        Debug.Log(isHit(currentNode, matrix[xEnd, yEnd]));
                        nodeDiscover();
                        if (isPlayerOnSight())
                        {
                            Debug.Log("vedo player");

                            RobotLight.color = Color.red;
                            lastEndPosition  = matrix[xEnd, yEnd];
                            if (currEndPosition == null || Vector3.Distance(getNodePosition(currEndPosition), getNodePosition(lastEndPosition)) > .07f)
                            {
                                sawTheEnd = true;
                                path      = null;
                            }
                        }
                        else if (currEndPosition != null)
                        {
                            path = null;
                        }
                        yield return(new WaitForSeconds(delay));
                    }
                    path = checkPath(path);

                    count++;
                }
                Score.text = "" + (int.Parse(Score.text) + 1);
            }
            else if (isPlayerOnSight() || sawTheEnd)
            {
                //removeNodeFromBlockList(currentNode);
                //removeNodeFromBlockList(matrix[xEnd, yEnd]);
                currEndPosition = matrix[xEnd, yEnd];
                lastEndPosition = matrix[xEnd, yEnd];
                sawTheEnd       = false;
                Debug.Log("vado a prendere il player in pos:" + currEndPosition.x + " " + currEndPosition.y + " mi trovo in pos " + currentNode.x + " " + currentNode.y);
                path = null;
                if (currentNode.x != currEndPosition.x || currentNode.y != currEndPosition.y)
                {
                    path = AStarSolver.Solve(g, currentNode, currEndPosition, myHeuristics[(int)Heuristics.Sight]);
                }
                else
                {
                    yield return(new WaitForSeconds(delay));
                }
                if (path != null)
                {
                    Debug.Log("il percorso è lungo " + path.Length);
                }

                RobotLight.color = Color.red;
                count            = 0;
                Debug.DrawRay(getNodePosition(currentNode) + Vector3.up, getNodePosition(matrix[xEnd, yEnd]) - getNodePosition(currentNode), Color.white, 20);
            }
            else
            {
                Debug.Log("vado a prendere un punto a caso o vicino al giocatore (se visto)");

                Node target;
                if (currEndPosition != null)
                {
                    lastEndPosition = matrix[xEnd, yEnd];
                }
                currEndPosition = null;
                //removeNodeFromBlockList(target);
                //removeNodeFromBlockList(currentNode);
                RobotLight.color = originaNpcColor;
                if (currentNode != matrix[xEnd, yEnd])
                {
                    target = bestNodeinSight();
                    if (target != null)
                    {
                        path = AStarSolver.Solve(g, currentNode, target, myHeuristics[(int)Heuristics.Sight]);
                    }
                }

                else
                {
                    yield return(new WaitForSeconds(.1f));
                }
                yield return(new WaitForSeconds(.1f));

                count = 0;
            }
        }
    }
Esempio n. 18
0
 public void CreateNewSolver(AStarPathNode[,] grid)
 {
     currentSolver = new AStarSolver <AStarPathNode, object>(grid);
 }