Python判断直线和矩形是否相交的方法

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Django 后台获取文件列表 InMemoryUploadedFile的例子

在使用Django项目中,From表单提交了图片集合 var formdata = new FormData(); formdata.append("csrfmiddlewareto...

IntelliJ IDEA安装运行python插件方法

IntelliJ IDEA安装运行python插件方法

IDEA 工具是我们常用的开发工具,全称:IntelliJ IDEA,它的功能强大就在于我们可以添加各种插件来编写不同的代码,当然也可以用来编写python,这篇文章我们来讲解,如何用I...

python实现监控linux性能及进程消耗性能的方法

本文以实例形式实现了python监控linux性能以及进程消耗性能的方法,具体实现代码如下: # -*- coding: utf-8 -*- """ Created on Tue J...

Python下singleton模式的实现方法

很多开发人员在刚开始学Python 时,都考虑过像 c++ 那样来实现 singleton 模式,但后来会发现 c++ 是 c++,Python 是 Python,不能简单的进行模仿。...

python通过定义一个类实例作为ftp回调方法

本文实例讲述了python通过定义一个类实例作为ftp回调方法。分享给大家供大家参考。具体实现方法如下: class Writer: def __init__(self, fil...