# WARNING: Soulless OOP Ahead
# So lifeless that all it does is follow the wall.
# Even a Dementor could find their way out of a labyrinth.
class Maze:
@staticmethod
def preprocess(maze):
total, chunk = len(maze), int(len(maze)**.5)
return [maze[i:i + chunk] for i in range(0, total, chunk)]
def __init__(self, maze):
self.maze = self.preprocess(maze)
self.x_dim = len(self.maze[-1])
self.y_dim = len(self.maze)
def is_wall(self, pos):
x, y = pos
return not (-1 < x < self.x_dim) or \
not (-1 < y < self.y_dim) or \
self.maze[y][x]
class Mouse:
compass = [
lambda x, y: (x, y-1),
lambda x, y: (x+1, y),
lambda x, y: (x, y+1),
lambda x, y: (x-1, y),
]
def __init__(self):
self.x, self.y = 0, 0
self.direction = 1
self.moves = []
def turn_right(self):
self.direction = (self.direction+1)%4
def turn_left(self):
self.direction = (self.direction-1)%4
def block_ahead(self):
return self.compass[self.direction](self.x, self.y)
def block_on_right(self):
return self.compass[(self.direction+1)%4](self.x, self.y)
def move(self):
next_move = self.block_ahead()
self.moves += [self.direction+1]
self.x, self.y = next_move
def at_end(self, maze):
return (self.x, self.y) == (maze.x_dim-1, maze.y_dim-1)
def solve_maze(self, maze):
while not self.at_end(maze):
if not maze.is_wall(self.block_on_right()):
self.turn_right()
self.move()
elif maze.is_wall(self.block_ahead()):
self.turn_left()
else:
self.move()
def entry(maze):
mouse = Mouse()
maze = Maze(maze)
mouse.solve_maze(maze)
return mouse.moves
post a comment