1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Point: def __init__(self, x, y): self.x=x self.y=y
class Vector: def __init__(self, start_point, end_point): self.start_point, self.end_point = start_point, end_point self.x = end_point.x - start_point.x self.y = end_point.y - start_point.y def vector_negative(vector): return Vector(vector.end_point, vector.start_point)
def vector_product(vectorA, vectorB): return vectorA.x * vectorB.y - vectorB.x * vectorA.y
def isOverlap(A, B, C, D): P1 = Point(A[0], A[1]) P2 = Point(B[0], B[1]) Q1 = Point(C[0], C[1]) Q2 = Point(D[0], D[1])
if (max(P1.x, P2.x) >= min(Q1.x, Q2.x) and max(Q1.x, Q2.x) >= min(P1.x, P2.x) and max(P1.y, P2.y) >= min(Q1.y, Q2.y) and max(Q1.y, Q2.y) >= min(P1.y, P2.y)):
P1Q1 = Vector(P1, Q1) P1Q2 = Vector(P1, Q2) P2Q1 = Vector(P2, Q1) P2Q2 = Vector(P2, Q2) Q1P1 = vector_negative(P1Q1) Q1P2 = vector_negative(P2Q1) Q2P1 = vector_negative(P1Q2) Q2P2 = vector_negative(P2Q2) return (vector_product(P1Q1, P1Q2) * vector_product(P2Q1, P2Q2) <= 0) and (vector_product(Q1P1, Q1P2) * vector_product(Q2P1, Q2P2) <= 0) else: return False
print(isOverlap([1,1], [1,5], [0,1], [0,4])) print(isOverlap([0,0], [0,5], [1,1], [-1,4]))
|