class Point:
def __init__(self, x, y):
self._x = x
self._y = y
class Vector:
def __init__(self, p1: Point, p2: Point):
self._x = p2._x - p1._x
self._y = p2._y - p1._y
def Cross(va: Vector, vb: Vector):
return va._x * vb._y - va._y * vb._x
def Direction(p1, p2, p3):
v1 = Vector(p1, p2)
v2 = Vector(p1, p3)
return Cross(v1, v2)
def OnSegment(p1: Point, p2: Point, p3: Point):
if (
p3._x <= max(p1._x, p2._x)
and p3._x >= min(p1._x, p2._x)
and p3._y <= max(p1._y, p2._y)
and p3._y >= min(p1._y, p2._y)
):
return True
else:
return False
def Intersect(p1, p2, p3, p4):
d1 = Direction(p1, p2, p3)
d2 = Direction(p1, p2, p4)
d3 = Direction(p3, p4, p1)
d4 = Direction(p3, p4, p2)
if d1 * d2 < 0 and d3 * d4 < 0:
return True
if d1 == 0 and OnSegment(p1, p2, p3):
return True
if d2 == 0 and OnSegment(p1, p2, p4):
return True
if d3 == 0 and OnSegment(p3, p4, p1):
return True
if d4 == 0 and OnSegment(p3, p4, p2):
return True
return False
def main():
p0 = Point(0, 0)
p1 = Point(1, 1)
p2 = Point(1, 0)
p3 = Point(0, 1)
p4 = Point(1, 1)
p5 = Point(2, 3)
p6 = Point(-1, -1)
p7 = Point(-0.5, -0.5)
p8 = Point(-1, 0)
p9 = Point(0, -1)
print(Intersect(p0, p1, p2, p3))
print(Intersect(p0, p1, p4, p5))
print(Intersect(p0, p1, p6, p7))
print(Intersect(p0, p1, p8, p9))
if __name__ == "__main__":
main()