-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmaze.py
executable file
·92 lines (70 loc) · 2.47 KB
/
maze.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
from PIL import Image
import dijkstra as d
from math import inf as infinity
import argparse
# Black
COLOR_WALL = (0, 0, 0)
# White
COLOR_PATH = (255, 255, 255)
# Red
COLOR_START = (255, 0, 0)
# Green
COLOR_END = (0, 255, 0)
# Blue
COLOR_SOLVED = (0, 0, 255)
def color_matches(color_1, color_2):
return color_1[0] == color_2[0] and color_1[1] == color_2[1] and color_1[2] == color_2[2]
def is_wall(pixel):
return color_matches(pixel, COLOR_WALL)
def is_path(pixel):
return color_matches(pixel, COLOR_PATH)
def is_start(pixel):
return color_matches(pixel, COLOR_START)
def is_end(pixel):
return color_matches(pixel, COLOR_END)
parser = argparse.ArgumentParser(description="Solve input PNG maze file")
parser.add_argument("-i", "--input", help="Maze file. Defaults to maze.png",
default="maze.png", required=False)
parser.add_argument("-o", "--output", default="solved.png",
help="PNG file to output to. Defaults to solved.png")
args = parser.parse_args()
try:
image = Image.open(args.input)
pixels = image.load()
except:
print("Could not load file", args.input)
exit()
nodes = [[None for _ in range(image.width)] for __ in range(image.height)]
for x in range(image.width):
for y in range(image.height):
pixel = pixels[x, y]
if is_wall(pixel):
nodes[y][x] = None
else:
nodes[y][x] = d.Node(x, y)
if is_start(pixel):
initial_coords = (x, y)
if is_end(pixel):
destination_coords = (x, y)
graph = d.Graph(nodes, initial_coords, destination_coords)
destination_distance = d.dijkstra(graph)
initial_node = graph.graph[initial_coords[1]][initial_coords[0]]
destination_node = graph.graph[destination_coords[1]][destination_coords[0]]
nodes = graph.get_nodes()
for node in nodes:
if node:
node.visited = False
current_node = destination_node
smallest_tentative_distance = destination_distance
# Go from destination node to initial node to find path
while current_node is not initial_node:
neighbors = graph.get_neighbors(current_node)
for neighbor in neighbors:
if not neighbor or neighbor.visited:
continue
if neighbor.tentative_distance < smallest_tentative_distance:
smallest_tentative_distance = neighbor.tentative_distance
neighbor.visited = True
current_node = neighbor
pixels[current_node.x, current_node.y] = COLOR_SOLVED
image.save(args.output, "PNG")