Ejemplo n.º 1
0
        public List <NodeWithCost <Vector3Int> > FindPathFrom(Vector3Int fromTile, Vector3Int targetTile)
        {
            AStarSearch search = new AStarSearch(LevelManager.Instance.grid,
                                                 fromTile, targetTile);

            return(search.FindPath());
        }
Ejemplo n.º 2
0
        public IEnumerable <string> Transform(string start, string end, bool substitutionsOnly)
        {
            Validate.IsNotNullOrEmpty(start);
            Validate.IsNotNullOrEmpty(end);
            Validate.IsTrue(
                !substitutionsOnly || start.Length == end.Length,
                "When only substitutions are allowed, the start and end words must be the same length.");

            if (substitutionsOnly)
            {
                return(RestrictedGraphSearcher.FindPath(
                           start,
                           end,
                           word => EditDistance.CalculateHamming(word, end)
                           ));
            }
            else
            {
                return(FullGraphSearcher.FindPath(
                           start,
                           end,
                           word => EditDistance.CalculateLevenshtein(word, end)
                           ));
            }
        }
Ejemplo n.º 3
0
    void InitPath(bool fromStart)
    {
        if (navigationState == State.Searching)
        {
            return;
        }

        navigationState = State.Searching;

        Node[] allNodes = FindObjectsOfType <Node>();
        Debug.LogFormat("found {0} nodes", allNodes.Length);

        Node firstNode = (fromStart)? GetFirstNode(allNodes) : GetClosestNode(allNodes, transform.position);

        Debug.Log("firstNode: " + firstNode.gameObject.name);

        Node targetNode = GetLastNode(allNodes);

        Debug.Log("target: " + targetNode.gameObject.name);

        //set neighbor nodes for all nodes
        foreach (Node node in allNodes)
        {
            node.FindNeighbors(maxDistance);
        }

        //get path from A* algorithm
        path = AStar.FindPath(firstNode, targetNode);

        if (path == null)
        {
            //increase search distance for neighbors
            Debug.Log("Increasing search distance: " + maxDistance);
            maxDistance    += .1f;
            navigationState = State.Idle;
            InitPath(fromStart);
            return;
        }

        //set next nodes
        for (int i = 0; i < path.Count - 1; i++)
        {
            path[i].NextInList = path[i + 1];
        }

        path[0].Activate(true);
        navigationState = State.Completed;
    }
Ejemplo n.º 4
0
    private void UpdateHoveredTile(Tile tile)
    {
        if (hoveredTile)
        {
            SelectionStatusHandler vH = hoveredTile.GetComponent <SelectionStatusHandler>();
            vH.ChangeSelectionStatus(Tile.SelectionStatus.Default);
        }
        hoveredTile = tile;
        // This event gets picked up by the visual handlers of hovered tile and
        // sets its tile visibility


        // Update Highlight Area
        if (highlightArea.Count > 0)
        {
            foreach (var item in highlightArea)
            {
                SelectionStatusHandler vH = item.GetComponent <SelectionStatusHandler>();
                vH.ChangeSelectionStatus(Tile.SelectionStatus.Highlighted);
            }
            foreach (var item in neighbours)
            {
                SelectionStatusHandler vH = item.GetComponent <SelectionStatusHandler>();
                vH.ChangeSelectionStatus(Tile.SelectionStatus.Hovered);
            }
            if (highlightArea.Contains(hoveredTile))
            {
                //_aStar.
                var search = new AStarSearch(_grid, currentSelected[0].GetComponent <Unit>().currTile.index, hoveredTile.index);
                movePath = search.FindPath();
                // Then Update Path
                if (movePath.Count > 0)
                {
                    foreach (var item in movePath)
                    {
                        Tile _t = _grid.TileAt(item);
                        SelectionStatusHandler vH = _t.GetComponent <SelectionStatusHandler>();
                        vH.ChangeSelectionStatus(Tile.SelectionStatus.Path);
                    }
                }
            }
        }
        SelectionStatusHandler vHnew = hoveredTile.GetComponent <SelectionStatusHandler>();

        vHnew.ChangeSelectionStatus(Tile.SelectionStatus.Hovered);
    }
Ejemplo n.º 5
0
 protected override void Start()
 {
     animator                = GetComponent <Animator>();
     r2                      = GetComponent <Rigidbody2D>();
     r2.gravityScale         = 0;
     r2.rotation             = 0;
     ScoreScipt1.scoreValue1 = 0;
     wall                    = GameObject.FindGameObjectsWithTag("Wall");
     floor                   = GameObject.FindGameObjectsWithTag("Floor");
     fire                    = GameObject.FindGameObjectsWithTag("Fire");
     this.createCost();
     graph = new SquareGrid(1, 1, 14, 14, costObject);
     initMap();
     axe    = GameObject.FindGameObjectWithTag("Axe");
     start  = new Location(transform.position.x, transform.position.y);
     goal   = new Location(axe.transform.position.x, axe.transform.position.y);
     astar  = new AStarSearch(graph, start, goal, costObject);
     path   = astar.FindPath();
     deltaT = 1.0f * astar.dem / 80;
     base.Start();
 }
