A little background:
I’m writing a small word based maze game starting with a simple maze made of X’s, O’s and F.
My maze is a list of lists representing the maze itself where X is a wall, O is an open spot and F is the finish line.
I’m trying to write a function that takes the name of the maze and the user’s current position and returns a list of all legal moves from that position (N, S, E, or W).
Here’s my practice maze and function.
def get_legal_directions(maze, position):
x = position[0]
y = position[1]
legal = []
if maze[x-1][y] == 'O' or maze[x-1][y] == 'F':
legal.append('N')
if maze[x+1][y] == 'O' or maze[x+1][y] == 'F':
legal.append('S')
if maze[x][y+1] == 'O' or maze[x][y+1] == 'F':
legal.append('E')
if maze[x][y-1] == 'O' or maze[x][y-1] == 'F':
legal.append('W')
return legal
>>> maze1 = [['X', 'X', 'X', 'X', 'X'], ['X', 'O', 'X', 'F', 'X'], ['X', 'O', 'X', 'O', 'X'], ['X', 'O', 'O', 'O', 'X'], ['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X']]
>>>
input: get_legal_directions(maze1, (1,1))
output: ['S']
so the function appears to work normally here, however when I use the function within another function in order for the user to interact with the maze, I get this:
def interact():
maze = raw_input('Maze File: ')
x = maze[0]
y = maze[1]
pos = (1,1)
history = [pos]
while 1:
print 'You are at position', pos
command = raw_input('Command: ')
if command == 'Q':
com = raw_input('Are you sure you want to quit? [y] or [n]: ')
if com =='y':
print 'Thank you for playing - Goodbye!'
break
else: continue
elif command == 'L':
get_legal_directions(maze, pos)
else: print 'invalid command'
I get the following:
>>> interact()
Maze File: maze1
You are at position (1, 1)
Command: L
" if maze[x-1][y] == 'O' or maze[x-1][y] == 'F':
IndexError: string index out of range"
Is there something wrong with the way I’ve written the if statement or is it something else? Thanks to anyone who can help.
How can I get the command L to call the function get_legal_directions()?
This makes maze a string:
Your function expects a list of lists instead.