Skip to content
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

still working on graph.py, need to do the dfs and dfs recursive. #750

Open
wants to merge 11 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
36 changes: 36 additions & 0 deletions lecture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Queue(object):
"""
docstring
"""

def __init__(self):
self.queue = []

def enqueue(self, value):
self.queue.append(value)

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

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


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)
82 changes: 82 additions & 0 deletions lecture3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
islands = [
[0, 1, 0, 1, 0],
[1, 1, 0, 1, 1],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 0],
[1, 1, 0, 0, 0]
]


def island_counter(islands):
# create a way to keep track of visited nodes
visited = []
for _ in range(len(islands)):
new_row = [False] * len(islands[0])
visited.append(new_row)

# print(visited)

island_count = 0
# walk through each
for row in range(len(islands)):
for col in range(len(islands[0])):
# if it is not visited
if not visited[row][col]:
# if its a 1:
if islands[row][col] == 1:
# do a traversal
dft(row, col, islands, visited)
# increment the counter
island_count += 1
return island_count


def dft(row, col, islands, visited):
s = []

s.append((row, col))

while len(s) > 0:
v = s.pop()
row, col = v
if not visited[row][col]:
visited[row][col] = True

for neighbor in get_neighbors(row, col, islands):
s.append(neighbor)

# what are the neighbors of (1,3)


def get_neighbors(row, col, islands):
neighbors = []
# check north
if row > 0 and islands[row-1][col] == 1:
neighbors.append((row-1, col))
# check south
if row < len(islands) - 1 and islands[row+1][col] == 1:
neighbors.append((row+1, col))
# check west
if col > 0 and islands[row][col-1] == 1:
neighbors.append((row, col-1))
# check east
if col < len(islands) - 1 and islands[row][col+1] == 1:
neighbors.append((row, col+1))

return neighbors


print(island_counter(islands)) # returns 4


"""
When is DFS better?
- might find the longest path
- if you suspect the target is deep within the graph
- if the target node is a leaf
- can be implemented recursively, or randomly

When is BFS better?
- might find the shortest path

"""
209 changes: 195 additions & 14 deletions projects/adventure/adv.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,200 @@
map_file = "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
# Print an ASCII map
world.print_rooms()

player = Player(world.starting_room)

# Fill this out with directions to walk
# traversal_path = ['n', 'n']
traversal_path = []


def bfs(starting_vertex):
q = []
visit = []
path = [starting_vertex]
travel = []
q.append(path)
# is the node in graph
# while queue isn't empty
while len(q) > 0:
# dequeue the node at the front of the line
current_path = q.pop(0)
# print("current path", current_path)
current_node = current_path[-1]
# print(current_node, "starting node")
# print("current_node bfs", current_node)
# if this node is a target node, return true
if has_exits(current_node):
# print("current_path return", current_path)
# traversal_path.extend(travel)
return current_path

# return current_path
if current_node not in visit:
visit.append(current_node)
# neighbors =
neighbors = [i for i in graph[current_node]]
# print("neighbors", neighbors)
for i in neighbors:
# if graph[current_node][i] < current_node:
# print("available", current_path + [graph[current_node][i]])
q.append(current_path + [graph[current_node][i]])
# else:
# continue
# else:
# print("BAHAHA", has_exits(current_node))


def has_exits(vertex):
free = []
for key, value in graph[vertex].items():
# print(key, value, "vertex", vertex)
if value == "?":
free.append(key)
if len(free) > 0:
# print("free", free)
return free
return False


traversal_path = []
graph = {}
current = player.current_room.id
visited = []
nodes = []
last = ''

s = []
s.append(current)
print(current, "current")
print(len(world.rooms))

while len(visited) != len(world.rooms):
vertex = s.pop()
nodes.append(vertex)
# print("vertex", vertex)
exits = player.current_room.get_exits()
index = random.randint(0, len(exits)-1)
random_dir = exits[index]
free_exits = []

