예제 #1
0
    /// <summary>
    /// Calculates the path.
    /// </summary>
    /// <param name="g">The g.</param>
    /// <returns>the path is possible</returns>
    public bool CalculatePath(GameObject g)
    {
        to = g.transform.localPosition;
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();
        UltimaCasilla = new Vector2Int((int)to.x, (int)to.y);
        PQ            = new Priority_Queue.SimplePriorityQueue <Vector2Int, int>();
        DistTo        = mapa.getDistTo((int)transform.localPosition.y, (int)transform.localPosition.x);
        EdgeTo        = new Vector2Int[mapa.altoMapa, mapa.anchoMapa];
        for (int i = 0; i < mapa.altoMapa; i++)
        {
            for (int j = 0; j < mapa.anchoMapa; j++)
            {
                EdgeTo[i, j].x = -1;
                EdgeTo[i, j].y = -1;
            }
        }
        Vector2Int from = new Vector2Int((int)transform.localPosition.x, (int)transform.localPosition.y);

        mapa.setOccupied(from.y, from.x, true);
        PQ.EnqueueWithoutDuplicates(from, 0);
        caminoPosible = false;


        int k = 0;

        while (PQ.Count > 0 && !caminoPosible)
        {
            k++;
            Vector2Int top = PQ.Dequeue();
            if (top != UltimaCasilla)
            {
                for (int i = 0; i < directions.Length; i++)
                {
                    relax(top, directions[i]);
                }
            }
            else
            {
                caminoPosible = true;
            }
        }
        stopwatch.Stop();
        if (caminoPosible)
        {
            GetComponent <Unidad>().SetPath(GetPath(ref UltimaCasilla, ref from));
        }
        GameManager.instance.updateDiagnostico(caminoPosible);
        GameManager.instance.updateDiagnostico(k, stopwatch.Elapsed.TotalMilliseconds, stopwatch.ElapsedTicks);


        return(caminoPosible);
    }
예제 #2
0
    public bool CalculatePath(Vector2Int casilla)
    {
        bestOption = new Vector2Int(-1, -1);
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();
        UltimaCasilla = new Vector2Int((int)casilla.x, (int)casilla.y);
        PQ            = new Priority_Queue.SimplePriorityQueue <Vector2Int, int>();
        Vector2Int from = new Vector2Int((int)transform.localPosition.x, (int)transform.localPosition.y);

        DistTo = mapa.getDistTo(from.y, from.x);
        EdgeTo = new Vector2Int[mapa.altoMapa, mapa.anchoMapa];
        for (int i = 0; i < mapa.altoMapa; i++)
        {
            for (int j = 0; j < mapa.anchoMapa; j++)
            {
                EdgeTo[i, j] = new Vector2Int(-1, -1);
            }
        }
        PQ.EnqueueWithoutDuplicates(from, 0);
        caminoPosible = false;


        int k = 0;

        while (PQ.Count > 0)
        {
            k++;
            Vector2Int top = PQ.Dequeue();
            if (top != UltimaCasilla)
            {
                for (int i = 0; i < directions.Length; i++)
                {
                    relax(top, directions[i]);
                }
            }
            else
            {
                caminoPosible = true;
            }
        }
        stopwatch.Stop();
        if (caminoPosible)
        {
            GetComponent <Agente>().setPath(GetPath(ref UltimaCasilla, ref from));
        }



        return(caminoPosible);
    }
예제 #3
0
    private void StartEventPlayback()
    {
        // write the beatmap
        string jsonString = LoadResourceTextfile(playbackTitle);

        currentEventMap = JsonUtility.FromJson <EventMap>(jsonString);

        // build up the selection registers
        SelectionRegister[] registers = currentEventMap.selectionRegisters;

        for (int h = 0; h < registers.Length; h++)
        {
            selectionRegister.Add(registers[h].name, registers[h].selections);
        }

        // use the beatmap to generate the beat queue, apply offset if there is one
        eventQueue = new Priority_Queue.SimplePriorityQueue <int>(); // make an empty queue
                                                                     // enqueue all the beats

        globalOffsetMs = currentEventMap.offset;

        for (int i = 0; i < currentEventMap.eventMap.Length; i++)
        {
            eventQueue.Enqueue(currentEventMap.eventMap[i].index + globalOffsetMs, currentEventMap.eventMap[i].index + globalOffsetMs);
            // create event hash table for efficiency
            eventsTable.Add(currentEventMap.eventMap[i].index + globalOffsetMs, currentEventMap.eventMap[i]);
        }


        // reset beat delta time
        eventDeltaTime = 0;
        nextEvent      = eventQueue.Dequeue();

        if (debug && startAtMs > 0)
        {
            // set audio start time
            float startTimeSec = startAtMs / 1000;
            clip.time = eventDeltaTime = startTimeSec;
        }

        // start audio
        clip.Play();

        playingEvents = true;
    }
