這篇文章主要介紹了Python判斷直線和矩形是否相交的方法,涉及Python坐標系下的直線與矩形相關運算,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python判斷直線和矩形是否相交的方法。分享給大家供大家參考。具體實現方法如下:
- """
- A(ax,ay),B(px,py)為兩個點 (x1,y1),(x2,y2)為矩形的左上角和右下角坐標 ,判斷A,B兩點是否和矩形相交
- """
- def Judge(ax, ay, px, py, x1, y1, x2, y2):
- #轉換為真除法
- ax, ay, px, py = float(ax), float(ay), float(px), float(py)
- x1, y1, x2, y2 = float(x1), float(y1), float(x2), float(y2)
- #判斷矩形上邊線和兩點直線相交的點
- sx = (y1 - ay) * (px - ax) / (py - ay) + ax
- if sx >= x1 and sx <= x2:
- return True
- #判斷矩形下邊線和兩點直線相交的點
- xx = (y1 - ay) * (px - ax) / (py - ay) + ax
- if sx >= x1 and sx <= x2:
- return True
- #判斷矩形左邊線和兩點直線相交的點
- zy = (y2 - ay) * (x2 - ax) / (px - ax) + ay
- if zy >= y1 and zy <= y2:
- return True
- #判斷矩形右邊線和兩點直線相交的點
- yy = (y2 - ay) * (x2 - ax) / (px - ax) + ay
- if yy <= y1 and yy >= y2:
- return True
- return False
- ax = raw_input()
- ay = input()
- px = input()
- py = input()
- x1 = input()
- y1 = input()
- x2 = input()
- y2 = input()
- print Judge(ax, ay, px, py, x1, y1, x2, y2)
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答