if vertex not in visited:
graph[vertex] = {}
visited.append(vertex)
# print("visited", visited)
for i in exits:
graph[vertex][i] = "?"
if len(traversal_path) > 0:
last = traversal_path[-1]
# print("traversal path", traversal_path)
# print("Nodes", nodes)
if last == "n":
if graph[vertex]['s'] == "?":
graph[vertex]['s'] = nodes[-2]
elif last == "s":
if graph[vertex]['n'] == "?":
graph[vertex]['n'] = nodes[-2]
elif last == "w":
if graph[vertex]['e'] == "?":
graph[vertex]['e'] = nodes[-2]
elif last == "e":
if graph[vertex]['w'] == "?":
graph[vertex]['w'] = nodes[-2]
for i in exits:
if graph[vertex][i] == "?":
free_exits.append(i)
# print("free exits", free_exits)
if len(free_exits) > 1:
index = random.randint(0, len(free_exits)-1)
random_dir = free_exits[index]
player.travel(random_dir)
traversal_path.append(random_dir)
graph[vertex][random_dir] = player.current_room.id
s.append(player.current_room.id)
elif len(free_exits) == 1:
player.travel(free_exits[0])
traversal_path.append(free_exits[0])
graph[vertex][free_exits[0]] = player.current_room.id
s.append(player.current_room.id)
else:
if len(visited) == len(world.rooms):
break

new_vertex = bfs(player.current_room.id)
# print(graph)
for i in range(len(new_vertex)-1):
# print(new_vertex[i], "i top")
for key, value in graph[new_vertex[i]].items():
# print('x top', key, value)
if value == new_vertex[i+1]:
# print(traversal_path, value, new_vertex[i+1], "before")
player.travel(key)
traversal_path.append(key)
# print(traversal_path, "after")
# print("new vertex", new_vertex)
# print("breaking new vertex top", new_vertex)
# print(len(visited))
# print("traversal length", len(traversal_path))
s.append(new_vertex[-1])
else:
if len(traversal_path) > 0:
last = traversal_path[-1]
if last == "n":
if graph[vertex]['s'] == "?":
graph[vertex]['s'] = nodes[-2]
elif last == "s":
if graph[vertex]['n'] == "?":
graph[vertex]['n'] = nodes[-2]
elif last == "w":
if graph[vertex]['e'] == "?":
graph[vertex]['e'] = nodes[-2]
elif last == "e":
if graph[vertex]['w'] == "?":
graph[vertex]['w'] = nodes[-2]
for i in exits:
if graph[vertex][i] == "?":
free_exits.append(i)
if len(free_exits) > 1:
index = random.randint(0, len(free_exits)-1)
random_dir = free_exits[index]
player.travel(random_dir)
traversal_path.append(random_dir)
graph[vertex][random_dir] = player.current_room.id
s.append(player.current_room.id)
elif len(free_exits) == 1:
player.travel(free_exits[0])
traversal_path.append(free_exits[0])
graph[vertex][free_exits[0]] = player.current_room.id
s.append(player.current_room.id)
else:
# find an open exit vertex and travel there.
if len(visited) == len(world.rooms):
break
new_vertex = bfs(player.current_room.id)
for i in range(len(new_vertex)-1):
# print(new_vertex[i], "i top")
for key, value in graph[new_vertex[i]].items():
# print('x top', key, value)
if value == new_vertex[i+1]:
# print(traversal_path, "before")
player.travel(key)
traversal_path.append(key)
# print(traversal_path, "after")
# print("breaking new vertex bottom", new_vertex)
# print(graph)
# print(len(visited))
s.append(new_vertex[-1])


# print("final graph", graph)
print("final len visited", len(visited))
print("final len rooms", len(world.rooms))
# print(has_exits(graph[0])

# TRAVERSAL TEST
visited_rooms = set()
Expand All @@ -41,22 +222,22 @@
visited_rooms.add(player.current_room)

if len(visited_rooms) == len(room_graph):
print(f"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited")
print(
f"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited")
else:
print("TESTS FAILED: INCOMPLETE TRAVERSAL")
print(f"{len(room_graph) - len(visited_rooms)} unvisited rooms")



#######
# UNCOMMENT TO WALK AROUND
#######
player.current_room.print_room_description(player)
while True:
cmds = input("-> ").lower().split(" ")
if cmds[0] in ["n", "s", "e", "w"]:
player.travel(cmds[0], True)
elif cmds[0] == "q":
break
else:
print("I did not understand that command.")
# player.current_room.print_room_description(player)
# while True:
# cmds = input("-> ").lower().split(" ")
# if cmds[0] in ["n", "s", "e", "w"]:
# player.travel(cmds[0], True)
# elif cmds[0] == "q":
# break
# else:
# print("I did not understand that command.")
Empty file added projects/adventure/fresh.py
Empty file.
Loading