예제 #4
0
    public Stack <Vector2Int> CalculatePath(Vector2Int casilla)
    {
        UltimaCasilla = new Vector2Int((int)casilla.x, (int)casilla.y);
        PQ            = new Priority_Queue.SimplePriorityQueue <Vector2Int, int>();
        Vector2Int from = new Vector2Int((int)transform.localPosition.x, (int)transform.localPosition.y);

        DistTo = mapa.getDistTo(from.y, from.x);
        EdgeTo = new Vector2Int[mapa.altoMapa, mapa.anchoMapa];
        for (int i = 0; i < mapa.altoMapa; i++)
        {
            for (int j = 0; j < mapa.anchoMapa; j++)
            {
                EdgeTo[i, j] = new Vector2Int(-1, -1);
            }
        }
        PQ.EnqueueWithoutDuplicates(from, 0);
        caminoPosible = false;


        int k = 0;

        while (PQ.Count > 0)
        {
            k++;
            Vector2Int top = PQ.Dequeue();
            if (top != UltimaCasilla)
            {
                for (int i = 0; i < directions.Length; i++)
                {
                    relax(top, directions[i]);
                }
            }
            else
            {
                caminoPosible = true;
            }
        }



        return(GetPath(ref UltimaCasilla, ref from));
    }
예제 #5
0
        public static void RunExample()
        {
            //First, we create the priority queue.
            SimplePriorityQueue <string> priorityQueue = new SimplePriorityQueue <string>();

            //Now, let's add them all to the queue (in some arbitrary order)!
            priorityQueue.Enqueue("Наков-1998", 0);
            priorityQueue.Enqueue("Уирт-1980", 1);


            //Change one of the string's priority to 2.  Since this string is already in the priority queue, we call UpdatePriority() to do this
            priorityQueue.UpdatePriority("Наков-1998", 2);

            //Finally, we'll dequeue all the strings and print them out
            while (priorityQueue.Count != 0)
            {
                string nextUser = priorityQueue.Dequeue();
                Console.WriteLine(nextUser);
            }
        }
예제 #6
0
    private void startBeat()
    {
        // write the beatmap
        string jsonString = LoadResourceTextfile(musicClip);

        currentBeatmap = JsonUtility.FromJson <BeatMap>(jsonString);

        // use the beatmap to generate the beat queue, apply offset if there is one
        beatQueue = new Priority_Queue.SimplePriorityQueue <int>(); // make an empty queue
        // enqueue all the beats
        for (int i = 0; i < currentBeatmap.beatmap.Length; i++)
        {
            beatQueue.Enqueue(currentBeatmap.beatmap[i] + currentBeatmap.offset, currentBeatmap.beatmap[i] + currentBeatmap.offset);
        }

        // reset beat delta time
        beatDeltatime = 0;
        nextBeat      = 0;

        musicPlaying = true; // this starts the update incrementing delta time
    }
예제 #7
0
    IEnumerator GetPathCoro(Coordinate start, Coordinate end)
    {
        List <Coordinate> visited = new List <Coordinate>();

        if (Target)
        {
            Priority_Queue.SimplePriorityQueue <Coordinate> queue = new Priority_Queue.SimplePriorityQueue <Coordinate>();
            if (start == null)
            {
                start = prev_start_coord;
            }
            if (start != null)
            {
                start.parent = null;
            }
            if (end == null)
            {
                end = prev_end_coord;
            }
            if (start == null || end == null)
            {
                yield break;
            }
            float tstart = Time.realtimeSinceStartup;
            prev_start_coord = start;
            prev_end_coord   = end;
            queue.Enqueue(start, GetCoordinateDistFromTarget(start));
            while (Path == null)
            {
                start = queue.Dequeue();
                if (start == end)
                {
                    /*  Debug.Log(Time.realtimeSinceStartup - tstart + " seconds : " +
                     *     queue.Count + " end routes considered : " +
                     *     start.GetNumParents() + " parents.");              */
                    Path = start;
                    yield break;
                }
                if (Time.realtimeSinceStartup > tstart + .01f || index != go_index)
                {
                    yield return(new WaitForEndOfFrame());

                    tstart = Time.realtimeSinceStartup;
                }
                int safe_layer = ptr.gameObject.layer;
                foreach (Coordinate coord in start.GetChildren())
                {
                    coord.traverse_cost = GetCoordinateDistFromTarget(coord);
                    if (!visited.Contains(coord))
                    {
                        coord.parent = start;
                        queue.Enqueue(coord, coord.GetTotalCost(safe_layer, can_dodge));
                        visited.Add(coord);
                    }
                    else if (queue.Contains(coord) && coord.GetTotalCost(safe_layer, can_dodge, 0, start) < queue.GetPriority(coord))
                    {
                        coord.parent = start;
                        queue.UpdatePriority(coord, coord.GetTotalCost(safe_layer, can_dodge));
                    }
                }
                if (queue.Count != 0)
                {
                    start = queue.First;
                }
                else
                {
                    break;
                }
            }
        }
        yield return(null);
    }
