-
Notifications
You must be signed in to change notification settings - Fork 2
/
solve.py
103 lines (78 loc) · 2.66 KB
/
solve.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
from PIL import Image
import time
from mazes import Maze
import bprofile
# Read command line arguments - the python argparse class is convenient here.
import argparse
def solve(method, input_file):
# Load Image
print ("Loading Image")
im = Image.open(input_file)
# Create the maze (and time it) - for many mazes this is more time consuming than solving the maze
print ("Creating Maze")
t0 = time.time()
maze = Maze(im)
t1 = time.time()
print ("Node Count:", maze.count)
total = t1-t0
print ("Time elapsed:", total)
# Create and run solver
[title, solver] = getSolver(method)
print ("Starting Solve:", title, " on image ", input_file)
t0 = time.time()
[result, stats] = solver(maze)
t1 = time.time()
total = t1-t0
# Print solve stats
print ("Nodes explored: ", stats[0])
if (stats[2]):
print ("Path found, length", stats[1])
else:
print ("No Path Found")
print ("Time elapsed: ", total)
print ("Saving Image\n")
im = im.convert('RGB')
impixels = im.load()
resultpath = [n.Position for n in result]
length = len(resultpath)
for i in range(0, length - 1):
a = resultpath[i]
b = resultpath[i+1]
# Blue - red
r = int((i / length) * 255)
px = (r, 0, 255 - r)
if a[0] == b[0]:
# Ys equal - horizontal line
for x in range(min(a[1],b[1]), max(a[1],b[1])):
impixels[x,a[0]] = px
elif a[1] == b[1]:
# Xs equal - vertical line
for y in range(min(a[0],b[0]), max(a[0],b[0]) + 1):
impixels[a[1],y] = px
im.save( input_file[:-4] +"_sol_"+ method +".png")
profiler = bprofile.BProfile('profiler.png')
def getSolver(method):
if method == "depthfirst":
import depthfirst
return ["Depth first search", depthfirst.solve]
elif method == "dijkstra":
import dijkstra
return ["Dijkstra's Algorithm", dijkstra.solve]
elif method == "astar":
import astar
return ["A-star Search", astar.solve]
else :
import breadthfirst
return ["Breadth first search", breadthfirst.solve]
def main():
Default = "breadthfirst"
Choices = ["breadthfirst","depthfirst","dijkstra", "astar"]
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--method", nargs='?', const=Default, default=Default, choices=Choices)
parser.add_argument("input_file")
args = parser.parse_args()
# The profiler generator a visual graph of the program during its execution.
with profiler:
solve(args.method, args.input_file)
if __name__ == "__main__":
main()