void relax(Vector2Int origen, Vector2Int direccion) { Vector2Int destino = origen + direccion; if (!(destino.x < 0 || destino.y < 0 || destino.x >= mapa.getAncho() || destino.y >= mapa.getAlto())) { if (agent.GetTILE_INFO(destino.y, destino.x)._Terreno != Tile.T_Terreno.T_DESCONOCIDO || destino == UltimaCasilla) { if (DistTo[destino.y, destino.x] > DistTo[origen.y, origen.x] + 1) { DistTo[destino.y, destino.x] = DistTo[origen.y, origen.x] + 1; EdgeTo[destino.y, destino.x] = origen; int h = heuristic(destino, UltimaCasilla); if (h != 0) { h += DistTo[destino.y, destino.x]; } else { h = 0; } PQ.Enqueue(destino, h); } } } }
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); } }
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; }
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 }
void relax(Vector2Int origen, Vector2Int direccion) { Vector2Int destino = origen + direccion; if (!(destino.x < 0 || destino.y < 0 || destino.x >= mapa.getAncho() || destino.y >= mapa.getAlto())) { if (!mapa.getOccupied(destino.y, destino.x)) { if (DistTo[destino.y, destino.x] > DistTo[origen.y, origen.x] + mapa.getCostOfTile(destino.y, destino.x)) { DistTo[destino.y, destino.x] = DistTo[origen.y, origen.x] + mapa.getCostOfTile(destino.y, destino.x); EdgeTo[destino.y, destino.x] = origen; int h = heuristic(destino, UltimaCasilla); if (h != 0) { h += DistTo[destino.y, destino.x]; } PQ.Enqueue(destino, h); } } } }
private void Update() { if (musicPlaying) { if (!MusicSource.isPlaying) { musicLooper(); } // check if we've reached the next beat in the queue beatDeltatime += Time.deltaTime; if (getBeatDeltaTime() > nextBeat) { // hit beat, fire and setup next one beat(); if (beatQueue.Count > 0) { nextBeat = beatQueue.Dequeue(); } else { // if we reached the end, just reset the beat delta time and start over beatDeltatime = 0; nextBeat = 0; // don't forget to re-write the queue string jsonString = LoadResourceTextfile("beatmap_stage_music_slow"); currentBeatmap = JsonUtility.FromJson <BeatMap>(jsonString); for (int i = 0; i < currentBeatmap.beatmap.Length; i++) { beatQueue.Enqueue(currentBeatmap.beatmap[i], currentBeatmap.beatmap[i]); } } } } }
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); }
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); }
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); }