Accessing the 8 elements surrounding an index in a 2D grid array

When attempting to do things such as implementing a 2D path-finding algorithm, you are required at times to access the 8 surrounding tiles of the tile you are currently working on and get or set properties of those tiles. This is easy, right? Increment/decrement x and y index values of the array as needed, e.g., increment x by one, increment y by one, increment x and y by one etc.

This is illustrated in the professionally drawn picture below:

DSC_0112

The first (terrible) method of achieving this that comes to mind is to just use 8 statements to check each element individually like so (I will just use C# syntax but this can, of course work in any other language):

//mapArr is the 2D array that we are working with here for illustrative purposes
//left tile
mapArr[unit_x-1,unit_y];
//right tile
mapArr[unit_x+1,unit_y];
//top tile
mapArr[unit_x,unit_y-1];
//bottom tile
mapArr[unit_x,unit_y+1];
//top left tile
mapArr[unit_x-1,unit_y-1];
//top right tile
mapArr[unit_x+1,unit_y-1];
//bottom left tile
mapArr[unit_x-1,unit_y+1];
//bottom right tile
mapArr[unit_x+1,unit_y+1];

Just typing that without any of the “if statement checking” that would likely need to accompany this is TIRING and TEDIOUS.

Other than that though, what is so terrible about doing this?

1) It’s very easy to make a mistake while copy-pasting the same line over and over again and then editing it.
2) it looks TERRIBLE and makes your code far longer than it needs to be.
3) If you need to make a change to this code at a later point, you will have to go and make changes at each one of these 8 chunks…

A better solution would be to use a nested for loop:

for (int x = -1; x < 2; x++)
   for (int y = -1; y < 2; y++)
   {
       mapArr[unit_x + x, unit_y + y];
   }

See how nice and clean that looks?

The only potential problem with this is that it does not only access the 8 surrounding tiles. It also accesses the central tile (when both x and y are equal to zero). This may or may not be a problem. If it is, you can simply add an if statement to check for that scenario:

for (int x = -1; x < 2; x++)
   for (int y = -1; y < 2; y++)
  {
       if( !(x == 0 && y == 0);
       mapArr[unit_x + x, unit_y + y];  
  }
Share

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.