Ejemplo n.º 6
0
    private void Update()
    {
        if (flag == true)
        {
            if (flag2 == true)
            {
                flag2 = false;
                axe   = GameObject.FindGameObjectWithTag("Axe");
                fire  = GameObject.FindGameObjectsWithTag("Fire");
                start = new Location(transform.position.x, transform.position.y);
                goal  = new Location(axe.transform.position.x, axe.transform.position.y);
                this.createCost();
                graph = new SquareGrid(1, 1, 14, 14, costObject);
                astar = new AStarSearch(graph, start, goal, costObject);
                path  = astar.FindPath();
                i     = 0;
            }
            time += Time.deltaTime;
            if (time > deltaT)
            {
                Tick();
                time  = 0;
                flag2 = true;
            }
        }
        if (flag == false)
        {
            axe = GameObject.FindGameObjectWithTag("Axe");
            if (axe == null)
            {
                fire = GameObject.FindGameObjectsWithTag("Fire");
                initMap();
                Instantiate(item, RandomPosition(), Quaternion.identity);
            }

            flag  = true;
            flag2 = true;
        }
    }
Ejemplo n.º 7
0
 // Update is called once per frame
 void Update()
 {
     if ((!esperando) && (!finJuego))
     {
         comprobarVictoria();
         StartCoroutine(comprobarVida());
         if (seleccionado)
         {
             buscarNuevoTarget();
         }
         StartCoroutine(detectarObjetivo());
         if (!quieto)
         {
             if (!cambio)
             {
                 if (!llego)
                 {
                     if (patrulla)
                     {
                         detectarEnemigoPatrulla();
                         if (pausarPatrulla)  //Ha detectado a alguien, va a por él
                         {
                             if ((nodoActual == null) || (target.position != targetPosicion))
                             {
                                 path = controlador.FindPath(transform.position, target.position, mapaCostes);//Find a path to the target
                                 if (path.Count > 0)
                                 {
                                     nodoActual     = path[0];
                                     numeroCamino   = 0;
                                     camino         = true;
                                     targetPosicion = target.position;
                                 }
                                 else
                                 {
                                     camino = false;
                                 }
                             }
                             if (camino)
                             {
                                 //Ahora nos movemos por el camino
                                 Nodo actual = controlador.GridReference.NodeFromWorldPoint(transform.position);
                                 if (actual == nodoActual) //Avanzo al siguiente nodo del camino
                                 {
                                     numeroCamino++;
                                     if (numeroCamino == path.Count)
                                     {
                                         //Quedate quieto porque has llegado al final del camino
                                         transform.position = transform.position;
                                         llego = true;
                                         //Debug.Log(actitud);
                                         StartCoroutine(buscarNuevoObjetivo());
                                     }
                                     else
                                     {
                                         nodoActual = path[numeroCamino];
                                     }
                                 }
                                 if (numeroCamino < path.Count)
                                 {
                                     //Muevete al siguiente nodo
                                     Vector3 direccion = nodoActual.vPosition - transform.position;
                                     direccion.Normalize();
                                     //Debug.Log(transform.position + " " + direccion + " " + mapaCostes[nodoActual.iGridX, nodoActual.iGridY]);
                                     transform.position = transform.position + direccion * vel * Time.deltaTime / mapaCostes[nodoActual.iGridX, nodoActual.iGridY];
                                 }
                             }
                         }
                         else  //No ha detectado a nadie, patrulla
                         {
                             if (nodoActual == null) //Inicio de la patrulla
                             {
                                 //Debug.Log("kwd " + name);
                                 path = controlador.FindPath(transform.position, caminoPatrulla[numCaminoPatrulla].vPosition, mapaCostes);//Find a path to the target
                                 if (path.Count > 0)
                                 {
                                     nodoActual     = path[0];
                                     numeroCamino   = 0;
                                     camino         = true;
                                     targetPosicion = caminoPatrulla[numCaminoPatrulla].vPosition;
                                 }
                                 else
                                 {
                                     camino = false;
                                 }
                             }
                             if (camino)
                             {
                                 //Ahora nos movemos por el camino
                                 Nodo actual = controlador.GridReference.NodeFromWorldPoint(transform.position);
                                 if (actual == nodoActual) //Avanzo al siguiente nodo del camino
                                 {
                                     numeroCamino++;
                                     if (numeroCamino == path.Count)
                                     {
                                         //Quedate quieto porque has llegado al final del camino
                                         transform.position = transform.position;
                                         nodoActual         = null;
                                         numCaminoPatrulla++;
                                         if (numCaminoPatrulla == caminoPatrulla.Length)
                                         {
                                             numCaminoPatrulla = 0;                                             //Si he llegado al final, repetimos
                                         }
                                     }
                                     else
                                     {
                                         nodoActual = path[numeroCamino];
                                     }
                                 }
                                 if (numeroCamino < path.Count)
                                 {
                                     //Muevete al siguiente nodo
                                     Vector3 direccion = nodoActual.vPosition - transform.position;
                                     direccion.Normalize();
                                     //Debug.Log(transform.position + " " + direccion + " " + mapaCostes[nodoActual.iGridX, nodoActual.iGridY]);
                                     transform.position = transform.position + direccion * vel * Time.deltaTime / mapaCostes[nodoActual.iGridX, nodoActual.iGridY];
                                 }
                             }
                         }
                     }
                     else
                     {
                         if ((nodoActual == null) || (target.position != targetPosicion))
                         {
                             path = controlador.FindPath(transform.position, target.position, mapaCostes);//Find a path to the target
                             if (path.Count > 0)
                             {
                                 nodoActual     = path[0];
                                 numeroCamino   = 0;
                                 camino         = true;
                                 targetPosicion = target.position;
                             }
                             else
                             {
                                 camino = false;
                             }
                         }
                         if (camino)
                         {
                             //Ahora nos movemos por el camino
                             Nodo actual = controlador.GridReference.NodeFromWorldPoint(transform.position);
                             if (actual == nodoActual) //Avanzo al siguiente nodo del camino
                             {
                                 numeroCamino++;
                                 if (numeroCamino == path.Count)
                                 {
                                     //Quedate quieto porque has llegado al final del camino
                                     transform.position = transform.position;
                                     llego = true;
                                     //Debug.Log(actitud);
                                     StartCoroutine(buscarNuevoObjetivo());
                                 }
                                 else
                                 {
                                     nodoActual = path[numeroCamino];
                                 }
                             }
                             if (numeroCamino < path.Count)
                             {
                                 //Muevete al siguiente nodo
                                 Vector3 direccion = nodoActual.vPosition - transform.position;
                                 direccion.Normalize();
                                 //Debug.Log(transform.position + " " + direccion + " " + mapaCostes[nodoActual.iGridX, nodoActual.iGridY]);
                                 transform.position = transform.position + direccion * vel * Time.deltaTime / mapaCostes[nodoActual.iGridX, nodoActual.iGridY];
                             }
                         }
                     }
                 }
             }
             else
             {
                 nodoActual = null;
                 Nodo n = controlador.GridReference.NodeFromWorldPoint(transform.position);
                 tagZona = controlador.getTagNodo(n);
                 cambio  = false;
                 llego   = false;
                 camino  = false;
             }
         }
     }
 }
