【计算几何】两条线段是否相交

#!/usr/bin/python3

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


# line segment p1p2, p3p4 intersect or not
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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值