Skip to content

Instantly share code, notes, and snippets.

@somnathrakshit
Last active August 4, 2016 05:13
Show Gist options
  • Save somnathrakshit/40040994b23f16cd857a897196ce8354 to your computer and use it in GitHub Desktop.
Save somnathrakshit/40040994b23f16cd857a897196ce8354 to your computer and use it in GitHub Desktop.
Rat in a Maze
#!/usr/bin/env python3
'''This code should actually work with any ASCII maze that contains spaces for open paths, and a S, and E for
start and ending points. characters representing borders are redundant.
Create a text file containing the maze and type the name of the file as input
while running this code.
'''
'''
Main method in which the program starts
'''
def main():
location = [] #list to hold the location we are at in the maze
hasNoEnd = True
mazefile = input("What maze do you want solved?: ")
maze = slurp(mazefile)
for y in range(0, len(maze)):
for x in range(0, len(maze[y])):
if maze[y][x] == 'S':
location = [y, x]
elif maze[y][x] == 'E':
hasNoEnd = False
if len(location) == 0:
raise Exception("No start cell found, check your input file")
if hasNoEnd:
raise Exception("Maze has no end, unsolvable.")
tick(maze, location[0], location[1])
print("\n\n")
dump(maze)
'''
Loads the maze file into a matrix and returns it.
@param mazefile: Location of maze file
'''
def slurp(mazefile):
infile = open(mazefile, 'r')
#Split the maze into a matrix.
maze = [list(row) for row in infile.read().splitlines()] #this line is beautiful. python is definately a powerful language.
infile.close()
return maze
'''
Prints the loaded maze matrix into a human readable format.
@param maze: Loaded maze matrix.
'''
def dump(maze):
print('\n'.join(''.join(row) for row in maze)) #I had fun writing this too :P
'''
Recursive method which solves the maze.
@param maze: the maze matrix
@param y: the y location
@param x: the x location
'''
def tick(maze, y, x):
dump(maze)
print("\n")
if maze[y][x] in (' ', 'S'):
maze[y][x] = 'x'
#check right, down, left, up
if (tick(maze, y, x+1) or tick(maze, y-1, x) or
tick(maze, y, x-1) or tick(maze, y+1, x)):
maze[y][x] = '.'
return True
elif maze[y][x] == 'E':
return True #start peeling back.
return False
'''
Start the main method if this program is run as main.
'''
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment