def bfs_path(self, starting_room_id, check_func): adj = self.saved_rooms['adjacency'] queue = Queue() final_path = None visited = set() queue.enqueue([starting_room_id]) while queue.len() > 0: path = queue.dequeue() vert = path[-1] if vert not in visited: if check_func(vert): final_path = path break visited.add(vert) for room in adj[vert].values(): new_path = list(path) new_path.append(room) queue.enqueue(new_path) if final_path is None: return new_path = [] for idx, room in enumerate(final_path): if idx > 0: lastRoom = final_path[idx - 1] for direction in adj[lastRoom]: if adj[lastRoom][direction] == room: new_path.append({'dir': direction, 'next_room': room}) return new_path
def findShortestPath(adj): q = Queue() q.enqueue([player.current_room.id]) visited = set() while q.len() > 0: path = q.dequeue() vert = path[-1] if vert not in visited: if "?" in adj[vert].values(): return path visited.add(vert) for room in adj[vert].values(): new_path = list(path) new_path.append(room) q.enqueue(new_path) return None
def bfs_back(room, visited, token): q = Queue() q.enqueue([{"room": room, "direction": None}]) traversal_visited = set() while q.len() > 0: path = q.dequeue() current = path[-1]["room"] if current["room_id"] not in traversal_visited: traversal_visited.add(current["room_id"]) if "?" in visited[current["room_id"]]["directions"].values(): for element in path: if element["direction"]: move(element["direction"], token, element["room"]["room_id"]) return current for direction in current["exits"]: next_room = visited[ current["room_id"]]["directions"][direction] path_copy = path.copy() path_copy.append({"room": next_room, "direction": direction}) q.enqueue(path_copy)