Ejemplo n.º 8
0
        public JobStep[] GetJobStepsFromJob(Job job, Actor actor)
        {
            if (job == null)
            {
                return(null);
            }

            Func <Location, Placeable, IEnumerable <JobStep> > buildpath = (from, to) =>
            {
                var destset = new HashSet <AStarNode>();
                for (int x = (int)to.Location.X; x < to.Location.X + to.Size.Width; ++x)
                {
                    for (int y = (int)to.Location.Y; y < to.Location.Y + to.Size.Height; ++y)
                    {
                        destset.Add(new AStarNode(new Location(x, y)));
                    }
                }

                var path = AStarSearch.FindPath(
                    new AStarNode(from),
                    destset,
                    (n1, n2) => Location.Distance(n1.Location, n2.Location),
                    n => Location.Distance(n.Location, new Location(job.Target.Location.X + job.Target.Size.Width / 2, job.Target.Location.Y + job.Target.Size.Height / 2)));

                return(path.Select((n, i) => new JobStep(n.Location, JobType.StepMove, null))
                       .SkipWhile(w => job.Target.ContainsPoint(w.Location))                                 // skip anything inside the target, stop just outside
                       .Reverse().Skip(1));                                                                  // reverse since the path returned is from the resource to us, then skip the actor's location (first path item)
            };

            if (job.Type == JobType.Harvest || job.Type == JobType.DropResources || job.Type == JobType.EnterWorkplace)
            {
                return(buildpath(actor.Location, job.Target)
                       .Concat(new JobStep(job.Target.Location, job.Type, job.Target).ToEnumerable())    // after we get to the target, queue an action step (harvest, drop, etc)
                       .ToArray());
            }
            else if (job.Type == JobType.FeedProduction)
            {
                var b = (Building)job.Target;

                // find the closest storage that contains stuff the production building needs
                // we know there is one or we wouldn't have gotten here
                var closeststorage = PlarfGame.Instance.World.Placeables.OfType <Building>()
                                     .Where(w => w.Function == BuildingFunction.Storage && w.Resources.ContainsAny(b.ProductionChain.Inputs))
                                     .OrderBy(w => w.Location.Distance(actor.Location))
                                     .First();

                // and build the path, actor->storage--(retrieve)-->prod--(prod)-->done
                var tostorage = buildpath(actor.Location, closeststorage).ToArray();
                var toprod    = buildpath(tostorage.Last().Location, b);
                return(tostorage
                       .Concat(new JobStep(closeststorage.Location, JobType.StepRetrieveResources, closeststorage, b.ProductionChain.Inputs.Intersect(closeststorage.Resources)).ToEnumerable())
                       .Concat(toprod)
                       .Concat(new JobStep(b.Location, JobType.DropResources, b).ToEnumerable())
                       .ToArray());
            }
            else if (job.Type == JobType.Production)
            {
                return new[] { new JobStep(JobType.Production) }
            }
            ;                                                                                               // simply start the production step

            throw new InvalidOperationException();
        }
    }