Pygame Details

Important, useful details for programming in PyGame.

Rectangle Positioning

You can control the size and location of a Rect by using these attributes:

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

For example, begin by creating a 30x20 rectangle whose upper left is at the origin.

r = pygame.rect.Rect(0,0,30,20)

Moving the center to (150, 100) is simple:

r.center = (150,100)

Making the rectangle 60 pixels high:

r.height = 60

(I don’t think just setting the height will keep the rectangle centered. I think the upper left is the anchor point that doesn’t change.)

Text Drawing

I use a global variable for the “font”, set up in the init() routine.

global font
font = pygame.font.Font(size=36)

Drawing requires several steps:

  1. Render the text using the font. This creates a Surface.

     BLACK = pygame.color.Color('black') # usually a global
     txt = font.render("WORDS", False, BLACK)
    

    Unfortunately, you cannot use keywords like antialias=False or color=BLACK to clarify the meaning of these arguments.

  2. Find the bounding rectangle for the text.

     txtrect = txt.get_rect()
    
  3. Create the positioning rectangle by moving the bounding rectangle’s (x,y) or center. In this example, I place the rectangle in the bottom center of the screen by matching the centerx and bottom.

     screenrect = screen.get_rect()
     txtrect.centerx = screenrect.centerx
     txtrect.bottom = screenrect.bottom
    
  4. The blit function copies the text (or any other surface) onto the screen. This function’s name is very old.

     screen.blit(txt, txtrect)
    
Last modified October 24, 2023: Key starting information for PyGame. (c75c78a)