Недавно я ссылался на некоторые другие посты, в которых даются указания, как найти перекрытие между двумя разными прямоугольниками.Я хотел бы одновременно показать картинку с использованием моих кодов, чтобы показать область перекрытия между двумя прямоугольниками.
Коды:
class Rectangle:
def __init__(self, left_x = 0, right_x = 0, bottom_y = 0, upper_y = 0):
self.left_x = left_x
self.right_x = right_x
self.bottom_y = bottom_y
self.upper_y = upper_y
def deter_intersect(self, second):
if self.left_x > second.right_x or self.right_x < second.left_x:
return False
if self.bottom_y > second.upper_y or self.upper_y < second.bottom_y:
return False
return True
def inner_intersect(self, second):
if not self.deter_intersect(second):
return Rectangle()
left_x = max(self.left_x, second.left_x)
right_x = min(self.right_x, second.right_x)
bottom_y = max(self.bottom_y, second.bottom_y)
upper_y = min(self.upper_y, second.upper_y)
return left_x, right_x, bottom_y, upper_y
def outer_intersect(self, second):
if not self.deter_intersect(second):
return Rectangle()
left_x = min(self.left_x, second.left_x)
right_x = max(self.right_x, second.right_x)
bottom_y = min(self.bottom_y, second.bottom_y)
upper_y = max(self.upper_y, second.upper_y)
return left_x, right_x, bottom_y, upper_y
def __str__(self):
return "Rectangle({self.left_x},{self.right_x},{self.bottom_y},{self.upper_y})".format(self=self)
def area(self):
return (self.right_x - self.left_x) * (self.upper_y - self.bottom_y)
if __name__ == "__main__":
first_rectangle = Rectangle(5,10,5,10)
second_rectangle = Rectangle(5,15,5,15)
print(first_rectangle.deter_intersect(second_rectangle))
print(first_rectangle.outer_intersect(second_rectangle))