PyGame Basics
Display text on screen
To display some words on screen, we create some text objects and add them to the screen. Then upate the screen to show the changes by using either display_surf.blit()
and pygame.display.flip()
or update()
.
Font
To draw text on screen, we need to create the font object.
With the font, we can now set our font object:
class Game():
def __init__(self):
pygame.init() # initialises Pygame libraries
self.display = pygame.display.set_mode((WIDTH, HEIGHT))
self.disp_surf = self.init_display()
self.size = WIDTH, HEIGHT
self.running = True if self.disp_surf else False
self.font = pygame.font.Font(pygame.font.get_default_font(), 36)
return
Font Colour
Let's set our RGB colour for our welcome screen font:
# R G B
BLACK = ( 0, 0, 0)
GREEN = ( 3, 192, 60)
We can now render our text's surface, or in other words generate our image/sprite object.
We'll first create a function that takes the text to display, colour of text and the center position of the text.
def draw_text(self, text, colour, center):
'''Draws text onto diplay surface'''
text_surf = self.font.render(text, True, colour)
And retrieve the rectangle object for our surface:
def draw_text(self, text, colour, center):
'''Draws text onto diplay surface'''
text_surf = self.font.render(text, True, colour)
text_rect = text_surf.get_rect()
To set the position of our object, let us put it at center of out display surface:
def draw_text(self, text, colour, center):
'''Draws text onto diplay surface'''
text_surf = self.font.render(text, True, colour)
text_rect = text_surf.get_rect()
text_rect.center = center
We then have to place it into our draw buffer.
blit
stands for BLock Image Tranfser. It transfers the created image of our text onto our display surface.
def draw_text(self, text, colour, center):
'''Draws text onto diplay surface'''
text_surf = self.font.render(text, True, colour)
text_rect = text_surf.get_rect()
text_rect.center = center
self.disp_surf.blit(text_surf, text_rect)
Then we just can just call the function:
def render(self):
'''Render surface'''
self.disp_surf.fill(BLACK)
# Draw text
self.draw_text("PyGame Basics", GREEN, (int(WIDTH/2), int(HEIGHT/2)))
It will be updated to the screen when we flip()
:
# Blit everything to screen
self.display.blit(self.disp_surf, (0,0))
pygame.display.flip()
Give it a try, you should end up with green text on black background.
python3 -m game