Pygame Drawing and Animation

Font Module, Render Method, Rect Object, and get_rect() method

In this section, we will introduce another pygame module called “font“.

As discussed earlier, in any pygame program, our first statement is }import pygame”.

When you import the pygame module, it brings inside it several modules. One such module is the font module called pygame.font. Inside the font module is a data type (object) called Font.

Note: The modules generally begin with lowercase letters and the data types (objects) begin with uppercase letters to distinguish between them.

The font module (pygame.font) allows you to render TrueType fonts to a new Surface object

To display the text on a pygame surface object, first we need to create a Font object. So, how do we create new Font objects?

How to Create a Font Object

The Font object is created by a statement below.

>>> fontA = pygame.font.SysFont(font type, font size)

Suppose you want to use Arial font with a font size of 32. You would type the following statement.

fontA = pygame.font.SysFont(arial, 32)

The above statement creates a new Font object that is stored in the variable named “fontA”. The font type of the “fontA” object is Arial and its font size is 32. You can use any variable name you like.

In case you do not specify the first argument (font type), a default font type is used by pygame. The first parameter is the name of the font, but you can use None value to use the default system font.

The statement Pygame.font.SysFont() creates a pygame Font object by searching the system font resources for the specified font type name.

We will show you in a later section how to create and use the Font object in a program.

Font Object’s Method get_rect()

The Font object created by the above statement has a method associated with it called get_rect().  The get_rect() method returns a Rect object that indicates the size and location of the Font object. We will discuss the get_rect() method below in detail.

How To Display Text on Pygame Surface

To display text on the pygame surface, we need to call the Font object’s method called render() and another pygame object called Rect discussed below.

Font Object’s Method render()

Font object has a method called render(). After creating the Font object, before we can write the text on the surface, Render() method is used to create a Surface object by calling the Font object’s render() method.

The following statements are an example of how you use the render() method.

  1. fontA = pygame.font.SysFont(font type, font size)
  2. txt = fontA.render(‘Text to be printed’, True, BLUE)

Line 1) statement creates a new Font object named “fontA”. The font type of the “fontA” object is Arial and its font size is 32.

Line 2) is the render() method statement. There are three arguments within the parenthesis of the render() method.

  • The first argument is the text you want to print. 
  • The third argument is the color of the text you want to be displayed.

The “fontA” object was created in line 1). In line 2), we use the render() method on the Font object named “fontA” to create a Surface object (named “txt”), which has the “Text to be printed” on it.

We then blit the Surface object with text on it to the display screen Surface object.

Rect Object

The Pygame module includes an object called Rect. A Rect is a rectangular area defined by the rectangle’s top-left corner (x,y) coordinates, and the rectangle’s width and height.

A Rect object can be created by calling the function pygame.Rect as below:

pygame.Rect(top-left corner’s x, y coordinates, width of rectangle, height of rectangle)

The parenthesis contains a tuple of four integers (top-left x,y coordinates, width, and height of the rectangle).  

Below is an example of how to create a Rect object.

>>> newRect = pygame.Rect(10, 10, 30, 40)

The above statement will create a rectangle named “newRect” with its top left corner at coordinates (10, 10). The rectangle is 30 pixels wide and 40 pixels high. 

We will use Rect objects in our animation programs in a later section.

Pygame objects have attributes and methods associated with them.

Rect Object’s Attributes:

The rect object has many attributes associated with it. 

In the example below, “newRect” is a Rect object. Below are a few of the attributes of the Rect object. We will use some of these attributes in the programs in this section.

ATTRIBUTEMEANING
newRect.centerxInteger value of the x-coordinate of
the center of the rectangle
newRect.centeryInteger value of the y-coordinate of
the center of the rectangle
newRect.widthValue of the width of the rectangle
newRect.leftInteger value of the x-coordinate of
the left side of rectangle
newRect.rightInteger value of the x-coordinate of
the right side of rectangle
RECT OBJECT ATTRIBUTES

Rect Objects Methods:

The Rect object has several methods, which can be used to move and position the rectangles.  We will present only one of them here, called get_rect() method.

Get_rect Method:

To explain the get_rect() method, let us look at the code in the example below.

>>> fontA = pygame.font.SysFont(arial, 32)   #  1

>>> txt = fontA.render(‘Text to be printed.’ True, BLUE)  #  2

>>> txtRect = txt.get_rect                                          #  3

  1. We first create a Font object and name it “fontA” as explained in this section above.
  2. The code in line 2) uses the render() method to create a Surface object by calling the Font object’s render() method, as explained above.  This Surface object is stored in the variable named “txt”.
    • The text that we want to display on the surface is “Text to be printed” and is the first argument.
    • We also specify the text color and (optionally) the background color.
    • The second argument “True” specifies anti-aliasing, which is explained in the EnrichmentMore About Colors, Frame-rate and Anti-aliasing section at the end of this chapter.  
  3. The Rect object has a method associated with it, called get_rect. The get_rect() method returns a Rect object, which is a rectangle that provides the bounds of the text (size) and position of the Font object.
    • This Font object is named “txtRect” in this example. You can choose any name that is meaningful to you.

