pygame.Rect

Rect stores a rectangle's position and size and offers dozens of helpers for moving, aligning, clamping and collision testing. It is the most-used class in Pygame.

2 min readUpdated
On this page

Overview#

A pygame.Rect holds four integers: x, y, width and height. Sprites use a Rect for their position, the draw functions accept Rects, and collision code relies on them. Rects store whole numbers; fractions are discarded when you assign them.

Constructors#

Python
pygame.Rect(left, top, width, height)
pygame.Rect((left, top), (width, height))
pygame.Rect(other_rect_or_object_with_rect_attribute)
image.get_rect(center=(320, 240))       # common: a Rect sized to an image

Virtual attributes#

Reading or assigning any of these moves (or resizes) the rect, keeping the size (or position) consistent:

PositionSize
x, y, left, top, right, bottomwidth, height, w, h, size
topleft, topright, bottomleft, bottomright
midtop, midbottom, midleft, midright
center, centerx, centery

right equals left + width, which is one pixel past the last pixel inside the rect. The same applies to bottom.

Methods#

MethodReturns / does
move(x, y) / move_ip(x, y)New moved Rect / moves this Rect in place (_ip = in place).
inflate(x, y) / inflate_ipGrows or shrinks around the centre.
scale_by(x, y=None)Scales the size around the centre.
clamp(rect) / clamp_ipMoves the rect fully inside another.
clip(rect)The overlapping area (size 0 if none).
union(rect) / unionall(list)The smallest rect containing both / all.
fit(rect)Scales and moves to fit inside another while keeping aspect ratio.
contains(rect)True if the other rect is completely inside.
collidepoint(x, y)True if the point is inside.
colliderect(rect)True if the rects overlap.
collidelist(list) / collidelistall(list)Index of the first hit (or -1) / indexes of all hits.
collidedict(dict) / collidedictall(dict)Same for dictionaries keyed or valued by rects.
clipline(x1, y1, x2, y2)The part of a line segment inside the rect, or an empty tuple.
copy()An independent copy.

Practical example#

rect_example.pyDownload
"""pygame.Rect: virtual attributes, moving, clamping, inflating and collision helpers."""
import pygame

r = pygame.Rect(10, 20, 100, 50)          # x, y, width, height
print(r.topleft, r.bottomright, r.center, r.size)   # (10, 20) (110, 70) (60, 45) (100, 50)

r.center = (200, 200)                      # assigning a virtual attribute moves the rect
print(r)                                   # Rect(150, 175, 100, 50)  (pygame prints <rect(...)>)

moved = r.move(10, 0)                      # returns a new Rect; r is unchanged
r.move_ip(10, 0)                           # _ip = "in place": changes r itself
print(moved == r)                          # True

bigger = r.inflate(20, 20)                 # grows around the centre
print(bigger.size, bigger.center == r.center)

screen_rect = pygame.Rect(0, 0, 640, 480)
outside = pygame.Rect(600, 450, 100, 100)
print(outside.clamp(screen_rect))          # moved back inside: Rect(540, 380, 100, 100)

a = pygame.Rect(0, 0, 50, 50)
b = pygame.Rect(40, 40, 50, 50)
print(a.colliderect(b), a.clip(b))         # True Rect(40, 40, 10, 10)
print(a.collidepoint(25, 25), a.collidepoint(50, 50))  # True False (right/bottom edges are outside)
walls = [pygame.Rect(100, 0, 10, 10), pygame.Rect(45, 45, 10, 10)]
print(a.collidelist(walls), a.collidelistall(walls))   # 1 [1]
print(pygame.Rect(0, 0, 10, 10).union(pygame.Rect(20, 20, 10, 10)))  # Rect(0, 0, 30, 30)

Common errors#

  • Objects don't move at slow speeds: adding 0.4 to rect.x rounds away. Keep a float position and assign rect.x = round(x), or use pygame-ce's FRect.
  • Aliasing: b = a makes both names refer to the same Rect, so moving b moves a. Use a.copy().
  • Edge-touching counts as no collision: rects that only share a border don't collide, by design.
  • Negative sizes: Rect(10, 10, -5, 20) is allowed but most methods misbehave. Call normalize() first.

pygame-ce notes#

pygame-ce adds pygame.FRect, with the same API but floating-point values, which simplifies smooth movement. It also adds Rect.move_to(**kwargs). Code using these requires pygame-ce.

Official documentation#

↑ ↓ to moveEnter to openEsc to close