예제 #8
0
    List <Vector3> FindPathMonteCarlo()
    {
        /*
         * Please configure the random generation of configurations before calling this function (or you can use FindPath instead).
         * ALGO:
         * We draw a point:
         * - If it connects two connected components together, we keep it
         * - If it is not reachable from any previous configuration, we keep it
         * - Otherwise we ignore it
         * - We can also accept a point that do not respect any of the conditions after a certain number of consecutive rejections
         * We update the connected components (union find) and eventually the dico for memoisation
         * We stop when the initial config and the final one are in the same connected component
         * We retrieve the configurations of this connected component and we search a path with it (we can use a dico for memoisation)
         */
        Dictionary <Link, float> dico       = new Dictionary <Link, float>();
        UnionFind <Vector3>      components = new UnionFind <Vector3>();
        List <Vector3>           pts        = new List <Vector3>();

        pts.Add(ConfigInfos.initialConf);
        components.MakeSet(pts[0]);
        pts.Add(ConfigInfos.finalConf);
        components.MakeSet(pts[1]);
        if (phy.moveAllowed(false, pts[0], pts[1]))
        {
            dico.Add(new Link(pts[0], pts[1]), distanceBetweenConf(pts[0], pts[1]));
            Debug.DrawLine(CarController.spatialCoordOfConfiguration(pts[0]), CarController.spatialCoordOfConfiguration(pts[1]), Color.red, 5f);
            components.UnionValues(pts[0], pts[1]);
        }

        int i = 0;
        int cons_rejections = 0;
        Dictionary <Vector3, bool> tmp_dico = new Dictionary <Vector3, bool>();

        while (components.Find(pts[0]).value != components.Find(pts[1]).value || i < minPointsMonteCarlo)
        {
            if (i >= maxPointsMonteCarlo)
            {
                return(null);
            }

            Vector3 pt = DrawConfiguration();
            if (!phy.configurationInCollision(pt))
            {
                bool reachable = false;
                HashSet <Vector3> components_linked = new HashSet <Vector3>();
                foreach (Vector3 v in pts)
                {
                    if (components_linked.Contains(components.Find(v).value))
                    {
                        continue;
                    }
                    bool linked = phy.moveAllowed(false, v, pt);
                    tmp_dico[v] = linked;
                    if (linked)
                    {
                        reachable = true;
                        components_linked.Add(components.Find(v).value);
                    }
                }
                if (!reachable || components_linked.Count >= 2 || cons_rejections >= maxConsecutiveRejections)
                {
                    cons_rejections = 0;
                    foreach (Vector3 v in pts)
                    {
                        bool linked = false;
                        try
                        {
                            linked = tmp_dico[v];
                        }
                        catch
                        {
                            linked = phy.moveAllowed(false, v, pt);
                        }
                        if (linked)
                        {
                            Debug.DrawLine(CarController.spatialCoordOfConfiguration(v), CarController.spatialCoordOfConfiguration(pt), Color.red, 5f);
                            dico[new Link(v, pt)] = distanceBetweenConf(v, pt);
                        }
                    }
                    pts.Add(pt);
                    components.MakeSet(pt);
                    foreach (Vector3 v in components_linked)
                    {
                        components.UnionValues(pt, v);
                    }
                }
                else
                {
                    cons_rejections++;
                }
                tmp_dico.Clear();
                i++;
            }
        }

        // Searching a path with Dijkstra in the connected component of the initial config...
        Vector3 component = components.Find(ConfigInfos.initialConf).value;

        pts.RemoveAll((v => components.Find(v).value != component));
        Priority_Queue.SimplePriorityQueue <Vector3> vertices = new Priority_Queue.SimplePriorityQueue <Vector3>();
        foreach (Vector3 pt in pts)
        {
            if (pt == ConfigInfos.initialConf)
            {
                vertices.Enqueue(pt, 0);
            }
            else
            {
                vertices.Enqueue(pt, Mathf.Infinity);
            }
        }

        Dictionary <Vector3, Vector3> paths = new Dictionary <Vector3, Vector3>();
        float   current_w = vertices.GetPriority(vertices.First);
        Vector3 current   = vertices.Dequeue();

        while (current != ConfigInfos.finalConf)
        {
            foreach (Vector3 v in vertices)
            {
                float w     = GetMemoisedValue(dico, v, current);
                float new_w = w + current_w;
                if (new_w < vertices.GetPriority(v))
                {
                    vertices.UpdatePriority(v, new_w);
                    paths[v] = current;
                }
            }
            current_w = vertices.GetPriority(vertices.First);
            current   = vertices.Dequeue();
        }

        List <Vector3> result = new List <Vector3>();

        result.Add(ConfigInfos.finalConf);
        current = ConfigInfos.finalConf;
        while (current != ConfigInfos.initialConf)
        {
            current = paths[current];
            result.Add(current);
        }
        result.Reverse();
        return(result);
    }
