在python中检查矩形内的矩形

时间:2014-01-22 06:25:39

标签: python rectangles

我是python中的新手。 有人可以告诉我如何在Python中检查一个小矩形(有两个坐标)在另一个Rectangle(有两个坐标)内。

2 个答案:

答案 0 :(得分:2)

你可以写点像

def contains(r1, r2):
   return r1.x1 < r2.x1 < r2.x2 < r1.x2 and r1.y1 < r2.y1 < r2.y2 < r1.y2

但是,确切的代码取决于矩形的编码。我假设每个矩形由左上角((x1|y1))和右下角((x2|y2))中的两个点定义,并且矩形不会旋转。

如果使用元组(例如((1,2),(2,4)))作为矩形的表示,则必须按索引访问字段。我强烈建议您使用命名元组(http://docs.python.org/2/library/collections.html#collections.namedtuple)。

答案 1 :(得分:2)

如果您正在开发游戏。我建议你使用Pygame。我假设您正在讨论使用精灵矩形的碰撞检查?无论如何这里是一个检查两个矩形之间碰撞的算法。我没有为您编写一个函数来复制粘贴并在程序中使用它。这只是您理解的逻辑,也是您自己编写一段代码,根据您的应用程序从这个逻辑中编写的。

def check_collision(  A,  B )
{

#If any of the sides from A are outside of B
if( bottomA <= topB )
{
    return false;
}

if( topA >= bottomB )
{
    return false;
}

if( rightA <= leftB )
{
    return false;
}

if( leftA >= rightB )
{
    return false;
}

#If none of the sides from A are outside B
return true;
}
相关问题