Many objects in a game can be treated as simple rectangles, rather than their actual shape. This simplifies code without noticeably affecting game play. Pygame has a rect object that makes it easy to work with game objects.
Table of Contents
Getting the screen rect object
We already have a screen object; we can easily access the rect object associated with the screen.
screen_rect = screen.get_rect()
Finding the center of the screen
Rect objects have a center attribute which stores the center point.
screen_center = screen_rect.center
Useful rect attributes
Once you have a rect object, there are a number of attributes that
are useful when positioning objects and detecting relative positions
of objects. (You can find more attributes in the Pygame
documentation.)
#Individual x and y values: screen_rect.left, screen_rect.right screen_rect.top, screen_rect.bottom screen_rect.centerx, screen_rect.centery screen_rect.width, screen_rect.height # Tuples screen_rect.center screen_rect.size
Creating a rect object
You can create a rect object from scratch. For example a small rect object that’s filled in can represent a bullet in a game. The Rect() class takes the coordinates of the upper left corner, and the width and height of the rect. The draw.rect() function takes a screen object, a color, and a rect. This function fills the given rect with the given color.
bullet_rect = pg.Rect(100, 100, 3, 15)
color = (100, 100, 100)
pg.draw.rect(screen, color, bullet_rect)