Recap: How to Display Text on Pygame Surface

To recap, the following are the steps to display text on a pygame Surface.

  1. Create a Font object by using pygame.font.SysFont() method.
  2. Next, create a Text surface object on which the text is to be written by using the render() method.
  3. Create a Rect object (which is a rectangle that gives the bounds of the text) using the get_rect() method to get the text Surface object.
  4. Use get.rect() attributes to position the text on the surface (center, etc.)
  5. Next step is to use the blit() method to copy the text Surface object to the display Surface object.
  6. Use pygame.display.update() method to make the text visible on the display Screen.

To display text or image on the display screen, we are working with three objects:

  • “screen” is the Surface object representing the application window.
  • “img” or “txt” is the Surface object of the image or text to be displayed on the display screen.
  • “rect” is the Rect object, which is the bounding rectangle of the text or image

If instead of text, you are displaying an image, you will follow the same procedure. Just replace “txt” with “image”.

Display Image and Text Without Using Rect Object

In the previous section, we learned about the Rect object, the get_rect method, and the render() method. We also learned how to display text on the surface. Now, let us apply these concepts to display an object on the Surface along with the text.

We will use the “pygame_ball_display.py” program we wrote on the Pygame Theory of Operation page and modify it to add text display capability to it.

We will do this in two steps:

  1. Without using Rect object
  2. Using Rect object
PROGRAM EXAMPLE: DISPLAY IMAGE AND TEXT ON SCREEN WITHOUT RECT OBJECT

Program: pygame_ball_display_with_text.py 

Image: ball.png

Copy and paste the program below in your Python folder.

Save the following image in the same folder as the python program and name it ball.png.

Pygame program to display the ball image.
Image of the Ball to be Displayed
import pygame
#
pygame.init()
#
width = 480
height = 320
screen = pygame.display.set_mode((width, height)) #1
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#
pygame.display.set_caption('Ball Image and Text') #2
#
clock = pygame.time.Clock()
#
ballImage = pygame.image.load('ball.png')
# Create a Font object and call it fontA.
fontA = pygame.font.SysFont("arial black", 48)	 #3
# To write the text on the surface, Render() method 
# is used to create a Surface object with text on 
# the Surface object.
txt = fontA.render("My Soccer ball", True, (255, 0, 0))	#4
textWidth = txt.get_width()			#5

x = 180
y = 140

def ball(x, y):
    screen.blit(ballImage, (x, y))		#6
    
# Main Loop
while True:
    screen.fill(WHITE)	
# Fill the entire screen with ‘WHITE’ color in computer memory
    screen.blit(txt, (240 - textWidth/2, 50))	#7
    ball(x, y)
    pygame.display.update()			#8
    clock.tick(60)

pygame.quit()
quit()

