Detecting Units on a Grid

Posted by hammythepig on Game Development See other posts from Game Development or by hammythepig
Published on 2012-06-20T19:07:48Z Indexed on 2012/06/20 21:26 UTC
Read the original article Hit count: 293

Filed under:
|
|

I am making a little turn based strategy game in pygame, that uses a grid system as the main map to hold all the characters and the map layout. (Similar to Fire Emblem, or Advance Wars)

I am trying to determine a way to quickly and efficiently (i.e. without too much of a slow down) check if there are any characters within a given range of the currently selected character.

So to illustrate:

O = currently selected character
X = squares within range

Range of 1:

    X
  X O X
    X

Range of 2:

     X
   X X X
 X X O X X
   X X X
     X

Range of 3:

      X
    X X X
  X X X X X
X X X O X X X
  X X X X X
    X X X
      X

Now I have to tell the user who is in range, and I have to let the user choose who to attack if there are multiple enemies in range.

If I have a 5x5 grid, filled with " " for empty and numbers for the characters:

[ ][ ][ ][ ][4]
[ ][1][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][2][3][ ]
[ ][ ][ ][ ][ ]

Depending on which character the user selects, I would like to show the user which other characters are in range. So if they all had a range of 3:

  • 1 can hit 2
  • 2 can hit 1 or 3
  • 3 can hit 2
  • 4 cannot hit anyone.

So, How do I quickly and/or efficiently run though my grid and tell the user where the enemies are?

PS- As a bonus, if someone could give an answer that could also work for a minimum distance type range, I would give them a pat on the back and a high five, should they ever travel to Canada and we ever meet in life.

For example: Range of 3 to 5: (- is out of range)

          X
        X X X
      X X X X X
    X X X - X X X
  X X X - - - X X X
X X X - - O - - X X X
  X X X - - - X X X
    X X X - X X X
      X X X X X
        X X X
          X

© Game Development or respective owner

Related posts about python

Related posts about pygame