Table of Contents
Step 012 - Text
There are more ways to display text than the
pygame.display.set_caption(“msg”) command. You can render any text directly on a pygame surface. This code example uses two defined functions to better seperate the text writing from the surface display commands. Note that inside the second function is a call to the first function, generating a random colour tuple of
(red, green, blue) values.
All the text rendering happens inside the
def write(msg="pygame is cool"): myfont = pygame.font.SysFont("None", random.randint(34,128)) mytext = myfont.render(msg, True, newcolour()) mytext = mytext.convert_alpha() return mytext
write-function, text is written to a surface (pygame uses the system font if no specific font-file is loaded) using a randomized font size and randomized colour. The text surface has already a transparent color and is returned to the function call inside the main loop:
# inside mainloop textsurface = write("hello world")
- prompt user for text to randomize
- read in a text file of words to display, change the word on collision with wall
For fun, no cleanrect method is used here and the background is only blitted to the screen when the text surface touches the left screen border.
The Flytext Function
This exmple is written as a big function, flytext(). The function flytext accept the two arguments msg (the text message to display) and duration.
Example: To call the function and let it write “Python is cool” for seven seconds, use:
flytext("Python is cool", 7)
Note that if you start flytext without arguments, the last two codelines will run the function with default arguments, writing “hello World” for five seconds. You can change the default values in the line where the flytext function is defined:
def flytext(msg="hello world", duration=5):
Source Code on Github
To run this example you need:
|012_text.py|| || Download the whole Archive with all files from Github:
View/Edit/Download the file directly in Github: https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/012_text.py
click reload in your browser if you see no code here: