Pygame Details
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:
-
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=Falseorcolor=BLACKto clarify the meaning of these arguments. -
Find the bounding rectangle for the text.
txtrect = txt.get_rect() -
Create the positioning rectangle by moving the bounding rectangle’s
(x,y)orcenter. In this example, I place the rectangle in the bottom center of the screen by matching thecenterxandbottom.screenrect = screen.get_rect() txtrect.centerx = screenrect.centerx txtrect.bottom = screenrect.bottom -
The
blitfunction copies the text (or any other surface) onto the screen. This function’s name is very old.screen.blit(txt, txtrect)