Skip to main content
Engineering LibreTexts

3.13: Rect Objects

  • Page ID
    14421
  • Pygame has two ways to represent rectangular areas (just like there are two ways to represent colors). The first is a tuple of four integers:

    1. The X coordinate of the top left corner.
    2. The Y coordinate of the top left corner.
    3. The width (in pixels) of the rectangle.
    4. Then height (in pixels) of the rectangle.

    The second way is as a pygame.Rect object, which we will call Rect objects for short. For example, the code below creates a Rect object with a top left corner at (10, 20) that is 200 pixels wide and 300 pixels tall:

    >>> import pygame
    >>> spamRect = pygame.Rect(10, 20, 200, 300)
    >>> spamRect == (10, 20, 200, 300)
    True
    

    The handy thing about this is that the Rect object automatically calculates the coordinates for other features of the rectangle. For example, if you need to know the X coordinate of the right edge of the pygame.Rect object we stored in the spamRect variable, you can just access the Rect object’s right attribute:

    >>> spamRect.right
    210
    

    The Pygame code for the Rect object automatically calculated that if the left edge is at the X coordinate 10 and the rectangle is 200 pixels wide, then the right edge must be at the X coordinate 210. If you reassign the right attribute, all the other attributes are automatically recalculated:

    >>>  spam.right = 350
    >>>  spam.left
    150

    Here’s a list of all the attributes that pygame.Rect objects provide (in our example, the variable where the Rect object is stored in a variable named myRect):

    Attribute Name Description
    myRect.left The int value of the X-coordinate of the left side of the rectangle.
    myRect.right The int value of the X-coordinate of the right side of the rectangle.
    myRect.top The int value of the Y-coordinate of the top side of the rectangle.
    myRect.bottom The int value of the Y-coordinate of the bottom side
    myRect.centerx The int value of the X-coordinate of the center of the rectangle.
    myRect.centery The int value of the Y-coordinate of the center of the rectangle.
    myRect.width The int value of the width of the rectangle.
    myRect.height The int value of the height of the rectangle.
    myRect.size A tuple of two ints: (width, height)
    myRect.topleft A tuple of two ints: (left, top)
    myRect.topright A tuple of two ints: (right, top)
    myRect.bottomleft A tuple of two ints: (left, bottom)
    myRect.bottomright A tuple of two ints: (right, bottom)
    myRect.midleft A tuple of two ints: (left, centery)
    myRect.midright A tuple of two ints: (right, centery)
    myRect.midtop A tuple of two ints: (centerx, top)
    myRect.midbottom A tuple of two ints: (centerx, bottom)
    • Was this article helpful?