Skip to content

All Days Complete #765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 56 additions & 4 deletions projects/adventure/adv.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,32 @@
# Load world
world = World()

class Stack():
def __init__(self):
self.stack = []

def push(self, value):
self.stack.append(value)

def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None

def size(self):
return len(self.stack)


# 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"
map_file = "projects/adventure/maps/main_maze.txt"

# Loads the map into a dictionary
room_graph=literal_eval(open(map_file, "r").read())
room_graph = literal_eval(open(map_file, "r").read())
world.load_graph(room_graph)

# Print an ASCII map
Expand All @@ -29,7 +45,44 @@
# traversal_path = ['n', 'n']
traversal_path = []


def travelers_path(direction):
# save our route back to unvisited exits
if direction == 'n':
return 's'
elif direction == 's':
return 'n'
elif direction == 'e':
return 'w'
elif direction == 'w':
return 'e'


paths = Stack()
visited = set()
# comparing visited to len of rooms to ensure a complete traversal
while len(visited) < len(world.rooms):

exits = player.current_room.get_exits()
print('Room:', player.current_room)
print('exits are', exits)
path = []
for exit in exits:
if exit is not None and player.current_room.get_room_in_direction(exit) not in visited:
# if exit exists and we haven't visited
path.append(exit)
print(path, '<~ path')
visited.add(player.current_room)
if len(path) > 0:
move = random.randint(0, len(path) - 1) # pick index of move (1 of up to 4)
paths.push(path[move])
player.travel(path[move])
traversal_path.append(path[move])
print('more rooms to explore')
else:
end = paths.pop()
player.travel(travelers_path(end))
traversal_path.append(travelers_path(end))
print('this is the end of this path')

# TRAVERSAL TEST
visited_rooms = set()
Expand All @@ -47,7 +100,6 @@
print(f"{len(room_graph) - len(visited_rooms)} unvisited rooms")



#######
# UNCOMMENT TO WALK AROUND
#######
Expand Down
1 change: 1 addition & 0 deletions projects/adventure/player.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Player:
def __init__(self, starting_room):
self.current_room = starting_room

def travel(self, direction, show_rooms = False):
next_room = self.current_room.get_room_in_direction(direction)
if next_room is not None:
Expand Down
7 changes: 7 additions & 0 deletions projects/adventure/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ def __init__(self, name, description, id=0, x=None, y=None):
self.w_to = None
self.x = x
self.y = y

def __str__(self):
return f"\n-------------------\n\n{self.name}\n\n {self.description}\n\n{self.get_exits_string()}\n"

def print_room_description(self, player):
print(str(self))

def get_exits(self):
exits = []
if self.n_to is not None:
Expand All @@ -26,8 +29,10 @@ def get_exits(self):
if self.e_to is not None:
exits.append("e")
return exits

def get_exits_string(self):
return f"Exits: [{', '.join(self.get_exits())}]"

def connect_rooms(self, direction, connecting_room):
if direction == "n":
self.n_to = connecting_room
Expand All @@ -44,6 +49,7 @@ def connect_rooms(self, direction, connecting_room):
else:
print("INVALID ROOM CONNECTION")
return None

def get_room_in_direction(self, direction):
if direction == "n":
return self.n_to
Expand All @@ -55,5 +61,6 @@ def get_room_in_direction(self, direction):
return self.w_to
else:
return None

def get_coords(self):
return [self.x, self.y]
1 change: 1 addition & 0 deletions projects/adventure/world.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ def __init__(self):
self.rooms = {}
self.room_grid = []
self.grid_size = 0

def load_graph(self, room_graph):
num_rooms = len(room_graph)
rooms = [None] * num_rooms
Expand Down
31 changes: 30 additions & 1 deletion projects/ancestor/ancestor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
from collections import deque

def earliest_ancestor(ancestors, starting_node):
pass
parents_for_child = {}

# Create a graph with IDs as vertices and child->parent relationships as edges
for relationship in ancestors:
parent = relationship[0]
child = relationship[1]
if child not in parents_for_child:
parents_for_child[child] = set()
parents_for_child[child].add(parent)

earliest_ancestor = -1

# Perform a Breadth-First Search on the graph and return the last ancestor found
queue = deque()
queue.append(starting_node)
while len(queue) > 0:
curr_vertex = queue.popleft()
if curr_vertex in parents_for_child:
parent_with_lowest_ID = None
for parent in parents_for_child[curr_vertex]:
if parent_with_lowest_ID is None:
parent_with_lowest_ID = parent
elif parent < parent_with_lowest_ID:
parent_with_lowest_ID = parent
queue.append(parent)
if parent_with_lowest_ID is not None:
earliest_ancestor = parent_with_lowest_ID

