How to avoid IndexError
<p><strong>A little background:</strong></p>

<p>I'm writing a small word based maze game starting with a simple maze made of X's, O's and F.</p>

<p>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.</p>

<p>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).</p>

<p><strong>Here's my practice maze and function.</strong></p>

<pre><code>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


&gt;&gt;&gt; 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']]
&gt;&gt;&gt;
</code></pre>

<p>input: <code>get_legal_directions(maze1, (1,1))</code></p>

<p>output: <code>['S']</code></p>

<p>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:</p>

<pre><code>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'
</code></pre>

<p>I get the following:</p>

<pre><code>&gt;&gt;&gt; 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"
</code></pre>

<p>Is there something wrong with the way I've written the if statement or is it something else?  Thanks to anyone who can help.</p>

<p>How can I get the command <code>L</code> to call the function <code>get_legal_directions()</code>?</p>
