def traverse(): graph = Graph() visited = set() test_path = list() mapped_rooms = graph.dft( player.current_room ) # maps out the graph connecting each room with its neighbors rooms = [ room for room in mapped_rooms ] # a list of all rooms in the order in which they were added to the stack while len(visited) < len(room_graph) - 1: path = graph.bfs( rooms[0], rooms[1] ) # As long as there's rooms to visit, we take the shortest path between the first two rooms while len( path ) > 1: # While there is at least two rooms in the shortest path we check if the adjacent_room is a neighbor of the current_room and if it is we append the direction value to the adjacent_room current_room = path[0] adjacent_room = path[1] if adjacent_room in mapped_rooms[current_room]: test_path.append(mapped_rooms[current_room][adjacent_room]) path.remove(current_room) rooms.remove( rooms[0] ) # Removes the room you checked and ads it to the visited so that you can keep checking each room through the list visited.add(rooms[0]) return test_path
def earliest_ancestor(ancestors, starting_node): """ given the dataset and the ID of an individual in the dataset, returns their earliest known ancestor – the one at the farthest distance from the input individual. If there is more than one ancestor tied for "earliest", return the one with the lowest numeric ID. If the input individual has no parents, the function should return -1. """ # Instantiate graph, count and way to track final vertex graph = Graph() final_v = 0 total_counter = 0 # for people in ancestors # add vertex and edge for people in ancestors: graph.add_vertex(people[0]) graph.add_vertex(people[1]) for people in ancestors: graph.add_edge(people[1], people[0]) # Instantiate Stack() to hold nodes to visit to_visit = Stack() to_visit.push(starting_node) # set to hold visited visited = set() # if not ancestors return -1 # no ancestors means no neighbors so it must be own ancestor # -1 for being your own ancestor ... lol hillbilly - I am my own grandpa if len(graph.get_neighbors(starting_node)) == 0: return -1 count = 0 # so long as we have vertex to visit start popping while to_visit.size() > 0: vertex = to_visit.pop() if len(graph.get_neighbors(vertex)) == 0: if count > total_counter: total_counter = count final_v = vertex if count == total_counter: if vertex < final_v: final_v = vertex if vertex not in visited: visited.add(vertex) if len(graph.get_neighbors(vertex)) != 0: for next_v in graph.get_neighbors(vertex): to_visit.push(next_v) count += 1 else: if to_visit.size() == 0: return final_v
def __init__(self, input_file): super(PRM, self).__init__(input_file) self.input_file = input_file self.gPrm = Graph() self.collision_checkList = {} self.gDict = {} self.visitedCollide = {} gPoints = self.get_grapple_points() # for i in range(self.num_grapple_points): self.gDict[gPoints[0]] = Graph()
def check_weight_update(weight_file, topo_file, nbrs): global curr_table global label global t_start print "Checking for Topology Changes" path = './' + label + '/weights' update = Graph() update.init_config(label, weight_file, topo_file) lock.acquire() if curr_table.serialize != update.serialize: curr_table.serialize = copy.deepcopy(update.serialize) print "Topology update detected. Rerouting..." update.bellman_on_src(label) curr_table.routes[label] = copy.deepcopy(update.routes[label]) curr_table.set_routes(copy.deepcopy(update.get_routes())) curr_table.hops[label] = copy.deepcopy(update.hops[label]) curr_table.set_hops(copy.deepcopy(update.get_hops())) curr_table.start = datetime.now() curr_table.bellman_on_src(label) print curr_table.get_routes() send_to_nbrs(nbrs) lock.release() threading.Timer( period, check_weight_update, [weight_file, topo_file, nbrs]).start() # Trigger Periodic Check
def getWinningStates(self, activePlayer): winningStates = [] #WINNING STATE 1 (2 Vertices) a1 = Vertex("a", activePlayer) b1 = Vertex("b", 1 - activePlayer) e1 = Edge(a1, b1) V1 = {a1, b1} E1 = {e1} winningState1 = Graph(V1, E1) winningStates.append(winningState1) #WINNING STATE 2 (3 Vertices) a2 = Vertex("a", activePlayer) b2 = Vertex("b", activePlayer) c2 = Vertex("c", 1 - activePlayer) e1 = Edge(a2, b2) e2 = Edge(a2, c2) V2 = {a2, b2, c2} E2 = {e1, e2} winningState2 = Graph(V2, E2) winningStates.append(winningState2) #WINNING STATE 3 (4 Vertices) a4 = Vertex("a", activePlayer) b4 = Vertex("b", activePlayer) c4 = Vertex("c", 1 - activePlayer) d4 = Vertex("d", 1 - activePlayer) e1 = Edge(a4, b4) e2 = Edge(a4, c4) e3 = Edge(a4, d4) e4 = Edge(c4, d4) e5 = Edge(b4, c4) V4 = {a4, b4, c4, d4} E3 = {e1, e2, e3} winningState3 = Graph(V4, E3) winningStates.append(winningState3) #ADD ON 3 E4 = {e1, e2, e3, e4} winningStates.append(Graph(V4, E4)) E5 = {e1, e2, e3, e4, e5} winningStates.append(Graph(V4, E5)) #WINNING STATE 3 return winningStates
def BinomialRandomGraph(k, p): v = {Vertex(i) for i in range(2 * k)} e = { Edge(a, b) for (a, b) in itertools.combinations(v, 2) if random.random() < p } return Graph(v, e)
def shortest_path(source, target): """ Returns the shortest list of (movie_id, person_id) pairs that connect the source to the target. If no possible path, returns None. """ frontier = QueueFrontier() node = Node(source, None, None) frontier.add(node) nodes_explored = [] edges = dict() print("Calculating...") while True: if frontier.empty(): graph = Graph(edges, []) graph.draw_graph("my_graph.png") return None node = frontier.remove() node_person_name = people[node.get_person_id()]["name"] if node.get_person_id() == target: path = [] path_name_labels = [people[source]["name"]] while node.get_parent() is not None: path.append([node.get_movie_id(), node.get_person_id()]) path_name_labels.append(people[node.get_person_id()]["name"]) node = node.get_parent() path.reverse() graph = Graph(edges, path_name_labels) graph.draw_graph("output_graph.png") return path else: nodes_explored.append(node.get_person_id()) for movie_id, person_id in neighbors_for_person(node.get_person_id()): child = Node(person_id, node, movie_id) child_person_name = people[child.get_person_id()]["name"] movie_name = movies[child.get_movie_id()]["title"] if(node_person_name != child_person_name): edges[(node_person_name, child_person_name)] = movie_name if not frontier.contains_state(person_id) and person_id not in nodes_explored: frontier.add(child)
def getLosingStates(self, activePlayer): losingStates = [] #LOSING STATE 1 a1 = Vertex("a", activePlayer) b1 = Vertex("b", activePlayer) c1 = Vertex("c", 1 - activePlayer) d1 = Vertex("d", 1 - activePlayer) e1 = Edge(a1, b1) e2 = Edge(b1, c1) e3 = Edge(c1, d1) V1 = {a1, b1, c1, d1} E1 = {e1, e2, e3} losingState1 = Graph(V1, E1) losingStates.append(losingState1) #LOSING STATE 2 a1 = Vertex("a", activePlayer) b1 = Vertex("b", 1 - activePlayer) c1 = Vertex("c", activePlayer) e1 = Edge(a1, b1) e2 = Edge(b1, c1) V1 = {a1, b1, c1} E1 = {e1, e2} losingState2 = Graph(V1, E1) losingStates.append(losingState2) #LOSING STATE 3 (4 Vertices) a3 = Vertex("a", 1 - activePlayer) b3 = Vertex("b", 1 - activePlayer) c3 = Vertex("c", activePlayer) d3 = Vertex("d", activePlayer) e1 = Edge(a3, b3) e2 = Edge(a3, c3) e3 = Edge(a3, d3) e4 = Edge(c3, d3) e5 = Edge(b3, d3) V4 = {a3, b3, c3, d3} E3 = {e1, e2, e3} losingState3 = Graph(V4, E3) losingStates.append(losingState3) #ADD ON E4 = {e1, e2, e3, e4} losingStates.append(Graph(V4, E4)) E3a = {e1, e2, Edge(b3, d3)} losingStates.append(Graph(V4, E3a)) E5 = {e1, e4} losingStates.append(Graph(V4, E5)) E6 = {e2, e5} losingStates.append(Graph(V4, E5)) #LOSING STATE 5 return losingStates
def play(): # create an array of visited rooms to keep track of visited = set() graph = Graph() # the path we take in that one run of the game trav_path = [] # using dfs to find the rooms - find all rooms on possible branch d_rooms = graph.dfs(player.current_room) # returns and array of the rooms in d_rooms rooms = [d_room for d_room in d_rooms] # while total visited is less than the total rooms in graph of world - 1 while (len(visited) < len(room_graph) - 1): # current room is the first room in the rooms array curr_room = rooms[0] # the next traverse will be to the next item in the rooms array next_room = rooms[1] # use a bfs to find the shortest path to destination - explores all the neighbour nodes shortest = graph.bfs(curr_room, next_room) # loop through shortest until nothing left while len(shortest) > 1: # find the neighbours curr_room_nays = d_rooms[shortest[0]] # next traverse will be to the next item in shortest array next_room = shortest[1] # if the next room (in the shortest path) exists in the current neighbours of curr room if next_room in curr_room_nays: trav_path.append(curr_room_nays[next_room]) # remove the first room from the queue shortest.remove(shortest[0]) # remove the current room from the total rooms rooms.remove(curr_room) # pop it on to the visited rooms array visited.add(curr_room) return trav_path
def set_init_graph(weight_file, topo_file): global curr_table global label path = './' + label + '/weights' g = Graph() g.init_config(label, weight_file, topo_file) g.bellman_on_src(label) curr_table = g print "Initial Table:\n" + str(curr_table.get_routes())
def earliest_ancestor(ancestors, starting_node): graph = Graph() # Add vertices for i in ancestors: if i[0] not in graph.vertices: graph.add_vertex(i[0]) if i[1] not in graph.vertices: graph.add_vertex(i[1]) # Add edges for i in ancestors: graph.add_edge(i[1], i[0]) path = graph.bft(starting_node) oldest = path[-1] if starting_node == oldest: return -1 else: return oldest
def earliest_ancestor(ancestors, starting_node): graph = Graph() for parent, child in ancestors: vertices = graph.vertices if parent not in vertices: graph.add_vertex(parent) if child not in vertices: graph.add_vertex(child) graph.add_edge(child, parent) s = Stack() s.push([starting_node]) longest = [starting_node] visited = set() oldest = -1 while s.size() > 0: path = s.pop() curr = path[-1] # breakpoint() if (len(path) > len(longest)) or (len(path) == len(longest) and curr < oldest): longest = path oldest = longest[-1] if curr not in visited: visited.add(curr) parents = graph.get_neighbors(curr) for parent in parents: new_path = path + [parent] s.push(new_path) return oldest
def earliest_ancestor(ancestors, starting_node): ancestor_tree = Graph() # Iterate through ancestors for (parent, child) in ancestors: # Add vertices to ancestor_tree ancestor_tree.add_vertex(parent) ancestor_tree.add_vertex(child) # print("ancestor tree", ancestor_tree.vertices) for (parent, child) in ancestors: # Add edges ancestor_tree.add_edge(child, parent) # print("neighbors", ancestor_tree.get_neighbors(5)) # print("ancestor tree", ancestor_tree.vertices) longest_path = 1 # Keep track of # ancestors; highest means most ancestors earliest_ancestor = 0 # Store last node (as an integer) for i in ancestor_tree.vertices: # print("i", i) # Print vertices # Call dfs function from Graph class path = ancestor_tree.dfs( i, starting_node) # i is each vertex/node in graph # print("ancestor dfs", ancestor_tree.dfs(starting_node, i)) print('path', path) if path: # If there are items in list if len( path ) > longest_path: # If list length is greater than longest path longest_path = len( path) # Set longest path equal to list length earliest_ancestor = i # Set earliest_ancestor equal to current node/vertex elif not path and longest_path == 1: # If path is 'None' and 'longest_path' is our default of 1 earliest_ancestor = -1 print("earliest ancestor", earliest_ancestor) return earliest_ancestor
def earliest_ancestor(ancestors, starting_node): ancestorTree = Graph() # Iterate through ancestors to find vertices # for (parent,child) in ancestors for ancestor in ancestors: for vert in ancestor: ancestorTree.add_vertex(vert) # print("Tree", ancestorTree.vertices) for ancestor in ancestors: ancestorTree.add_edge(ancestor[1], ancestor[0]) # print("Tree", ancestorTree.vertices) # default length to check the length of path list against longest_path = 1 # counter for storing storing the last node last_node = 0 # passing the vertices by reference ancestor_vert = ancestorTree.vertices # Iterate through the vertices of the ancestorTree for i in ancestor_vert: # i = individual nodes/vertices added using add_vert() # returns a list of nodes and sets the list to the variable path path = ancestorTree.dfs(starting_node, i) # print("path list loop", path) # If path is not = to None and the length of the path list in greater that longest_path which defaults to the value integer 1 if path is not None and len(path) > longest_path: # set longest_path = length of the path longest_path = len(path) print("longest_path", longest_path) # last node is = to last node/vertice of the longest_path last_node = i print("last_node", last_node) # I was missing that longest_path defaults to 1. # If path list is empty and longest_path is set to default of 1 elif not path and longest_path == 1: # print("empty", path) # print("elif path", longest_path) # set last_node to -1 last_node = -1 # print("Out of for loop", last_node) return last_node
def earliest_ancestor(ancestors, current_vertex): # create blank graph for ancestors current_graph = Graph() # loop through and add all ancestors for ancestor in ancestors: current_graph.add_vertex(ancestor[0]) current_graph.add_vertex(ancestor[1]) # loop through and add all edges for ancestor in ancestors: current_graph.add_edge(ancestor[1], ancestor[0]) max_path = 1 # if the input has no parents return -1 earliest_ancestor = -1 # create blank traversing path traversing_path = Stack() # Start traversing path with the first vertex traversing_path.push([current_vertex]) # while traversing path not empty while traversing_path.size() > 0: # start traversed path traversed_path = traversing_path.pop() # get last vertex in the traversed path last_vertex = traversed_path[-1] # get length of traversed path tp_length = len(traversed_path) # (if traversed path is longer than or equal to max_path AND # if last vertex is smaller than current earliest ancestor ) # ##### OR # if traversed path is longer than max_path if (tp_length >= max_path and last_vertex < earliest_ancestor) or (tp_length > max_path): # set earliest ancestor as last vertex # set max path as last item in traversed path earliest_ancestor = last_vertex max_path = len(traversed_path) # get neighbors of last vertex neighbors = current_graph.vertices[last_vertex] # loop through each neighbor for neighbor in neighbors: # get current path list, append neighbor to it, and add to traversing path new_path = list(traversed_path) new_path.append(neighbor) traversing_path.push(new_path) # return earliest ancestor return earliest_ancestor
def earliest_ancestor(ancestors, starting_node): ''' Build the graph ''' # instantiate a new graph object graph = Graph() # loop over all pairs in ancestors for pair in ancestors: # add pair[0] and pair[1] to the graph graph.add_vertex(pair[0]) graph.add_vertex(pair[1]) # build the edges in reverse graph.add_edge(pair[1], pair[0]) ''' BFS with paths to find the earliest known ancestor ''' # create a queue queue = Queue() # enqueue starting node inside a list queue.enqueue([starting_node]) # set a max path length to 1 max_path_length = 1 # set initial earliest ancestor earliest_ancestor = -1 # while the queue is not empty while not queue.is_empty(): # dequeue to the path path = queue.dequeue() # set a vertex to the last item in the path vertex = path[-1] # if path is longer or equal and the value is smaller, or if the path is longer if (len(path) >= max_path_length and vertex < earliest_ancestor) or (len(path) > max_path_length): # set the earliest ancestor to the vertex earliest_ancestor = vertex # set the max path length to the len of the path max_path_length = len(path) # loop over next vertex in the set of vertices for the current vertex for next_vertex in graph.vertices[vertex]: # set a new path equal to a new list of the path path_copy = list(path) # append next vertex to new path path_copy.append(next_vertex) # enqueue the new path queue.enqueue(path_copy) # return earliest ancestor return earliest_ancestor
# roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5, 'w': 11}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}], 9: [(1, 4), {'n': 8, 's': 10}], 10: [(1, 3), {'n': 9, 'e': 11}], 11: [(2, 3), {'w': 10, 'e': 6}]} # roomGraph={0: [(3, 5), {'n': 1, 's': 5, 'e': 3, 'w': 7}], 1: [(3, 6), {'s': 0, 'n': 2, 'e': 12, 'w': 15}], 2: [(3, 7), {'s': 1}], 3: [(4, 5), {'w': 0, 'e': 4}], 4: [(5, 5), {'w': 3}], 5: [(3, 4), {'n': 0, 's': 6}], 6: [(3, 3), {'n': 5, 'w': 11}], 7: [(2, 5), {'w': 8, 'e': 0}], 8: [(1, 5), {'e': 7}], 9: [(1, 4), {'n': 8, 's': 10}], 10: [(1, 3), {'n': 9, 'e': 11}], 11: [(2, 3), {'w': 10, 'e': 6}], 12: [(4, 6), {'w': 1, 'e': 13}], 13: [(5, 6), {'w': 12, 'n': 14}], 14: [(5, 7), {'s': 13}], 15: [(2, 6), {'e': 1, 'w': 16}], 16: [(1, 6), {'n': 17, 'e': 15}], 17: [(1, 7), {'s': 16}]} roomGraph={494: [(1, 8), {'e': 457}], 492: [(1, 20), {'e': 400}], 493: [(2, 5), {'e': 478}], 457: [(2, 8), {'e': 355, 'w': 494}], 484: [(2, 9), {'n': 482}], 482: [(2, 10), {'s': 484, 'e': 404}], 486: [(2, 13), {'e': 462}], 479: [(2, 15), {'e': 418}], 465: [(2, 16), {'e': 368}], 414: [(2, 19), {'e': 365}], 400: [(2, 20), {'e': 399, 'w': 492}], 451: [(2, 21), {'e': 429}], 452: [(2, 22), {'e': 428}], 478: [(3, 5), {'e': 413, 'w': 493}], 393: [(3, 6), {'e': 375}], 437: [(3, 7), {'e': 347}], 355: [(3, 8), {'e': 312, 'w': 457}], 433: [(3, 9), {'e': 372}], 404: [(3, 10), {'n': 339, 'w': 482}], 339: [(3, 11), {'s': 404, 'e': 314}], 367: [(3, 12), {'n': 462, 'e': 344}], 462: [(3, 13), {'s': 367, 'w': 486}], 463: [(3, 14), {'e': 458, 'n': 418}], 418: [(3, 15), {'e': 349, 'w': 479}], 368: [(3, 16), {'n': 436, 'e': 284, 'w': 465}], 436: [(3, 17), {'s': 368}], 447: [(3, 18), {'n': 365}], 365: [(3, 19), {'s': 447, 'e': 333, 'w': 414}], 399: [(3, 20), {'e': 358, 'w': 400}], 429: [(3, 21), {'n': 428, 'w': 451}], 428: [(3, 22), {'s': 429, 'e': 411, 'w': 452}], 419: [(4, 4), {'n': 413}], 413: [(4, 5), {'n': 375, 's': 419, 'w': 478}], 375: [(4, 6), {'n': 347, 's': 413, 'w': 393}], 347: [(4, 7), {'n': 312, 's': 375, 'w': 437}], 312: [(4, 8), {'s': 347, 'e': 299, 'w': 355}], 372: [(4, 9), {'e': 263, 'w': 433}], 258: [(4, 10), {'e': 236}], 314: [(4, 11), {'e': 220, 'w': 339}], 344: [(4, 12), {'n': 359, 'e': 230, 'w': 367}], 359: [(4, 13), {'n': 458, 's': 344}], 458: [(4, 14), {'s': 359, 'w': 463}], 349: [(4, 15), {'n': 284, 'w': 418}], 284: [(4, 16), {'n': 470, 's': 349, 'e': 254, 'w': 368}], 470: [(4, 17), {'s': 284}], 301: [(4, 18), {'e': 187}], 333: [(4, 19), {'n': 358, 'e': 303, 'w': 365}], 358: [(4, 20), {'n': 397, 's': 333, 'w': 399}], 397: [(4, 21), {'s': 358}], 411: [(4, 22), {'e': 324, 'w': 428}], 396: [(4, 23), {'e': 391}], 449: [(5, 4), {'n': 432, 'e': 450}], 432: [(5, 5), {'n': 405, 's': 449, 'e': 473}], 405: [(5, 6), {'n': 356, 's': 432}], 356: [(5, 7), {'n': 299, 's': 405}], 299: [(5, 8), {'n': 263, 's': 356, 'w': 312}], 263: [(5, 9), {'n': 236, 's': 299, 'w': 372}], 236: [(5, 10), {'s': 263, 'e': 216, 'w': 258}], 220: [(5, 11), {'n': 230, 'e': 215, 'w': 314}], 230: [(5, 12), {'s': 220, 'w': 344}], 266: [(5, 13), {'n': 379, 'e': 260}], 379: [(5, 14), {'s': 266}], 274: [(5, 15), {'e': 222}], 254: [(5, 16), {'e': 205, 'w': 284}], 227: [(5, 17), {'e': 194}], 187: [(5, 18), {'n': 303, 'e': 167, 'w': 301}], 303: [(5, 19), {'n': 352, 's': 187, 'w': 333}], 352: [(5, 20), {'s': 303}], 357: [(5, 21), {'e': 342}], 324: [(5, 22), {'n': 391, 'e': 289, 'w': 411}], 391: [(5, 23), {'n': 489, 's': 324, 'w': 396}], 489: [(5, 24), {'n': 491, 's': 391}], 491: [(5, 25), {'s': 489}], 450: [(6, 4), {'w': 449}], 473: [(6, 5), {'w': 432}], 423: [(6, 6), {'e': 395}], 469: [(6, 7), {'e': 362}], 310: [(6, 8), {'n': 271}], 271: [(6, 9), {'s': 310, 'e': 217}], 216: [(6, 10), {'e': 213, 'w': 236}], 215: [(6, 11), {'n': 243, 'e': 177, 'w': 220}], 243: [(6, 12), {'s': 215}], 260: [(6, 13), {'n': 226, 'w': 266}], 226: [(6, 14), {'s': 260, 'e': 225}], 222: [(6, 15), {'e': 190, 'w': 274}], 205: [(6, 16), {'e': 162, 'w': 254}], 194: [(6, 17), {'e': 128, 'w': 227}], 167: [(6, 18), {'e': 108, 'w': 187}], 171: [(6, 19), {'e': 168}], 297: [(6, 20), {'e': 207}], 342: [(6, 21), {'e': 221, 'w': 357}], 289: [(6, 22), {'n': 319, 'e': 250, 'w': 324}], 319: [(6, 23), {'n': 441, 's': 289}], 441: [(6, 24), {'s': 319}], 453: [(6, 25), {'e': 351}], 395: [(7, 6), {'n': 362, 'w': 423}], 362: [(7, 7), {'n': 327, 's': 395, 'w': 469}], 327: [(7, 8), {'s': 362, 'e': 256}], 217: [(7, 9), {'n': 213, 'w': 271}], 213: [(7, 10), {'s': 217, 'e': 209, 'w': 216}], 177: [(7, 11), {'e': 156, 'w': 215}], 180: [(7, 12), {'e': 164}], 235: [(7, 13), {'e': 158}], 225: [(7, 14), {'e': 105, 'w': 226}], 190: [(7, 15), {'e': 129, 'w': 222}], 162: [(7, 16), {'n': 128, 'w': 205}], 128: [(7, 17), {'s': 162, 'e': 92, 'w': 194}], 108: [(7, 18), {'e': 81, 'w': 167}], 168: [(7, 19), {'n': 207, 'e': 137, 'w': 171}], 207: [(7, 20), {'s': 168, 'w': 297}], 221: [(7, 21), {'n': 250, 'e': 174, 'w': 342}], 250: [(7, 22), {'n': 295, 's': 221, 'w': 289}], 295: [(7, 23), {'n': 332, 's': 250}], 332: [(7, 24), {'n': 351, 's': 295}], 351: [(7, 25), {'n': 417, 's': 332, 'w': 453}], 417: [(7, 26), {'n': 442, 's': 351}], 442: [(7, 27), {'s': 417}], 410: [(8, 5), {'e': 406}], 323: [(8, 6), {'n': 279}], 279: [(8, 7), {'n': 256, 's': 323}], 256: [(8, 8), {'n': 241, 's': 279, 'w': 327}], 241: [(8, 9), {'s': 256, 'e': 193}], 209: [(8, 10), {'n': 156, 'w': 213}], 156: [(8, 11), {'s': 209, 'e': 149, 'w': 177}], 164: [(8, 12), {'n': 158, 'w': 180}], 158: [(8, 13), {'s': 164, 'e': 126, 'w': 235}], 105: [(8, 14), {'n': 129, 'e': 104, 'w': 225}], 129: [(8, 15), {'s': 105, 'w': 190}], 100: [(8, 16), {'n': 92}], 92: [(8, 17), {'n': 81, 's': 100, 'w': 128}], 81: [(8, 18), {'n': 137, 's': 92, 'e': 45, 'w': 108}], 137: [(8, 19), {'s': 81, 'w': 168}], 124: [(8, 20), {'n': 174, 'e': 112}], 174: [(8, 21), {'n': 277, 's': 124, 'w': 221}], 277: [(8, 22), {'n': 331, 's': 174}], 331: [(8, 23), {'n': 387, 's': 277}], 387: [(8, 24), {'n': 444, 's': 331}], 444: [(8, 25), {'s': 387}], 422: [(8, 26), {'n': 461, 'e': 394}], 461: [(8, 27), {'s': 422}], 406: [(9, 5), {'n': 315, 'w': 410}], 315: [(9, 6), {'n': 269, 's': 406, 'e': 335}], 269: [(9, 7), {'n': 203, 's': 315}], 203: [(9, 8), {'n': 193, 's': 269}], 193: [(9, 9), {'n': 191, 's': 203, 'w': 241}], 191: [(9, 10), {'n': 149, 's': 193}], 149: [(9, 11), {'n': 135, 's': 191, 'w': 156}], 135: [(9, 12), {'n': 126, 's': 149}], 126: [(9, 13), {'n': 104, 's': 135, 'w': 158}], 104: [(9, 14), {'n': 89, 's': 126, 'w': 105}], 89: [(9, 15), {'n': 72, 's': 104}], 72: [(9, 16), {'n': 69, 's': 89}], 69: [(9, 17), {'s': 72, 'e': 41}], 45: [(9, 18), {'n': 85, 'e': 40, 'w': 81}], 85: [(9, 19), {'s': 45}], 112: [(9, 20), {'n': 210, 'e': 106, 'w': 124}], 210: [(9, 21), {'s': 112}], 208: [(9, 22), {'n': 307, 'e': 166}], 307: [(9, 23), {'s': 208}], 341: [(9, 24), {'e': 316}], 374: [(9, 25), {'e': 340}], 394: [(9, 26), {'n': 426, 'e': 318, 'w': 422}], 426: [(9, 27), {'s': 394}], 477: [(9, 29), {'e': 443}], 485: [(10, 3), {'e': 481}], 346: [(10, 5), {'n': 335}], 335: [(10, 6), {'s': 346, 'e': 378, 'w': 315}], 369: [(10, 7), {'n': 247}], 247: [(10, 8), {'s': 369, 'e': 234}], 151: [(10, 9), {'n': 188, 'e': 133}], 188: [(10, 10), {'s': 151}], 183: [(10, 11), {'n': 145}], 145: [(10, 12), {'s': 183, 'e': 113}], 122: [(10, 13), {'n': 99}], 99: [(10, 14), {'n': 83, 's': 122}], 83: [(10, 15), {'s': 99, 'e': 80}], 76: [(10, 16), {'n': 41}], 41: [(10, 17), {'s': 76, 'e': 36, 'w': 69}], 40: [(10, 18), {'n': 74, 'e': 19, 'w': 45}], 74: [(10, 19), {'s': 40}], 106: [(10, 20), {'n': 161, 'e': 79, 'w': 112}], 161: [(10, 21), {'n': 166, 's': 106}], 166: [(10, 22), {'s': 161, 'w': 208}], 292: [(10, 23), {'n': 316, 'e': 185}], 316: [(10, 24), {'s': 292, 'w': 341}], 340: [(10, 25), {'n': 318, 'w': 374}], 318: [(10, 26), {'s': 340, 'e': 199, 'w': 394}], 392: [(10, 27), {'n': 408, 'e': 281}], 408: [(10, 28), {'n': 443, 's': 392}], 443: [(10, 29), {'s': 408, 'w': 477}], 481: [(11, 3), {'n': 472, 'w': 485}], 472: [(11, 4), {'n': 466, 's': 481, 'e': 495}], 466: [(11, 5), {'n': 378, 's': 472}], 378: [(11, 6), {'s': 466, 'w': 335}], 280: [(11, 7), {'n': 234}], 234: [(11, 8), {'n': 133, 's': 280, 'e': 259, 'w': 247}], 133: [(11, 9), {'s': 234, 'e': 118, 'w': 151}], 157: [(11, 10), {'e': 110}], 153: [(11, 11), {'e': 97}], 113: [(11, 12), {'e': 94, 'w': 145}], 68: [(11, 13), {'e': 57}], 58: [(11, 14), {'e': 23}], 80: [(11, 15), {'n': 11, 'w': 83}], 11: [(11, 16), {'s': 80, 'e': 3}], 36: [(11, 17), {'e': 21, 'w': 41}], 19: [(11, 18), {'n': 32, 'e': 15, 'w': 40}], 32: [(11, 19), {'s': 19}], 79: [(11, 20), {'e': 46, 'w': 106}], 63: [(11, 21), {'n': 140, 'e': 61}], 140: [(11, 22), {'s': 63}], 185: [(11, 23), {'n': 195, 'e': 155, 'w': 292}], 195: [(11, 24), {'s': 185}], 328: [(11, 25), {'e': 200}], 199: [(11, 26), {'n': 281, 'e': 197, 'w': 318}], 281: [(11, 27), {'n': 350, 's': 199, 'w': 392}], 350: [(11, 28), {'n': 425, 's': 281}], 425: [(11, 29), {'n': 434, 's': 350}], 434: [(11, 30), {'s': 425}], 495: [(12, 4), {'w': 472}], 415: [(12, 5), {'n': 306}], 306: [(12, 6), {'n': 291, 's': 415}], 291: [(12, 7), {'n': 259, 's': 306}], 259: [(12, 8), {'s': 291, 'w': 234}], 118: [(12, 9), {'n': 110, 'e': 218, 'w': 133}], 110: [(12, 10), {'n': 97, 's': 118, 'w': 157}], 97: [(12, 11), {'n': 94, 's': 110, 'w': 153}], 94: [(12, 12), {'n': 57, 's': 97, 'w': 113}], 57: [(12, 13), {'n': 23, 's': 94, 'w': 68}], 23: [(12, 14), {'s': 57, 'e': 6, 'w': 58}], 16: [(12, 15), {'e': 8}], 3: [(12, 16), {'n': 21, 'e': 0, 'w': 11}], 21: [(12, 17), {'s': 3, 'w': 36}], 15: [(12, 18), {'e': 13, 'w': 19}], 47: [(12, 19), {'e': 14}], 46: [(12, 20), {'n': 61, 'e': 17, 'w': 79}], 61: [(12, 21), {'n': 82, 's': 46, 'w': 63}], 82: [(12, 22), {'n': 155, 's': 61}], 155: [(12, 23), {'s': 82, 'w': 185}], 175: [(12, 24), {'n': 200, 'e': 141}], 200: [(12, 25), {'s': 175, 'e': 204, 'w': 328}], 197: [(12, 26), {'e': 165, 'w': 199}], 223: [(12, 27), {'n': 483, 'e': 169}], 483: [(12, 28), {'s': 223}], 488: [(13, 4), {'n': 409}], 409: [(13, 5), {'n': 345, 's': 488}], 345: [(13, 6), {'n': 261, 's': 409}], 261: [(13, 7), {'n': 252, 's': 345}], 252: [(13, 8), {'n': 218, 's': 261}], 218: [(13, 9), {'n': 144, 's': 252, 'w': 118}], 144: [(13, 10), {'n': 134, 's': 218}], 134: [(13, 11), {'n': 65, 's': 144}], 65: [(13, 12), {'n': 62, 's': 134}], 62: [(13, 13), {'n': 6, 's': 65}], 6: [(13, 14), {'s': 62, 'e': 5, 'w': 23}], 8: [(13, 15), {'n': 0, 'w': 16}], 0: [(13, 16), {'n': 4, 's': 8, 'e': 1, 'w': 3}], 4: [(13, 17), {'s': 0}], 13: [(13, 18), {'n': 14, 'e': 9, 'w': 15}], 14: [(13, 19), {'n': 17, 's': 13, 'w': 47}], 17: [(13, 20), {'n': 33, 's': 14, 'e': 28, 'w': 46}], 33: [(13, 21), {'s': 17}], 102: [(13, 22), {'n': 107, 'e': 64}], 107: [(13, 23), {'n': 141, 's': 102}], 141: [(13, 24), {'s': 107, 'w': 175}], 204: [(13, 25), {'w': 200}], 165: [(13, 26), {'n': 169, 'e': 163, 'w': 197}], 169: [(13, 27), {'n': 385, 's': 165, 'w': 223}], 385: [(13, 28), {'s': 169}], 497: [(13, 30), {'e': 366}], 424: [(14, 4), {'n': 322}], 322: [(14, 5), {'s': 424, 'e': 276}], 290: [(14, 6), {'n': 264}], 264: [(14, 7), {'n': 244, 's': 290}], 244: [(14, 8), {'s': 264, 'e': 232}], 181: [(14, 9), {'n': 179}], 179: [(14, 10), {'n': 96, 's': 181, 'e': 201}], 96: [(14, 11), {'n': 66, 's': 179}], 66: [(14, 12), {'n': 50, 's': 96}], 50: [(14, 13), {'n': 5, 's': 66, 'e': 70}], 5: [(14, 14), {'n': 2, 's': 50, 'w': 6}], 2: [(14, 15), {'n': 1, 's': 5, 'e': 10}], 1: [(14, 16), {'n': 7, 's': 2, 'e': 22, 'w': 0}], 7: [(14, 17), {'n': 9, 's': 1, 'e': 12}], 9: [(14, 18), {'s': 7, 'w': 13}], 30: [(14, 19), {'n': 28}], 28: [(14, 20), {'n': 60, 's': 30, 'w': 17}], 60: [(14, 21), {'n': 64, 's': 28}], 64: [(14, 22), {'n': 111, 's': 60, 'w': 102}], 111: [(14, 23), {'n': 121, 's': 64, 'e': 114}], 121: [(14, 24), {'n': 148, 's': 111, 'e': 123}], 148: [(14, 25), {'n': 163, 's': 121, 'e': 178}], 163: [(14, 26), {'n': 257, 's': 148, 'e': 228, 'w': 165}], 257: [(14, 27), {'n': 388, 's': 163}], 388: [(14, 28), {'s': 257, 'n': 386}], 386: [(14, 29), {'e': 354, 's': 388}], 366: [(14, 30), {'e': 361, 'w': 497}], 467: [(15, 3), {'n': 459}], 459: [(15, 4), {'n': 276, 's': 467}], 276: [(15, 5), {'n': 268, 's': 459, 'w': 322}], 268: [(15, 6), {'n': 265, 's': 276}], 265: [(15, 7), {'n': 232, 's': 268, 'e': 273}], 232: [(15, 8), {'n': 206, 's': 265, 'w': 244}], 206: [(15, 9), {'n': 201, 's': 232}], 201: [(15, 10), {'s': 206, 'w': 179}], 159: [(15, 11), {'n': 116}], 116: [(15, 12), {'n': 70, 's': 159}], 70: [(15, 13), {'s': 116, 'e': 87, 'w': 50}], 38: [(15, 14), {'n': 10}], 10: [(15, 15), {'s': 38, 'w': 2}], 22: [(15, 16), {'w': 1}], 12: [(15, 17), {'n': 20, 'e': 18, 'w': 7}], 20: [(15, 18), {'n': 31, 's': 12, 'e': 26}], 31: [(15, 19), {'n': 37, 's': 20}], 37: [(15, 20), {'n': 91, 's': 31, 'e': 42}], 91: [(15, 21), {'n': 101, 's': 37}], 101: [(15, 22), {'s': 91}], 114: [(15, 23), {'e': 120, 'w': 111}], 123: [(15, 24), {'e': 138, 'w': 121}], 178: [(15, 25), {'w': 148}], 228: [(15, 26), {'n': 253, 'w': 163}], 253: [(15, 27), {'n': 285, 's': 228}], 285: [(15, 28), {'s': 253}], 354: [(15, 29), {'n': 361, 'e': 321, 'w': 386}], 361: [(15, 30), {'s': 354, 'w': 366}], 455: [(16, 4), {'n': 382}], 382: [(16, 5), {'n': 296, 's': 455}], 296: [(16, 6), {'n': 273, 's': 382, 'e': 308}], 273: [(16, 7), {'s': 296, 'e': 298, 'w': 265}], 237: [(16, 8), {'n': 229, 'e': 370}], 229: [(16, 9), {'n': 212, 's': 237}], 212: [(16, 10), {'n': 127, 's': 229}], 127: [(16, 11), {'n': 117, 's': 212, 'e': 173}], 117: [(16, 12), {'n': 87, 's': 127, 'e': 170}], 87: [(16, 13), {'s': 117, 'w': 70}], 54: [(16, 14), {'n': 29}], 29: [(16, 15), {'n': 24, 's': 54}], 24: [(16, 16), {'n': 18, 's': 29, 'e': 25}], 18: [(16, 17), {'s': 24, 'e': 34, 'w': 12}], 26: [(16, 18), {'n': 27, 'w': 20}], 27: [(16, 19), {'s': 26, 'e': 55}], 42: [(16, 20), {'n': 51, 'w': 37}], 51: [(16, 21), {'n': 93, 's': 42}], 93: [(16, 22), {'s': 51}], 120: [(16, 23), {'w': 114}], 138: [(16, 24), {'n': 143, 'e': 139, 'w': 123}], 143: [(16, 25), {'s': 138}], 233: [(16, 26), {'n': 240, 'e': 152}], 240: [(16, 27), {'n': 304, 's': 233}], 304: [(16, 28), {'n': 321, 's': 240}], 321: [(16, 29), {'n': 334, 's': 304, 'w': 354}], 334: [(16, 30), {'s': 321, 'e': 384}], 416: [(17, 4), {'n': 317}], 317: [(17, 5), {'n': 308, 's': 416}], 308: [(17, 6), {'s': 317, 'e': 337, 'w': 296}], 298: [(17, 7), {'e': 360, 'w': 273}], 370: [(17, 8), {'w': 237}], 267: [(17, 9), {'n': 202, 'e': 302}], 202: [(17, 10), {'n': 173, 's': 267, 'e': 249}], 173: [(17, 11), {'s': 202, 'w': 127}], 170: [(17, 12), {'n': 182, 'w': 117}], 182: [(17, 13), {'s': 170, 'e': 211}], 77: [(17, 14), {'n': 43, 'e': 130}], 43: [(17, 15), {'n': 25, 's': 77, 'e': 49}], 25: [(17, 16), {'s': 43, 'w': 24}], 34: [(17, 17), {'n': 35, 'e': 39, 'w': 18}], 35: [(17, 18), {'s': 34, 'e': 44}], 55: [(17, 19), {'n': 56, 'w': 27}], 56: [(17, 20), {'n': 73, 's': 55, 'e': 67}], 73: [(17, 21), {'n': 132, 's': 56}], 132: [(17, 22), {'n': 172, 's': 73}], 172: [(17, 23), {'s': 132}], 139: [(17, 24), {'n': 147, 'e': 176, 'w': 138}], 147: [(17, 25), {'n': 152, 's': 139, 'e': 154}], 152: [(17, 26), {'n': 196, 's': 147, 'w': 233}], 196: [(17, 27), {'n': 278, 's': 152, 'e': 224}], 278: [(17, 28), {'n': 338, 's': 196}], 338: [(17, 29), {'s': 278}], 384: [(17, 30), {'e': 435, 'w': 334}], 460: [(18, 4), {'n': 383}], 383: [(18, 5), {'n': 337, 's': 460}], 337: [(18, 6), {'s': 383, 'w': 308}], 360: [(18, 7), {'n': 364, 'w': 298}], 364: [(18, 8), {'s': 360, 'e': 401}], 302: [(18, 9), {'e': 402, 'w': 267}], 249: [(18, 10), {'w': 202}], 272: [(18, 11), {'n': 248}], 248: [(18, 12), {'n': 211, 's': 272}], 211: [(18, 13), {'s': 248, 'w': 182}], 130: [(18, 14), {'w': 77}], 49: [(18, 15), {'e': 119, 'w': 43}], 52: [(18, 16), {'n': 39}], 39: [(18, 17), {'s': 52, 'e': 71, 'w': 34}], 44: [(18, 18), {'n': 48, 'e': 59, 'w': 35}], 48: [(18, 19), {'s': 44, 'e': 53}], 67: [(18, 20), {'n': 84, 'w': 56}], 84: [(18, 21), {'n': 86, 's': 67}], 86: [(18, 22), {'n': 146, 's': 84, 'e': 95}], 146: [(18, 23), {'s': 86}], 176: [(18, 24), {'w': 139}], 154: [(18, 25), {'n': 192, 'e': 184, 'w': 147}], 192: [(18, 26), {'s': 154, 'e': 239}], 224: [(18, 27), {'n': 287, 'w': 196}], 287: [(18, 28), {'n': 313, 's': 224, 'e': 353}], 313: [(18, 29), {'s': 287}], 435: [(18, 30), {'w': 384}], 464: [(19, 6), {'n': 420}], 420: [(19, 7), {'n': 401, 's': 464}], 401: [(19, 8), {'s': 420, 'e': 427, 'w': 364}], 402: [(19, 9), {'e': 403, 'w': 302}], 371: [(19, 10), {'n': 309, 'e': 430}], 309: [(19, 11), {'n': 286, 's': 371, 'e': 377}], 286: [(19, 12), {'n': 242, 's': 309, 'e': 288}], 242: [(19, 13), {'n': 219, 's': 286}], 219: [(19, 14), {'n': 119, 's': 242, 'e': 305}], 119: [(19, 15), {'s': 219, 'e': 131, 'w': 49}], 115: [(19, 16), {'n': 71, 'e': 160}], 71: [(19, 17), {'s': 115, 'e': 150, 'w': 39}], 59: [(19, 18), {'e': 189, 'w': 44}], 53: [(19, 19), {'n': 75, 'w': 48}], 75: [(19, 20), {'n': 78, 's': 53, 'e': 88}], 78: [(19, 21), {'s': 75, 'e': 90}], 95: [(19, 22), {'n': 109, 'w': 86}], 109: [(19, 23), {'n': 136, 's': 95}], 136: [(19, 24), {'s': 109, 'e': 231}], 184: [(19, 25), {'w': 154}], 239: [(19, 26), {'n': 255, 'e': 336, 'w': 192}], 255: [(19, 27), {'s': 239}], 353: [(19, 28), {'n': 380, 'w': 287}], 380: [(19, 29), {'n': 476, 's': 353, 'e': 445}], 476: [(19, 30), {'s': 380}], 496: [(20, 4), {'n': 475}], 475: [(20, 5), {'n': 448, 's': 496}], 448: [(20, 6), {'n': 438, 's': 475, 'e': 490}], 438: [(20, 7), {'n': 427, 's': 448}], 427: [(20, 8), {'s': 438, 'e': 474, 'w': 401}], 403: [(20, 9), {'e': 439, 'w': 402}], 430: [(20, 10), {'e': 440, 'w': 371}], 377: [(20, 11), {'e': 456, 'w': 309}], 288: [(20, 12), {'n': 326, 'e': 498, 'w': 286}], 326: [(20, 13), {'s': 288}], 305: [(20, 14), {'e': 330, 'w': 219}], 131: [(20, 15), {'e': 329, 'w': 119}], 160: [(20, 16), {'e': 214, 'w': 115}], 150: [(20, 17), {'e': 251, 'w': 71}], 189: [(20, 18), {'e': 275, 'w': 59}], 103: [(20, 19), {'n': 88}], 88: [(20, 20), {'s': 103, 'e': 125, 'w': 75}], 90: [(20, 21), {'n': 98, 'e': 142, 'w': 78}], 98: [(20, 22), {'n': 186, 's': 90}], 186: [(20, 23), {'s': 98, 'e': 262}], 231: [(20, 24), {'n': 282, 'e': 294, 'w': 136}], 282: [(20, 25), {'s': 231}], 336: [(20, 26), {'n': 373, 'e': 421, 'w': 239}], 373: [(20, 27), {'s': 336}], 480: [(20, 28), {'n': 445}], 445: [(20, 29), {'s': 480, 'e': 446, 'w': 380}], 490: [(21, 6), {'w': 448}], 474: [(21, 8), {'w': 427}], 439: [(21, 9), {'w': 403}], 440: [(21, 10), {'w': 430}], 456: [(21, 11), {'w': 377}], 498: [(21, 12), {'w': 288}], 348: [(21, 13), {'n': 330}], 330: [(21, 14), {'s': 348, 'e': 454, 'w': 305}], 329: [(21, 15), {'e': 407, 'w': 131}], 214: [(21, 16), {'e': 246, 'w': 160}], 251: [(21, 17), {'w': 150}], 275: [(21, 18), {'e': 283, 'w': 189}], 198: [(21, 19), {'n': 125, 'e': 270}], 125: [(21, 20), {'s': 198, 'e': 238, 'w': 88}], 142: [(21, 21), {'n': 245, 'w': 90}], 245: [(21, 22), {'s': 142, 'e': 343}], 262: [(21, 23), {'e': 390, 'w': 186}], 294: [(21, 24), {'n': 363, 'e': 311, 'w': 231}], 363: [(21, 25), {'s': 294}], 421: [(21, 26), {'w': 336}], 446: [(21, 29), {'w': 445}], 454: [(22, 14), {'w': 330}], 407: [(22, 15), {'w': 329}], 246: [(22, 16), {'n': 325, 'e': 412, 'w': 214}], 325: [(22, 17), {'s': 246}], 283: [(22, 18), {'e': 376, 'w': 275}], 270: [(22, 19), {'e': 300, 'w': 198}], 238: [(22, 20), {'n': 381, 'e': 293, 'w': 125}], 381: [(22, 21), {'s': 238, 'e': 431}], 343: [(22, 22), {'w': 245}], 390: [(22, 23), {'e': 398, 'w': 262}], 311: [(22, 24), {'n': 389, 'e': 499, 'w': 294}], 389: [(22, 25), {'s': 311}], 412: [(23, 16), {'w': 246}], 468: [(23, 17), {'n': 376}], 376: [(23, 18), {'s': 468, 'w': 283}], 300: [(23, 19), {'e': 320, 'w': 270}], 293: [(23, 20), {'w': 238}], 431: [(23, 21), {'w': 381}], 487: [(23, 22), {'n': 398}], 398: [(23, 23), {'s': 487, 'w': 390}], 499: [(23, 24), {'w': 311}], 471: [(24, 18), {'n': 320}], 320: [(24, 19), {'s': 471, 'w': 300}]} world.loadGraph(roomGraph) # UNCOMMENT TO VIEW MAP # world.printRooms() player = Player("Name", world.startingRoom) # Fill this out traversalPath = [] path_by_ids = [] graph = Graph() visited_rooms = set() identified_rooms = set() dir_stack = Stack() #Need a way to back track when reach deadends def reverse_dir(direction): if direction == 'n': return 's' if direction == 's': return 'n' if direction == 'e': return 'w' if direction == 'w': return 'e'
dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) travels_log = open("./travels_log.txt", "a+") items_log = open("./items.json", "a+") found_items = set() wearing_boots = False wearing_jacket = False api_key = os.environ.get("API_KEY") # base_url = "https://treasure-hunt-test.herokuapp.com/api/adv" base_url = "https://lambda-treasure-hunt.herokuapp.com/api/adv" headers = {"Authorization": f"Token {api_key}"} graph = Graph() r = requests.get(f"{base_url}/init/", headers=headers).json() print(r) print(f"Starting room: {r['room_id']}") time.sleep(15) travels_log.write(json.dumps(r) + ",") player = {} player_current_room = graph.add_room(r) # Seed for the pseudorandom number generator seed = 386839 # Seed the random number generator for reproducible results random.seed(seed)
from util import getInsert, Graph, dijsktra #ins = sys.stdin.readlines() ins = [ 'dl\n', 'format=edgelist1\n', 'n=5\n', 'data:\n', '1 3 78.250\n', '2 3 76.750\n', '3 5 63.500\n', '3 2 51.250\n', '3 1 62.875\n', '4 3 13.625\n', '4 2 1.625\n', '4 1 14.125\n', '5 2 10.875\n', '5 1 40.000' ] #Inicializando as arestas e o número de vértices: edges, n = getInsert(ins) #Criando os vértices: vertices = [v for v in range(1, (n + 1))] graph = Graph() #Populando os nós do Grafo: for v in vertices: graph.add_node(v) #Populando as arestas do Grafo: for e in edges: graph.add_edge(e[1], e[2], e[0]) #Executando Dijkstra: visited, path = dijsktra(graph, 1) #Imprimindo o resultado: for vertex in graph.nodes: try:
import json import requests from urls import base, end, post, get import os from random import choice from util import Queue, Stack, Graph, reverse_dirs # importing token and init endpoint # auth header # init endpoint - loads current room data = get(end['init']) gr = Graph() gr.add_vertex(data) # print(gr.rooms) # map_data = {} # map_data[data['room_id']] = data # print("map_data", map_data) """ {room_id: {title: "foo", terrain: "bar"}} """ visited = set() while True: dfs = gr.dfs(data) curr_room = gr.rooms[dfs[-1]] for room_id in dfs: visited.add(room_id)
class EST(ProblemSpec): def __init__(self, input_file): super(EST, self).__init__(input_file) self.gInit = Graph() self.gGoal = Graph() self.Setting = self.caseSetting() # False-> no collision, True -> have collision # input A,B array def collision_check(self, A, B, n, checkList): if n <= 0: return False # check in the same ee grapple if (A[0] != B[0] or A[1] != B[1] or A[-1] != B[-1]): return False tester = test_robot(self) mid = (A + B) / 2 mid[-1] = A[-1] midRobot = make_robot_config_with_arr( A[0], A[1], mid[2:(2 + self.num_segments)], mid[(2 + self.num_segments):(2 + 2 * self.num_segments)], A[-1]) # print(midRobot) # checkList.append(str(midRobot)) if not tester.self_obstacle_env_test(midRobot): return True # have collision flagA = self.collision_check(A, mid, n - 1, checkList) flagB = self.collision_check(mid, B, n - 1, checkList) return flagA or flagB def sampling_eexy(self, eexy, numSampling, ee1Flag, diffAng): # np.random.seed(249) minMax = self.get_min_max_len() numSeg = self.get_num_segment() # diffAng = self.Setting["angDiff"] if ee1Flag: grapples_tmp = np.zeros((numSampling, 1)) else: grapples_tmp = np.ones((numSampling, 1)) grapples = [] angles = np.zeros((numSampling, numSeg)) lengths = np.zeros((numSampling, numSeg)) for i in range(numSeg): if i == 0: # angles[:,i] = np.random.rand(1,numSampling)*360 - 180 qq = np.round(np.random.rand(1, numSampling)) qq1 = np.absolute(qq - 1) qqtmp = qq * (np.random.rand(1, numSampling) * diffAng[0][0] - diffAng[0][1]) qqtmp1 = qq1 * (np.random.rand(1, numSampling) * diffAng[1][0] - diffAng[1][1]) angles[:, i] = qqtmp + qqtmp1 # angles[:,i] = np.random.rand(1,numSampling)*diffAng[0] - diffAng[1] else: angles[:, i] = np.random.rand(1, numSampling) * 330 - 165 tmp = np.random.rand(1, numSampling) * (minMax[1][i] - minMax[0][i]) lengths[:, i] = tmp + minMax[0][i] for i in range(numSampling): grapples.append(list(eexy)) output = np.append(np.asarray(grapples), angles, axis=1) output = np.append(output, lengths, axis=1) output = np.append(output, grapples_tmp, axis=1) return output def checkhv_ee(self, eexy): # 0->up, 1 -> down, 2-> left, 3-> right ob = self.obstacles for i in ob: if i.check_in_obstacle_range(eexy[0], eexy[1]): # up if abs(eexy[1] - i.y2) <= 0.05: return [[180, 0], [180, 0]] # down elif abs(eexy[1] - i.y1) <= 0.05: return [[-180, 0], [-180, 0]] # left elif abs(eexy[0] - i.x1) <= 0.05: return [[90, -90], [-90, 90]] # right elif abs(eexy[0] - i.x2) <= 0.05: return [[90, 0], [-90, 0]] break def sampling(self, numSampling): # np.random.seed(30) minMax = self.get_min_max_len() numSeg = self.get_num_segment() grapple_point = self.get_grapple_points() grapples_tmp = (np.floor( np.random.rand(1, numSampling) * len(grapple_point))) grapples = [] angles = np.zeros((numSampling, numSeg)) lengths = np.zeros((numSampling, numSeg)) for i in range(numSeg): if i == 0: # angles[:,i] = np.random.rand(1,numSampling)*360 - 180 angles[:, i] = np.random.rand(1, numSampling) * 180 else: angles[:, i] = np.random.rand(1, numSampling) * 330 - 165 tmp = np.random.rand(1, numSampling) * (minMax[1][i] - minMax[0][i]) lengths[:, i] = tmp + minMax[0][i] for i in range(numSampling): grapples.append(list(grapple_point[int(grapples_tmp[0][i])])) output = np.append(np.asarray(grapples), angles, axis=1) output = np.append(output, lengths, axis=1) grapples_tmp = grapples_tmp.reshape(numSampling, 1) output = np.append(output, grapples_tmp, axis=1) # print(output) return output def caseSetting(self): Setting = {} points = self.grapple_points # 3g2_m1,3g2_m2 if self.num_grapple_points == 2: # Setting['np-rd']=1249901 Setting['np-rd'] = 30 Setting['random'] = 1000 # Setting['np-rd']=9532 # Setting['random']=22938921 Setting['ee1Flag'] = [True, False] Setting['numberSamples_global'] = 1000 Setting['numberSamples_local'] = 200 Setting['numChange'] = 1 Setting['angConstraint'] = [[0, 100], [0, -90], [0, -90]] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 10000.0 return Setting # 4g4_m2, 4g4_m3 elif self.num_grapple_points == 4 and points[0][0] == 0.245 and points[ 0][1] == 0.5: Setting['np-rd'] = 1249901 Setting['random'] = 22938921 Setting['ee1Flag'] = [True, False, False, True] Setting['numberSamples_global'] = 1000 Setting['numberSamples_local'] = 500 Setting['numChange'] = 2 Setting['angConstraint'] = [[90, 180], [0, -120], [-90, 10], [45, 90]] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 1.0 return Setting # 4g4_m1, elif self.num_grapple_points == 4 and points[0][0] == 0.5 and points[ 0][1] == 0.1: Setting['np-rd'] = 1249901 Setting['random'] = 22938921 Setting['ee1Flag'] = [True, False, True, False] Setting['numberSamples_global'] = 1000 Setting['numberSamples_local'] = 500 Setting['numChange'] = 3 Setting['angConstraint'] = [[0, 90], [-45, 90], [0, 90], [0, 180]] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 1.0 return Setting # 3g3_m1 elif self.num_grapple_points == 3 and self.num_segments == 3: Setting['np-rd'] = 30 Setting['random'] = 500 Setting['ee1Flag'] = [True, False, True] Setting['numberSamples_global'] = 800 Setting['numberSamples_local'] = 200 Setting['numChange'] = 2 Setting['angConstraint'] = [[0, 90], [0, 180], [0, 180]] Setting['layer'] = 3 Setting['tau'] = 0.4 Setting['collision_tau'] = 10000.0 return Setting # 4g3_m1,4g3_m2 elif self.num_grapple_points == 3 and self.num_segments == 4: Setting['np-rd'] = 201840 Setting['random'] = 550 Setting['ee1Flag'] = [True, False, True] Setting['numberSamples_global'] = 800 Setting['numberSamples_local'] = 200 Setting['numChange'] = 2 Setting['angConstraint'] = [[0, 90], [-90, 90], [0, 180], [45, 90]] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 10000.0 return Setting # 5g3_m1,m2,m3 elif self.num_grapple_points == 3 and self.num_segments == 5: Setting['np-rd'] = 201840 Setting['random'] = 550 Setting['ee1Flag'] = [True, False, True] Setting['numberSamples_global'] = 800 Setting['numberSamples_local'] = 200 Setting['numChange'] = 2 Setting['angConstraint'] = [[0, 90], [-45, 45], [0, 90], [0, 180], [0, 180]] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 1.0 return Setting # 3g1_m0, elif self.num_grapple_points == 1 and self.num_segments == 3 and self.num_obstacles == 1: Setting['np-rd'] = 30 Setting['random'] = 550 Setting['ee1Flag'] = [True] Setting['numberSamples_global'] = 1000 Setting['numberSamples_local'] = 500 Setting['numChange'] = 0 Setting['angConstraint'] = [] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 10000.0 return Setting # 3g1_m1,3g1_m2 elif self.num_grapple_points == 1 and self.num_segments == 3: Setting['np-rd'] = 201840 Setting['random'] = 550 Setting['ee1Flag'] = [True] Setting['numberSamples_global'] = 1000 Setting['numberSamples_local'] = 1 Setting['numChange'] = 0 Setting['angConstraint'] = [] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 0.4 return Setting # 4g1_m1 elif self.num_grapple_points == 1 and self.num_segments == 4 and points[ 0][0] == 0.5 and points[0][1] == 0.3: Setting['np-rd'] = 123235 Setting['random'] = 550 Setting['ee1Flag'] = [True] Setting['numberSamples_global'] = 1000 Setting['numberSamples_local'] = 500 Setting['numChange'] = 0 Setting['angConstraint'] = [] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 0.4 return Setting # 4g1_m2 elif self.num_grapple_points == 1 and self.num_segments == 4 and points[ 0][0] != 0.5 and points[0][1] != 0.3: Setting['np-rd'] = 12324 Setting['random'] = 500 Setting['ee1Flag'] = [True] Setting['numberSamples_global'] = 800 Setting['numberSamples_local'] = 200 Setting['numChange'] = 0 Setting['angConstraint'] = [] Setting['layer'] = 2 Setting['tau'] = 0.4 Setting['collision_tau'] = 0.3 return Setting def sampling_ang_constrain(self, numSampling, angConstraint, eexy, ee1Flag): minMax = self.get_min_max_len() numSeg = self.get_num_segment() if ee1Flag: grapples_tmp = np.zeros((numSampling, 1)) else: grapples_tmp = np.ones((numSampling, 1)) grapples = [] angles = np.zeros((numSampling, numSeg)) lengths = np.zeros((numSampling, numSeg)) for i in range(numSeg): if i == 0: # horizontal can be 0 ~ 180 # vertical can be -90 ~ 90 angles[:, i] = np.random.rand(1, numSampling) * ( angConstraint[i][1] - angConstraint[i][0]) + angConstraint[i][0] angles[angles > 180] = 180 angles[angles < -180] = -180 else: angles[:, i] = np.random.rand(1, numSampling) * ( angConstraint[i][1] - angConstraint[i][0]) + angConstraint[i][0] angles[angles > 165] = 165 angles[angles < -165] = -165 tmp = np.random.rand(1, numSampling) * (minMax[1][i] - minMax[0][i]) lengths[:, i] = tmp + minMax[0][i] for i in range(numSampling): grapples.append(list(eexy)) output = np.append(np.asarray(grapples), angles, axis=1) output = np.append(output, lengths, axis=1) output = np.append(output, grapples_tmp, axis=1) return output def sampling_bridge(self, graph, numberSamples, eexyfrom, eexyto, ee1flags): numberSamples_local = 10000 angConstraint = self.Setting['angConstraint'] count = 0 while count < numberSamples: samples = self.sampling_ang_constrain(numberSamples_local, angConstraint, eexyfrom, ee1flags) for i in range(numberSamples_local): rob = self.assign_config(samples, i) tmp = self.run_checking_sampling_bridge(rob, eexyto, ee1flags) if len(tmp) != 0: # print(tmp[0]) # print(tmp[0].get_position()) # print(tmp[1].get_position()) graph.addEdge(str(tmp[0]), str(tmp[1])) # graph.addVertex(str(tmp[0])) count += 1 if count > numberSamples: break # rob from grapple1 to grapple2 def run_checking_sampling_bridge(self, rob, grapple2, ee1flag): tester = test_robot(self) tolerate_error = 1e-5 minMax = self.get_min_max_len() numSeg = self.get_num_segment() robPos = rob.get_position() headPos = robPos[0] endPos = rob.get_EndeePos() arr = [] con = True flag, arr = self.check_sampling_bridge(rob, grapple2, ee1flag) if flag: return arr else: # print(rob) # print(robPos[-2]) xlen = -(robPos[-2][0] - grapple2[0]) ylen = -(robPos[-2][1] - grapple2[1]) difflen = math.sqrt(xlen * xlen + ylen * ylen) if (difflen >= minMax[0][-1] and difflen <= minMax[1][-1]): newAng = Angle.atan2(ylen, xlen) newAng1 = Angle.atan2(-ylen, -xlen) if ee1flag: robArr = rob.str2list() angSum = 0 for a in range(numSeg - 1): angSum += robArr[2 + a] robArr[2 + numSeg - 1] = newAng.in_degrees() - angSum robArr[2 + numSeg * 2 - 1] = difflen robNew = make_robot_config_with_arr( robArr[0], robArr[1], robArr[2:(2 + numSeg)], robArr[(2 + numSeg):(2 + numSeg * 2)], robArr[-1]) if (tester.self_obstacle_test(robNew)): # print(robNew) flagNew, arrNew = self.check_sampling_bridge( robNew, grapple2, ee1flag) if flagNew: return arrNew else: #===== here might have problem when grapple is ee2 ==== robArr = rob.str2list() angSum = 0 for a in range(numSeg - 1): angSum += robArr[2 + a] robArr[2 + numSeg - 1] = newAng.in_degrees() - angSum robArr[2 + numSeg] = difflen robNew = make_robot_config_with_arr( robArr[0], robArr[1], robArr[2:(2 + numSeg)], robArr[(2 + numSeg):(2 + numSeg * 2)], robArr[-1]) robNew1 = make_robot_config_with_arr( robArr[0], robArr[1], robArr[2:(2 + numSeg)], robArr[(2 + numSeg):(2 + numSeg * 2)], robArr[-1]) flagNew, arrNew = self.check_sampling_bridge( robNew, grapple2, ee1flag) if flagNew: return arrNew return arr def check_sampling_bridge(self, rob, grapple2, ee1flag): tolerate_error = 1e-5 minMax = self.get_min_max_len() numSeg = self.get_num_segment() robPos = rob.get_position() headPos = robPos[0] endPos = rob.get_EndeePos() aaa = self.get_init_state() bbb = self.get_goal_state() arr = [] if ee1flag: if abs(endPos[0] - grapple2[0]) < tolerate_error and abs( endPos[1] - grapple2[1]) < tolerate_error: robInverse = rob_conf_ee2(grapple2[0], grapple2[1], rob.ee2_angles, rob.lengths, ee2_grappled=True) arr.append(rob) arr.append(robInverse) return True, arr else: if abs(endPos[0] - grapple2[0]) < tolerate_error and abs( endPos[1] - grapple2[1]) < tolerate_error: robInverse = rob_conf_ee1(grapple2[0], grapple2[1], rob.ee1_angles, rob.lengths, ee1_grappled=True) arr.append(rob) arr.append(robInverse) return True, arr return False, arr def sampling_withinD(self, robot, D, numSampling, eexy, ee1Flag): minMax = self.get_min_max_len() numSeg = self.get_num_segment() grapple_point = self.get_grapple_points() limitAngle = Angle(radians=D[0]) limitLength = D[1] # read robot angle and length robot_ang = robot.get_angle() robot_len = robot.get_length() # sampling angles angles = np.zeros((numSampling, numSeg)) lengths = np.zeros((numSampling, numSeg)) for i in range(numSeg): tmpAng = np.random.rand(1,numSampling)*limitAngle.in_degrees()*2 \ - limitAngle.in_degrees() +robot_ang[i].in_degrees() if i == 0: tmpAng[tmpAng > 180] = 180 tmpAng[tmpAng < -180] = -180 angles[:, i] = tmpAng else: tmpAng[tmpAng > 165] = 165 tmpAng[tmpAng < -165] = -165 angles[:, i] = tmpAng # # sampling length if (minMax[1][i] - minMax[0][i]) != 0: tmp = np.random.rand( 1, numSampling) * (D[1] * 2) - D[1] + robot_len[i] tmp[tmp > minMax[1][i]] = minMax[1][i] tmp[tmp < minMax[0][i]] = minMax[0][i] else: tmp = np.zeros((1, numSampling)) + robot_len[i] lengths[:, i] = tmp # grapple grapples = [] if ee1Flag: grapples_tmp = np.zeros((1, numSampling)) else: grapples_tmp = np.ones((1, numSampling)) # grapples_tmp = (np.floor(np.random.rand(1,numSampling)*len(grapple_point))) for i in range(numSampling): grapples.append(list(eexy)) output = np.append(np.asarray(grapples), angles, axis=1) output = np.append(output, lengths, axis=1) grapples_tmp = grapples_tmp.reshape(numSampling, 1) output = np.append(output, grapples_tmp, axis=1) return output def assign_config(self, sample_config, id): numSeg = self.get_num_segment() x = sample_config[id][0] y = sample_config[id][1] angles = [] lengths = [] for i in range(numSeg): angles.append(Angle(degrees=sample_config[id][2 + i])) lengths.append(sample_config[id][2 + numSeg + i]) if (int(sample_config[id][-1]) == 0): return rob_conf_ee1(x, y, angles, lengths, ee1_grappled=True) else: return rob_conf_ee2(x, y, angles, lengths, ee2_grappled=True) def str2robotConfig(self, stringInput): ee1_xy_str, ee1_angles_str, lengths_str, ee1_grappled = stringInput.strip( ).split(';') ee1x, ee1y = tuple([float(i) for i in ee1_xy_str.split(' ')]) ee1_angles = [ Angle(degrees=float(i)) for i in ee1_angles_str.strip().split(' ') ] lengths = [float(i) for i in lengths_str.strip().split(' ')] if int(ee1_grappled) == 1: return rob_conf_ee1(ee1x, ee1y, ee1_angles, lengths, ee1_grappled=True) else: return rob_conf_ee2(ee1x, ee1y, ee1_angles, lengths, ee2_grappled=True) def run_EST(self, outPath): init = self.get_init_state() goal = self.get_goal_state() self.gInit.addVertex(str(init)) self.gGoal.addVertex(str(goal)) s = 100000 for i in range(s): added_m, flagInit = self.expandTree() connected, q = self.connectTree(added_m, flagInit) # haven't checked path if connected: # print(added_m) print("traverse from middle point back to init and goal") robot_config_list = self.traverseBack(flagInit, added_m, q) for rc in range(len(robot_config_list)): robot_config_list[rc] = robot_config_list[rc][:-3] write_robot_config_list_to_file(outPath, robot_config_list) return True return False # flagInit = 0 -> added_m in init, otherwise added_m in goal def traverseBack(self, flagInit, added_m, q): if flagInit == 0: path1 = self.traverse(self.gInit, added_m, 1) path2 = self.traverse(self.gGoal, q, 0) else: path1 = self.traverse(self.gInit, q, 1) path2 = self.traverse(self.gGoal, added_m, 0) out = [] out.extend(path1) out.extend(path2) return out def traverse(self, graph, node, reverseFlag): x = graph.getVertex(str(node)) statelist = [] while x.getParents() is not None: statelist.append(x.getId()) aa = x.getParents() x = graph.getVertex(x.getParents().getId()) # print(x.getParents()) statelist.append(x.getId()) if (reverseFlag == 1): arr = [] for i in reversed(statelist): arr.append(i) return arr return statelist def expandTree(self): k = 1 D = [0.4, 1e-2] tau = 0.4 pr = round(random.random()) T = self.gGoal if pr == 1 else self.gInit tester = test_robot(self) while True: prVertex = math.floor(random.random() * T.getNumbVertices()) mVertex = T.getVertex(T.getVerticeByInt(prVertex)) m = self.str2robotConfig(mVertex.getId()) # m need to become robot robot_conf = [] # robot_conf = self.sampling_withinD(m,D,k) for i in range(k): # print(robot_conf[i]) q = self.assign_config(robot_conf, i) # check q is collision or not if (tester.self_collision_test(q) ) and tester.test_config_distance_tau(m, q, self, tau): print(str(q)[:-3]) f = open("tmp_output.txt", "a") f.write(str(q)[:-3] + '\n') f.close() T.addEdge(str(m), str(q)) return q, pr # else: # output = self.obstacle_sampling(T,m,q,D,k,tester,tau) # if output is not None: # return output,pr def obstacle_sampling(self, T, m, q, D, k, tester, tau): q_test = self.sampling_withinD(q, D, k, m.get_HeadeePos(), m.ee1_grappled) for i in range(k): q_test_conf = self.assign_config(q_test, i) # find q_test in the distance of D from q if (tester.self_collision_test(q_test_conf) ) and tester.test_config_distance_tau(m, q_test_conf, self, tau): curNode = str(m) knNode = str(q_test_conf) if curNode[-1] == knNode[-1]: if int(curNode[-1]) == 1: if curNode.split(' ')[0] == knNode.split( ' ')[0] and curNode.split( ' ')[1] == knNode.split(' ')[1]: T.addEdge(str(m), str(q_test_conf)) return q_test_conf else: if curNode.split(' ')[0] == knNode.split( ' ')[0] and curNode.split( ' ')[1] == knNode.split(' ')[1]: T.addEdge(str(m), str(q_test_conf)) return q_test_conf else: # find middle point tmpA = np.asarray(q.str2list()) tmpB = np.asarray(q_test_conf.str2list()) tmpC = (tmpA + tmpB) / 2 midRobot = make_robot_config_with_arr( tmpA[0], tmpA[1], tmpC[2:(2 + self.num_segments)], tmpC[2 + self.num_segments:(2 + 2 * self.num_segments)], tmpA[-1]) if (tester.self_collision_test(midRobot) ) and tester.test_config_distance_tau( m, midRobot, self, tau): curNode = str(m) knNode = str(midRobot) if curNode[-1] == knNode[-1]: if int(curNode[-1]) == 1: if curNode.split(' ')[0] == knNode.split( ' ')[0] and curNode.split( ' ')[1] == knNode.split(' ')[1]: T.addEdge(str(m), str(midRobot)) return midRobot else: if curNode.split(' ')[0] == knNode.split( ' ')[0] and curNode.split( ' ')[1] == knNode.split(' ')[1]: T.addEdge(str(m), str(midRobot)) return midRobot # T.addEdge(str(m),str(midRobot)) # return midRobot return None def connectTree(self, added_m, flagInit): tester = test_robot(self) tau = 0.4 # check added_m in the other tree T = self.gInit if flagInit == 1 else self.gGoal visited = set() for i in range(T.getNumbVertices()): VertexTmp = T.getVertex(i) prVertex = math.floor(random.random() * T.getNumbVertices()) if (prVertex not in visited): visited.add(prVertex) mVertex = T.getVertex(T.getVerticeByInt(prVertex)) q = self.str2robotConfig(mVertex.getId()) # print("comp:",added_m) # print("other tree:",q) # should find the minimum q to calculate the distance, but not implement now if tester.test_config_distance_tau(added_m, q, self, tau): # print(added_m) # print(q) # self.combineTwoGraph(flagInit,added_m,q) return True, q return False, None def combineTwoGraph(self, flagInit, added_m, q): # added_m in the self tree initNode = added_m if flagInit == 0 else q goalNode = added_m if flagInit == 1 else q self.gInit.addEdge(str(initNode), str(goalNode)) goalTmp = self.gGoal.getVertex(str(goalNode)) while goalTmp.getParent(): self.gInit.addEdge(str(goalTmp), str(goalTmp.getParent())) goalTmp = self.gGoal.getVertex(goalTmp.getParent())
# Add edges for room_id in ad_list: neighbors = ad_list[room_id] for i in range(len(neighbors)): neighbor = neighbors[i] neighbor_direction = list(neighbor.keys()) neighbor_direction = neighbor_direction[0] neighbor_id = neighbor[neighbor_direction] g.add_edge(room_id, str(neighbor_id), neighbor_direction) # First graph sync g = Graph() sync_graph(g) # === Find nearest unvisited room === # Main function def find_nearest_unvisited(player, visited): room_id = player.cur_room neighbors = g.get_neighbors(room_id) q = Queue() # FORMAT OF QUEUE: [ [directions], [room_ids] ] # Initialize queue for direction in neighbors: if neighbors[direction] == '-1': # Return to main calling function
# Seed the random number generator for reproducible results random.seed(seed) # Start player in the first room player = Player(world.starting_room) # Will be filled with directions to walk traversal_path = [] # Keep track of visited rooms so we know when we've visited them all visited_rooms = set() visited_rooms.add(player.current_room) # Initialize a graph to track rooms and connections between them graph = Graph() graph.add_room(player.current_room.id, player.current_room.get_exits()) backtracked = False # Track whether player has returned from a dead end # Loop until all rooms have been visited while len(visited_rooms) != len(room_graph): # Get a list of unvisited exits from the current location exits = graph.get_connected_rooms(player.current_room.id, visited=False) # If there are exits if exits: # Store current room for connecting to the next room current_room = player.current_room
# player.current_room.id <- returns the room id # player.current_room.get_exits() <- returns the availble exits from the current room (['n', 's', ...]) # player.travel('n') <- Input a direction and move to that room # room.get_room_in_direction('n') <- Input a direction and get the room id that's connected or None # Shape of the graph (based on test_cross map) # { # 0: {'n': 1, 's': 5, 'w': 7, 'e': 3}, <- Room 0 has 4 connected rooms # 1: {'n': 2, 's': 0}, <- Room 1 has 2 connected rooms # 2: {'s': 1}, <- Room 2 has 1 connected room # ... # 8: {'e': 7} <- Room 8 has 1 connected room # } # FIRST: Explore all rooms and populate the graph graph = Graph() # Add starting room starting_room = world.starting_room # graph.add_vertex(starting_room.id) stack = Stack() stack.push(starting_room) visited = set() # Continue until we have seen all rooms and the stack is empty while stack.size() > 0: room = stack.pop() # returns a <Room> class instance, not a room id room_id = room.id if room_id not in graph.vertices: graph.add_vertex(room_id) # Get connected rooms connected_rooms = room.get_exits() # returns an array of directions for direction in connected_rooms:
q.enqueue([(player.current_room, d)]) visited = set() while q.size: path = q.dequeue() curr_room = path[-1][0] if '?' in gr.rooms[curr_room].values(): return [d for _, d in path][1:] elif curr_room not in visited: visited.add(curr_room) for direction in curr_room.get_exits(): next_room = curr_room.get_room_in_direction(direction) q.enqueue(path + [(next_room, direction)]) return None gr = Graph() gr.add_vertex() while True: if not any('?' in d.values() for d in gr.rooms.values()): break linear_dir = gr.go_in_direction_until_dead_end(player.current_room) get_current_room(linear_dir) traversal_path += linear_dir path_to_unexplored_room = find_unexplored_room() if path_to_unexplored_room is not None: traversal_path += path_to_unexplored_room get_current_room(path_to_unexplored_room) # TRAVERSAL TEST visited_rooms = set()
import sys if len(sys.argv) < 2: print 'usage: infer_kmeans.py path_to_trips/' sys.exit(0) # load traces traces = read_traces(sys.argv[1]) # get initial markers markers_by_trace = get_markers(traces, SEED_DISTANCE) flat_markers = [ marker for trace_markers in markers_by_trace for marker in trace_markers ] # initialize clusters and run k-means initial_clusters = initialize_clusters(flat_markers, DISTANCE_THRESHOLD, BEARING_THRESHOLD) clusters = kmeans(flat_markers, initial_clusters, 2 * DISTANCE_THRESHOLD, MOVEMENT_THRESHOLD) # extract road network graph = Graph() for cluster in clusters: cluster.vertex = graph.add_vertex(cluster.x, cluster.y) generate_edges(graph, markers_by_trace, clusters) # output graph graph.write('kmeans-inferred.graph')
def __init__(self, input_file): super(EST, self).__init__(input_file) self.gInit = Graph() self.gGoal = Graph() self.Setting = self.caseSetting()
# You may uncomment the smaller graphs for development and testing purposes. # map_file = "maps/test_line.txt" # map_file = "maps/test_cross.txt" # map_file = "maps/test_loop.txt" # map_file = "maps/test_loop_fork.txt" map_file = "maps/main_maze.txt" # Loads the map into a dictionary room_graph = literal_eval(open(map_file, "r").read()) world.load_graph(room_graph) # Print an ASCII map world.print_rooms() player = Player(world.starting_room) graph = Graph() # Populate graph by traversing through all the rooms using a depth first traversal def dft(): #Create Stack stack = Stack() #Put the starting point in the stack stack.push(world.starting_room) # Create a set to keep track of where we've been visited = set() #While the stack is not empty while stack.size() > 0: # grabs room instance off of stack room = stack.pop()
from util import Queue, inverse_order, Graph from map_file import room_graph g = Graph() traversal_path = [] g.create_world(room_graph) def travel(travel_array): ''' Helper function to collect directions ''' # create an empty list path = [] # enumerate the list for index, room in enumerate(travel_array): # shave front and last if index > len(travel_array) - 2: return path # check if for d in g.rooms[room]: if g.rooms[room][d] == travel_array[index + 1]: path.append(d) def bfs(rooms_id, target): """ Return a list containing the shortest path from starting_vertex to destination_vertex in breath-first order.
from urls import post, get, end from util import Graph from mine import mine import json import os global data data = get(end['init']) global snitch snitch = False if data['room_id'] < 500 else True gr = Graph() map_file = 'map.json' if snitch == False else 'map2.json' with open(map_file) as map: completed_map = json.load(map) for room in completed_map: if completed_map[room] == data['room_id']: data = completed_map[room] gr.add_vertex(completed_map[room]) def exits(): global data all_exits = data['exits'] print('Exits: [', end='') for i, x in enumerate(all_exits): room_id = gr.rooms[data['room_id']]['exits'][x] room_title = gr.rooms[room_id]['title'] terrain = gr.rooms[room_id]['terrain'] if i + 1 == len(all_exits):