Detailed Line-by-line Program Explanation:

  1. screen = pygame.display.set_mode((width, height)) Create a display Surface object called ‘screen’ of dimensions width = 480 pixels and height = 320 pixels.
  2. pygame.display.set_caption('Ball Image and Text') This step defines the Pygame window name. This is the caption that appears on the top of the window screen border. We named it ‘Ball Image and Text’.
  3. fontA = pygame.font.SysFont(“arial black”, 48)
    • Call function to create a Font object.  The parameters in parenthesis specify the font name = “Arial Black” and font size = 48.
    • We store this Font object in the variable “fontA”.  You can any name of your choosing.
  4. txt = fontA.render(“My Soccer ball”, True, (255, 0, 0))
    • Font objects have a method called render().  In this step, we call the render() method to create a Text Surface object with the text written on it.
    • In this program, the text to be written on the display surface object is specified as the parameter “My Soccer ball” within the parenthesis.
    • The color of the text font is specified as a parameter and is set as RED, RGB = (255, 0, 0).
    • The second parameter (‘True’) specifies anti-aliasing. Refer to the Enrichment section “More About Color” at the end of this chapter for more details on RGB Color, Frame-rate, and anti-aliasing.
  5. text.get_width()
    • fThe get_width unction gets the width of the text message.
  6. def ball(x, y): screen.blit(ballImage, (x,y))
    • Define a function named “ball”. This function copies the ball image to the Surface object “screen”.
  7. screen.blit(txt, (240 - textWidth/2, 50))
    • This line of code copies the text object “txt” to the surface object “screen”.
    • The first parameter is the text Surface object defined in step 4)
    • The second parameter is the destination address where the text will be displayed.  The destination address x = (240 – textWidth/2, which is the center of the display surface in the x direction. The destination address for the y-direction is arbitrarily chosen to be 50 pixels.
  8. pygame.display_update() function makes the ball and the text visible on the display surface screen.

The following is the program output.

Without Animation Display Image with Text
Pygame Display Image With Text

Display Image and Text Using Rect Object

In the above program, we did not use the Rect object that we learned in the previous section.  Let us now apply what we learned about Rect objects to write a program to display a ball image and text on the display surface using a Rect object.

PROGRAM EXAMPLE: DISPLAY IMAGE AND TEXT USING rect OBJECT

Image: ball.png

Program name: pygame_ball_display_with_text_rect.py

import pygame
from pygame.locals import *			#1
pygame.init()
w = 340
h = 240
# Create a Surface object 'screen' 400 pixels wide and 300 pixels high.
screen = pygame.display.set_mode((w, h))	#2
# Define RGB values of colors we are going to use in the program.
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GRAY = (128, 128, 128)
# Name our pygame window.
pygame.display.set_caption('Ball and Text with Rect object')
#
clock = pygame.time.Clock()
# Load ball image specifying image file name
# Create a rectangular Rect Surface object for image using 
# get_rect() method.
img = pygame.image.load('ball.png')		#3a)
imgRect = img.get_rect()			#4a)
# Set the location on the screen for the ball to be displayed.
imgRect.center = w//2, h//1.5		        #6a)
# Create a Font object by calling pygame.font.SysFont()
# method.
# Font name is FontA. Font type = 'Arial Black'. 
# Font size is 32 points.
fontA = pygame.font.SysFont("arial black", 32)	#3
# Create a text surface object using render() method.
# Variable name of the surface is 'text'.
txt1 = fontA.render("My Soccer Ball", True, RED) #4
# Create a Rect object for text Surface using get_rect()
# method.
textRect = txt1.get_rect()			#5
# Set the location of the text to be written.
textRect.center = w//2, h//4			#6
    
# Main Loop.  
# This is infinite loop that iterates 60 times per second.
while True:
    screen.fill(WHITE)
    # Copy ball image object to screen Surface object.
    screen.blit(img, imgRect)			#7a)
    # Copy text object to screen surface object.
    screen.blit(txt1, textRect)			#7
    # Make the ball image and text visible on the Surface.
    pygame.display.update()			#8
    clock.tick(60)

pygame.quit()
quit()

Detailed Line-by-line Program Explanation:

  1. from pygame.locals import
    • pygame.locals  contains many constant variables that we use with Pygame such as QUIT.
  2. Set the width and height of the display screen object in the display.set_mode() function.
  3. a) img = pygame.image.load('ball.png')
    • Load the image of the ball. In this step, we define a variable called “img”. This statement calls the pygame.image.load('ball.png') function that returns a new Surface with the loaded image. The image name (“ball.png”) is specified within the parenthesis in the function as a parameter.
  4. a) imgRect = img.get_rect()
    • Create a Rect object (which is a rectangle that gives the bounds of the image) using the get_rect() method to get the Surface object with the image.
    • 3. fontA = pygame.font.SysFont("arial black", 32).

This function creates a Font object.  The parameters in parenthesis specify the font name = :Arial Black” and the font size = 32. We store this Font object in the variable “fontA”.

4. txt1 = fontA.render("My Soccer Ball", True, RED)

Call the Font object’s render() method to create a Surface object.  The render() method writes the text on this Surface object, named “txt1”. The text “My Soccer Ball” is specified as a parameter within the quotes inside the parenthesis.

Within the parenthesis, the second parameter is “True“, which selects anti-aliasing,

The third parameter sets the font color RED.

5. textRect = txt1.get_rect()

This line calls the text Surface object’s get_rect() method. This method creates a Rect object that is rectangular for the text Surface object “txt1”. This rectangular object has the correct width and height as required by the text specified in step 4). We store it in the variable “textRect”.

In the next step, we will set the top-left coordinates of the Rect object.

6) textRect.center = w//2, h//4

Using the center property (also called attribute) of the Rect object, set the position of the Rectangular object in the middle of the Surface in the x-direction and down 1/4th of the screen height in the y-direction.

6a) imgRect.center = w//2, h//1.5

Similar to 6) for setting image position.

7) screen.blit(txt1, textRect) 

Use the blit function to copy the text surface object to the ballDisplay surface object at position set in step 6)

7a) screen.blit(img, imgRect) Similar to step 7) for ball image blit.

8) pygame.display.update()

Call pygame.display.update() method to make the ballDisplay surface (along with the text) visible on the display screen.

Verified by MonsterInsights