return earliest_ancestor
140 changes: 87 additions & 53 deletions projects/graph/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,79 +2,113 @@
Simple graph implementation
"""
from util import Stack, Queue # These may come in handy
from collections import deque

class Graph:

"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}

def __repr__(self):
return str(self.vertices)

def add_vertex(self, vertex_id):
"""
Add a vertex to the graph.
"""
pass # TODO
self.vertices[vertex_id] = set()

def add_edge(self, v1, v2):
"""
Add a directed edge to the graph.
"""
pass # TODO
if v1 not in self.vertices or v2 not in self.vertices:
return
self.vertices[v1].add(v2)

def get_neighbors(self, vertex_id):
"""
Get all neighbors (edges) of a vertex.
"""
pass # TODO
return self.vertices[vertex_id] if vertex_id in self.vertices else None

def bft(self, starting_vertex):
"""
Print each vertex in breadth-first order
beginning from starting_vertex.
"""
pass # TODO
visited = set()
queue = deque()
queue.append(starting_vertex)
while len(queue) > 0:
currNode = queue.popleft()
if currNode not in visited:
visited.add(currNode)
print(currNode)
for neighbor in self.get_neighbors(currNode):
queue.append(neighbor)

def dft(self, starting_vertex):
"""
Print each vertex in depth-first order
beginning from starting_vertex.
"""
pass # TODO

def dft_recursive(self, starting_vertex):
"""
Print each vertex in depth-first order
beginning from starting_vertex.

This should be done using recursion.
"""
pass # TODO
def dft(self, starting_vertex):
visited = set()
stack = deque()
stack.append(starting_vertex)
while len(stack) > 0:
currNode = stack.pop()
if currNode not in visited:
visited.add(currNode)
print(currNode)
for neighbor in self.vertices[currNode]:
stack.append(neighbor)

def dft_recursive(self, starting_vertex, path=[]):
path += [starting_vertex]
print(starting_vertex)
for neighbor in self.get_neighbors(starting_vertex):
if neighbor not in path:
self.dft_recursive(neighbor, path)

def bfs(self, starting_vertex, destination_vertex):
"""
Return a list containing the shortest path from
starting_vertex to destination_vertex in
breath-first order.
"""
pass # TODO
visited = set()
queue = Queue()
queue.enqueue({'current_vertex': starting_vertex, 'path': [starting_vertex]})
while queue.size() > 0:
currNode = queue.dequeue()
curr_path = currNode['path']
curr_vertex = currNode['current_vertex']
if curr_vertex not in visited:
if curr_vertex == destination_vertex:
return curr_path
visited.add(curr_vertex)
for neighbor in self.get_neighbors(curr_vertex):
new_path = list(curr_path)
new_path.append(neighbor)
queue.enqueue({'current_vertex': neighbor, 'path': new_path})


def dfs(self, starting_vertex, destination_vertex):
"""
Return a list containing a path from
starting_vertex to destination_vertex in
depth-first order.
"""
pass # TODO

def dfs_recursive(self, starting_vertex, destination_vertex):
"""
Return a list containing a path from
starting_vertex to destination_vertex in
depth-first order.

This should be done using recursion.
"""
pass # TODO
visited = set()
stack = deque()
# Push the current path you're on onto the stack, instead of just a single vertex
stack.append([starting_vertex])
while len(stack) > 0:
currPath = stack.pop()
currNode = currPath[-1] # the current node you're on is the last node in the path
if currNode == destination_vertex:
return currPath
if currNode not in visited:
visited.add(currNode)
for neighbor in self.vertices[currNode]:
newPath = list(currPath) # make a copy of the current path
newPath.append(neighbor)
stack.append(newPath)

def dfs_recursive(self, starting_vertex, destination_vertex, visited=None, path=None):
if visited is None:
visited = set()
if path is None:
path = []

visited.add(starting_vertex)
path = path + [starting_vertex] # makes a copy of the existing path

if starting_vertex == destination_vertex:
return path

for neighbor in self.get_neighbors(starting_vertex):
if neighbor not in visited:
new_path = self.dfs_recursive(neighbor, destination_vertex, visited, path)
if new_path is not None:
return new_path
return None

if __name__ == '__main__':
graph = Graph() # Instantiate your graph
Expand Down
Loading