If you want to draw text to the screen, you could write several calls to
pygame.draw.line() to draw out the lines of each letter. This would be a headache to type out all those
pygame.draw.line() calls and figure out all the XY coordinates, and probably wouldn’t look very good.
The above message would take forty one calls to the
pygame.draw.line() function to make. Instead, Pygame provides some much simpler functions for fonts and creating text. Here is a small Hello World program using Pygame’s font functions. Type it into IDLE’s file editor and save it as fonttext.py:
import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Hello World!') WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLUE = (0, 0, 128) fontObj = pygame.font.Font('freesansbold.ttf', 32) textSurfaceObj = fontObj.render('Hello world!', True, GREEN, BLUE) textRectObj = textSurfaceObj.get_rect() textRectObj.center = (200, 150) while True: # main game loop DISPLAYSURF.fill(WHITE) DISPLAYSURF.blit(textSurfaceObj, textRectObj) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
There are six steps to making text appear on the screen:
- Create a
pygame.font.Fontobject. (Like on line 12)
- Create a Surface object with the text drawn on it by calling the Font object’s
render()method. (Line 13)
- Create a Rect object from the Surface object by calling the Surface object’s
get_rect()method. (Line 14) This Rect object will have the width and height correctly set for the text that was rendered, but the top and left attributes will be
- Set the position of the Rect object by changing one of its attributes. On line 15, we set the center of the Rect object to be at 200, 150.
- Blit the Surface object with the text onto the Surface object returned by
pygame.display.set_mode(). (Line 19)
pygame.display.update()to make the display Surface appear on the screen. (Line 24)
The parameters to the
pygame.font.Font() constructor function is a string of the font file to use, and an integer of the size of the font (in points, like how word processors measure font size). On line 12, we pass '
freesansbold.ttf' (this is a font that comes with Pygame) and the integer
32 (for a 32-point sized font).
See http://invpy.com/usingotherfonts for more info on using other fonts.
The parameters to the
render() method call are a string of the text to render, a Boolean value to specify if we want anti-aliasing (explained later in this chapter), the color of the text, and the color of the background. If you want a transparent background, then simply leave off the background color parameter in the method call.