How to identify the values of indexes around a specific array coordinate?
<p>If I had a 2-D array, representing a world, that looked something like: </p>

<pre><code>. . . . . . . . . . . . . . .
. P . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . t . . . . . . . . .
. . . . . . t . . . . . . . .
. . . . . . . t . . . . . . .
. . . . . . . t t . . . . . .
. . . . . m . . . . . . . . .
. . . . . . m m . . . . . . .
. . . . . . . . m m . . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . m . . . .
. . . . . . . . . . . m . . .
. . . . . . . . . . . . . . .
</code></pre>

<p><code>m</code> stands for <code>mountains</code>, <code>t</code> for <code>trees</code> and <code>P</code> for <code>Player</code>.</p>

<p>Now, let's say we have a <code>Player</code> class that tracks the <code>userpos</code> or user position in an array, which is currently <code>(1, 1)</code>:</p>

<pre><code>class Player(object):
    def __init__(self, x, y, array):
        self.x = x
        self.y = y
        self.userpos = array[x][y] 
</code></pre>

<p>If I were to write a method inside of the <code>Player</code> class that deals with basic movement controls to edit the location of the <code>P</code> value inside of the array, how could I go about tracking the 8 tiles around the <code>P</code> value? For example, we can see all of the tiles around the current <code>player</code> <code>userpos</code> is all <code>.</code>'s. </p>

<p>I want to restrict the player from moving onto <code>m</code> tiles, being that they are mountains. It is easy to identify the current tile with the <code>userpos</code> variable, since the <code>P</code> value is only added to a string version of the map, and not the actual array. However, the issue comes from trying to move the player to a previous position. I want to be able to return the player to the nearest <code>empty</code> or <code>.</code> tile, but do not know how to decide what index inside of the array that the player should be moved to.  </p>

<p>Is there an easier way of doing this, or would tracking the tiles around the player be the easiest way?</p>

<p>Since you got the x and y and the original array, you should be able to iterate through this points with code like:</p>

<pre><code>tiles_to_move = []
for i in range(x-1, x+2):
    for j in range(y-1, y+2):
         if i != x or j != y:
             if array[i][j] != 'm': # depends on how you manage your array
                 tiles_to_move.append([i, j])
</code></pre>

<p>and use the tiles stored in <code>tiles_to_move</code> to determine your next optional move.</p>

python arrays python-2.7 multidimensional-array