所以我有一个这种形式的矩形:
class Rect: # used for the tunneling algorithm
def __init__(self, x, y, w, h):
self.x1 = x
self.y1 = y
self.x2 = x + w
self.y2 = y + h
def center(self):
center_x = (self.x1 + self.x2) // 2
center_y = (self.y1 + self.y2) // 2
return center_x, center_y
def intersect(self, other):
# returns true if this rectangle intersects with another one
return (self.x1 <= other.x2 and self.x2 >= other.x1 and
self.y1 <= other.y2 and self.y2 >= other.y1)
我一直在尝试从任何墙上(包括角落)获取任何点并将其作为 x, y 值传递。矩形只有这些值:坐标 x 和 y、宽度和高度。
通常,对于任何类型的二维数组来获取所有值(包括角点,即使它们重复),我会这样做:
alist=[arr[0,:], arr[:,-1], arr[-1,:], arr[:,0]]
这基本上会给我从中选择的值,但在这种特殊情况下,我只使用 4 个值,并且我不知道如何在不必重新创建整个矩形二维数组的情况下执行此操作。
请注意,整个矩形本身位于一个更大的数组中,并且所述坐标来自那里,但我希望它尽可能独立。
最佳答案
如果您想生成矩形的所有整数坐标,一种方法是在 Rect
类中实现 __getitem__
方法:
def __getitem__(self, k):
def iteritem(k, kmin, kmax):
if isinstance(k, int):
yield kmin + k if k >= 0 else kmax + k
elif isinstance(k, slice):
for i in range(k.start or kmin, k.stop or kmax, k.step or 1):
yield i
if isinstance(k, tuple) and len(k) == 2:
result = []
for i in iteritem(k[0], self.x1, self.x2):
for j in iteritem(k[1], self.y1, self.y2):
result.append((i, j))
return result
这会产生任何类型的坐标范围:
>>> r = Rect(10, 20, 5, 4)
左上角:
>>> r[0,0]
[(10, 20)]
右下角:
>>> r[-1,-1]
[(14, 23)]
顶行:
>>> r[0,:]
[(10, 20), (10, 21), (10, 22), (10, 23)]
所有坐标:
>>> r[:,:]
[(10, 20), (10, 21), (10, 22), (10, 23), (11, 20), (11, 21), (11, 22), (11, 23), (12, 20), (12, 21), (12, 22), (12, 23), (13, 20), (13, 21), (13, 22), (13, 23), (14, 20), (14, 21), (14, 22), (14, 23)]
边界坐标:
>>> r[0,:] + r[:,-1] + r[-1,:] + r[:,0]
[(10, 20), (10, 21), (10, 22), (10, 23), (10, 23), (11, 23), (12, 23), (13, 23), (14, 23), (14, 20), (14, 21), (14, 22), (14, 23), (10, 20), (11, 20), (12, 20), (13, 20), (14, 20)]
关于Python从二维数组中的矩形中获取随机墙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51945758/