-
Notifications
You must be signed in to change notification settings - Fork 0
/
p1.py
173 lines (146 loc) · 6.52 KB
/
p1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
import queue
def dijkstras_shortest_path(initial_position, destination, graph, adj):
frontier = queue.PriorityQueue()
frontier.put(initial_position, 0)
visited = []
visited.append(initial_position)
came_from = {}
cost_so_far = {}
came_from[initial_position] = None
cost_so_far[initial_position] = 0
while not frontier.empty():
current = frontier.get()
if current == destination:
break
for neighbor in adj(graph,current):
if neighbor in visited: continue
new_cost = cost_so_far[current] + neighbor[1]
if neighbor[0] not in visited or new_cost < cost_so_far[neighbor[0]]:
cost_so_far[neighbor[0]] = new_cost
frontier.put(neighbor[0], new_cost)
visited.append(neighbor[0])
came_from[neighbor[0]] = current
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initial_position: The initial cell from which the path extends.
destination: The end location for the path.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
If a path exits, return a list containing all cells from initial_position to destination.
Otherwise, return None.
"""
print(came_from[destination])
#now create a list backtracking the path from came_from
result_path = []
cursor=destination
while cursor is not initial_position:
result_path.append(cursor)
cursor=came_from[cursor]
return result_path
pass
def dijkstras_shortest_path_to_all(initial_position, graph, adj):
frontier = queue.PriorityQueue()
frontier.put(initial_position, 0)
visited = []
visited.append(initial_position)
came_from = {}
cost_so_far = {}
came_from[initial_position] = None
cost_so_far[initial_position] = 0
while not frontier.empty():
current = frontier.get()
for neighbor in adj(graph,current):
if neighbor in visited: continue
new_cost = cost_so_far[current] + neighbor[1]
if neighbor[0] not in visited or new_cost < cost_so_far[neighbor[0]]:
cost_so_far[neighbor[0]] = new_cost
frontier.put(neighbor[0], new_cost)
visited.append(neighbor[0])
came_from[neighbor[0]] = current
""" Calculates the minimum cost to every reachable cell in a graph from the initial_position.
Args:
initial_position: The initial cell from which the path extends.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
A dictionary, mapping destination cells to the cost of a path from the initial_position.
"""
return cost_so_far
pass
def navigation_edges(level, cell):
# A cell is a 'tuple' that is used to store an x/y coordinate
dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
diags = [[1, -1], [1, 1], [-1, 1], [-1, -1]]
result = []
#basic directions
for currdir in dirs:
neighborpos = (cell[0] + currdir[0], cell[1] + currdir[1])
if neighborpos in level['spaces']:
neighbor = (neighborpos, (level['spaces'][neighborpos]/2)+(level['spaces'][cell]/2))
result.append(neighbor)
#diagonals
for currdir in diags:
neighborpos = (cell[0] + currdir[0], cell[1] + currdir[1])
if neighborpos in level['spaces']:
neighbor = (neighborpos, (((level['spaces'][neighborpos])*(sqrt(2))/2)+((level['spaces'][cell])*(sqrt(2))/2)))
result.append(neighbor)
""" Provides a list of adjacent cells and their respective costs from the given cell.
Args:
level: A loaded level, containing walls, spaces, and waypoints.
cell: A target location.
Returns:
A list of tuples containing an adjacent cell's coordinates and the cost of the edge joining it and the
originating cell.
E.g. from (0,0):
[((0,1), 1),
((1,0), 1),
((1,1), 1.4142135623730951),
... ]
"""
return result
pass
def test_route(filename, src_waypoint, dst_waypoint):
""" Loads a level, searches for a path between the given waypoints, and displays the result.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
dst_waypoint: The character associated with the destination waypoint.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source and destination coordinates from the level.
src = level['waypoints'][src_waypoint]
dst = level['waypoints'][dst_waypoint]
# Search for and display the path from src to dst.
path = dijkstras_shortest_path(src, dst, level, navigation_edges)
if path:
show_level(level, path)
else:
print("No path possible!")
def cost_to_all_cells(filename, src_waypoint, output_filename):
""" Loads a level, calculates the cost to all reachable cells from
src_waypoint, then saves the result in a csv file with name output_filename.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
output_filename: The filename for the output csv file.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source coordinates from the level.
src = level['waypoints'][src_waypoint]
# Calculate the cost to all reachable cells from src and save to a csv file.
costs_to_all_cells = dijkstras_shortest_path_to_all(src, level, navigation_edges)
save_level_costs(level, costs_to_all_cells, output_filename)
if __name__ == '__main__':
filename, src_waypoint, dst_waypoint = 'example.txt', 'a', 'e'
# Use this function call to find the route between two waypoints.
test_route(filename, src_waypoint, dst_waypoint)
# Use this function to calculate the cost to all reachable cells from an origin point.
cost_to_all_cells(filename, src_waypoint, 'my_costs.csv')