예제 #9
0
    public bool GetPath(Vector2Int start, Vector2Int destination, out Vector2Int[] path)
    {
        Priority_Queue.SimplePriorityQueue <Vector2Int> open = new Priority_Queue.SimplePriorityQueue <Vector2Int>();
        Dictionary <Vector2Int, bool> closed   = new Dictionary <Vector2Int, bool>();
        Dictionary <Vector2Int, Step> allSteps = new Dictionary <Vector2Int, Step>();

        Step startStep = new Step(start, 0, null);

        allSteps.Add(startStep.Location, startStep);
        open.Enqueue(startStep.Location, 0);

        Step       currentStep;
        Vector2Int currentLocation;
        Step       neighborStep;

        // While lowest rank in OPEN is not the GOAL:
        while (open.Count > 0)
        {
            // Set current = remove lowest rank item from OPEN
            currentLocation = open.Dequeue();
            if (!allSteps.TryGetValue(currentLocation, out currentStep))
            {
                throw new Exception("Could not find expected step");
            }
            if (currentLocation == destination)
            {
                // Reconstruct reverse path from goal to start by following parent pointers
                path = GetPoints(currentStep);
                return(true);
            }
            // Add current to CLOSED
            closed.Add(currentLocation, true);

            // For neighbors of current:
            foreach (Vector2Int m in movements)
            {
                bool       inOpen;
                bool       inClosed;
                int        nextCost     = currentStep.Cost + 1;
                Vector2Int nextLocation = currentLocation + m;
                Step       nextStep     = new Step(nextLocation, nextCost, currentStep);

                if (!IsPossibleMove(currentLocation, nextLocation))
                {
                    // Spot is bad.
                    continue;
                }

                // If neighbor in OPEN and cost less than g(neighbor):
                // remove neighbor from OPEN, because new path is better
                if (open.Contains(nextLocation))
                {
                    if (!allSteps.TryGetValue(nextLocation, out neighborStep))
                    {
                        throw new Exception("Could not find expected step");
                    }
                    if (nextCost < neighborStep.Cost)
                    {
                        open.Remove(nextLocation);
                        allSteps.Remove(nextLocation);
                        inOpen = false;
                    }
                    else
                    {
                        inOpen = true;
                    }
                }
                else
                {
                    inOpen = false;
                }

                // If neighbor in CLOSED and cost less than g(neighbor):
                // remove neighbor from CLOSED
                if (closed.ContainsKey(nextLocation))
                {
                    if (!allSteps.TryGetValue(nextLocation, out neighborStep))
                    {
                        throw new Exception("Could not find expected step");
                    }
                    if (nextCost < neighborStep.Cost)
                    {
                        closed.Remove(nextLocation);
                        inClosed = false;
                    }
                    else
                    {
                        inClosed = true;
                    }
                }
                else
                {
                    inClosed = false;
                }

                // If neighbor not in OPEN and neighbor not in CLOSED:
                if (!inOpen && !inClosed)
                {
                    int h = Heuristic(nextLocation, destination);
                    neighborStep = new Step(nextLocation, nextCost, currentStep);
                    allSteps.Add(nextLocation, neighborStep);
                    open.Enqueue(nextLocation, nextCost + h);
                }
            }
        }
        path = null;
        return(false);
    }