learn Python. Create Games

User Tools

Site Tools


Step 012 - Text

Code Discussion

randomized 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 write function:

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

Inside this 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")

Code Challenges:

  • 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:

file in folder download pygame Download the whole Archive with all files from Github:

View/Edit/Download the file directly in Github:

click reload in your browser if you see no code here:

Comment this Page


/var/www/horst/ · Last modified: 2014/01/09 11:07 (external edit)