Using fonts (Simple)

Frequently there is a need to display some text, for instance, a counter or a message.

How to do it...

Pygame has a font module that can help us to show text.

  1. Creating a font: We can create a font by specifying, the font filename, and font size as constructor parameters:
    font = pygame.font.Font('freesansbold.ttf', 32)
  2. Displaying text: Since we made an image move around the edge in the previous recipe, it would be great to display a counter and the position of the image in the center of the screen with a blue background and red letters. The following code snippet accomplishes this:
    text = "%d %d %d" % (i, pos[i][0], pos[i][1])
    rendered = font.render(text, True, RED, BLUE)
    screen.blit(rendered, (150, 200))

    Note

    A screenshot of the animation is shown as follows and should be on YouTube too at https://www.youtube.com/watch?v=xhjfcFhaXN0.

    How to do it...

    The code is almost the same as for the previous recipe, with the addition of code for the creation and display of fonts:

    import pygame, sys
    from pygame.locals import *
    import numpy
    
    pygame.init()
    clock = pygame.time.Clock()
    screen = pygame.display.set_mode((400, 400))
    
    pygame.display.set_caption('Animating Objects')
    img = pygame.image.load('head.jpg')
    
    steps = numpy.linspace(20, 360, 40).astype(int)
    right = numpy.zeros((2, len(steps)))
    down = numpy.zeros((2, len(steps)))
    left = numpy.zeros((2, len(steps)))
    up = numpy.zeros((2, len(steps)))
    
    right[0] = steps
    right[1] = 20
    
    down[0] = 360
    down[1] = steps
    left[0] = steps[::-1]
    left[1] = 360
    
    up[0] = 20
    up[1] = steps[::-1]
    
    pos = numpy.concatenate((right.T, down.T, left.T, up.T))
    i = 0
    
    # create a font
    font = pygame.font.Font('freesansbold.ttf', 32)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    
    while True: 
       # Erase screen
       screen.fill((255, 255, 255))
    
       if i >= len(pos):
          i = 0
    
       screen.blit(img, pos[i])
    
       # displaying text in the center of the screen
       text = "%d %d %d" % (i, pos[i][0], pos[i][1])
       rendered = font.render(text, True, RED, BLUE)
       screen.blit(rendered, (150, 200))
       i += 1
    
       for event in pygame.event.get():
          if event.type == QUIT:
             pygame.quit()
             sys.exit()
    
       pygame.display.update()
       clock.tick(30)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset