Python-Creating List Of Grid Positions Within A Certain Bound Given A Distance

two scenarios

I have an x axis size, a y axis size, a render distance, a list of grid position numbers and a central grid position.

I am trying to create a list of all the grid positions within the render distance of a central grid position.

The size of the x and y axis may be different independently. Optimally this algorithm would not attempt to get positions where the render distance extends over the side of the x or y axis.



I’m writing this to help you answer your own question in the style that I would go about it. As with anything in coding, what you need to do is be able to break down a big problem into multiple smaller ones.

  1. Design two functions to convert to and from (x, y) coordinates (optional, it’ll make your life easier, but won’t be as efficient, personally I would avoid this for a bit of a challenge).

  2. Given n, size and distance, calculate up, down, left and right. If the size is different for different axis, then just provide the function with the correct one.


def right(n, size, distance):
    return n + size * distance

def down(n, size, distance):
    return n - distance
  1. Given size, make sure the above functions don’t go off the edge of the grid. Converting the points to (x, y) coordinates for this part may help.

  2. Now you have the sides of the square, run the functions again to get the corners. For example, to get the top right corner, you could do right(up(*args)) or up(right(*args))

  3. With the corners, you can now calculate what’s in your square. Converting the points to (x, y) coordinates will make it easier.