Last active
April 11, 2018 16:29
-
-
Save 20esaua/672cca2a0db98daf15d038898366f29d to your computer and use it in GitHub Desktop.
An automatic maze solver thing I wrote in python while in CS160 class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# enter in the maze content in ascii here | |
maze = [list('######################'), | |
list('#S #### # # ##'), | |
list('## #### # ##### ### ##'), | |
list('## # ###E##'), | |
list('####### ####### ######'), | |
list('## # ### ##'), | |
list('## ######## ##### ##'), | |
list('## ####### ##### ##'), | |
list('## ## ##'), | |
list('######################') | |
] | |
# define characters to control maze | |
wall = '#' | |
start = 'S' | |
end = 'E' | |
# these will be automatically calculated, leave them alone | |
position_start = [0, 0] | |
position_end = [0, 0] | |
alreadytested = list() | |
# find start position | |
for y in range(0, len(maze)): | |
for x in range(0, len(maze[y])): | |
if maze[y][x] == start: | |
position_start = [x, y] | |
break | |
# walk a position in the maze | |
def walk(pos): | |
x = pos[0] | |
y = pos[1] | |
# make record that x,y was tested, and make new combinations to test | |
alreadytested.append([x, y]) | |
totest = [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] | |
# basic checks | |
if maze[y][x] == end: | |
global position_end | |
position_end = [x, y] | |
return True | |
elif maze[y][x] == wall: | |
return False | |
else: | |
maze[y][x] = 'X' | |
# loop through each combination of walking in xy direction | |
for test in totest: | |
x = test[0] | |
y = test[1] | |
# check if the x and y values are in range and if so, try walking them | |
if y >= 0 and y < len(maze) and x >= 0 and x < len(maze[y]) and maze[y][x] != wall and not [x, y] in alreadytested: | |
if walk([x, y]): | |
maze[y][x] = '.' | |
return True | |
return False | |
# solve maze | |
solvable = walk(position_start) | |
maze[position_start[1]][position_start[0]] = start | |
if solvable: | |
print('Maze solved!') | |
maze[position_end[1]][position_end[0]] = end | |
else: | |
print('Maze not solved!') | |
# print out maze solution | |
for row in maze: | |
content = '' | |
for c in row: | |
content += c | |
print(content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment