Question

I am a newbie in python. Can some one tell me how can I check a small rectangle (with two coordinates) is inside another Rectangle(with two coordinates) in Python.

Was it helpful?

Solution 2

If you are working on a game. I suggest you use Pygame. I assume you are talking about collision checking for the use of sprite rectangles? Anyway here's an algorithm to check for collision between two rectangles. I am not writing a function for you to copy paste and use it in your program. This is just logic for you to understand and for you to write a piece of code by yourself to write from this logic depending on your application.

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;
}

OTHER TIPS

You could write something like

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

However, the exact code depends on the encoding of your rectangle. I am assuming that each rectangle is defined by two points in the upper left ((x1|y1)) and lower right corner ((x2|y2)) and that your rectangles are not rotated.

If you use a tuple (such as ((1,2),(2,4))) as your representation of rectangles, you will have to access the fields by index. I highly recommend that you use named tuples (http://docs.python.org/2/library/collections.html#collections.namedtuple).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top