使用两个左下角和右上角检查两个矩形是否在python中重叠

Gar*_*ich 10 python python-3.x

class Point:

    def __init__(self, xcoord=0, ycoord=0):
        self.x = xcoord
        self.y = ycoord

class Rectangle:
    def __init__(self, bottom_left, top_right, colour):
        self.bottom_left = bottom_left
        self.top_right = top_right
        self.colour = colour

    def intersects(self, other):
Run Code Online (Sandbox Code Playgroud)

我试图看看两个矩形是否基于右上角和左下角相交,但是当我创建函数时:

def intersects(self, other):
    return self.top_right.x>=other.top_right.x>=self.bottom_left.x and self.top_right.x>=other.bottom_left.x>=self.bottom_left.x and self.top_right.y>=other.top_right.y>=self.bottom_left.y and self.top_right.x>=other.bottom_left.x>=self.bottom_left.x
Run Code Online (Sandbox Code Playgroud)

输入时该函数将返回false:

r1=Rectangle(Point(1,1), Point(2,2), 'blue')
r3=Rectangle(Point(1.5,0), Point(1.7,3), 'red')
r1.intersects(r3)
Run Code Online (Sandbox Code Playgroud)

进壳.

sam*_*gak 16

您可以使用分离轴定理的简单版本来测试交点.如果矩形不相交,则右侧中的至少一个将位于另一个矩形的左侧的左侧(即,它将是分离轴),或反之亦然,或者顶侧中的一个将是在另一个矩形的底侧下方,反之亦然.

因此,更改测试以检查它们是否不相交:

def intersects(self, other):
    return not (self.top_right.x < other.bottom_left.x or self.bottom_left.x > other.top_right.x or self.top_right.y < other.bottom_left.y or self.bottom_left.y > other.top_right.y)
Run Code Online (Sandbox Code Playgroud)

此代码假定"top"具有比"bottom"更大的y值(y在屏幕下方减小),因为这就是您的示例似乎如何工作.如果您正在使用其他约定,那么您只需翻转y比较的符号.

  • 使用 self 作为 python 变量名是不是很混乱? (2认同)

小智 7

我最近遇到了这个问题,今天遇到了命名元组,所以我想我应该尝试一下:

from collections import namedtuple

RECT_NAMEDTUPLE = namedtuple('RECT_NAMEDTUPLE', 'x1 x2 y1 y2')

Rect1 = RECT_NAMEDTUPLE(10,100,40,80)
Rect2 = RECT_NAMEDTUPLE(20,210,10,60)

def overlap(rec1, rec2):
  if (rec2.x2 > rec1.x1 and rec2.x2 < rec1.x2) or \
     (rec2.x1 > rec1.x1 and rec2.x1 < rec1.x2):
    x_match = True
  else:
    x_match = False
  if (rec2.y2 > rec1.y1 and rec2.y2 < rec1.y2) or \
     (rec2.y1 > rec1.y1 and rec2.y1 < rec1.y2):
    y_match = True
  else:
    y_match = False
  if x_match and y_match:
    return True
  else:
    return False

print ("Overlap found?", overlap(Rect1, Rect2))

Overlap found? True

Run Code Online (Sandbox Code Playgroud)