Working With Texts In Pygame By albro

Texts are an important part of games because they're used to communicate with the player. In this part, I'll talk about the texts and the way of using fonts in game development with Pygame.
Working with texts
In Pygame, text cannot be written directly to the screen. The first step to display the text in the window is to create a Font object with the given font size. The next step is to render the text into an image with a specific color. The third step is to display the image on the screen. So first we make the font, then we put the font inside an image, then we display the image in the window. These steps are given below:
font = pygame.font.SysFont(None, 24)
img = font.render('Welcome To @albro Blog On Hive Blockchain', True, BLUE)
screen.blit(img, (20, 20))
Once the font is created, its size cannot be changed. A Font object is used to create a Surface object from a string. It's not possible to directly display a text on a Surface object with Pygame. To create a Surface object from the text, we must use the render method.
Initializing a font
Font initialization can take a few seconds. With the following code, we can find out how much time it took to create the font:
t0 = time.time()
font = pygame.font.SysFont(None, 48)
print('time needed for Font creation :', time.time()-t0)
The result of running the code is as follows:
time needed for Font creation : 0.03698086738586426
The get_fonts function returns an array of all installed fonts. The following code checks what fonts are on your system and how many there are, and then prints them to the console:
fonts = pygame.font.get_fonts()
print(len(fonts))
for f in fonts:
print(f)
The result of running the code is as follows:
344
bigcaslonttf
silomttf
sfnsdisplayblackitalicotf
chalkdusterttf
. . .
Display text
The font object can convert a given text into an image. In the example below, I put a blue bounding rectangle around my text image:
img = font.render('Welcome To', True, RED)
rect = img.get_rect()
pygame.draw.rect(img, BLUE, rect, 1)
Then I create two more fonts named Chalkduster and Didot with size 72. I display the text with both fonts:
font1 = pygame.font.SysFont('chalkduster.ttf', 72)
img1 = font1.render('@albro', True, BLUE)
font2 = pygame.font.SysFont('didot.ttc', 72)
img2 = font2.render('Hive Blog', True, GREEN)
Finally, text images are displayed in the window like normal images:
screen.fill(background)
screen.blit(img, (20, 20))
screen.blit(img1, (20, 50))
screen.blit(img2, (20, 120))
pygame.display.update()
The entire code is below:
import pygame,sys
from pygame.locals import *
import time
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY = (200, 200, 200)
pygame.init()
screen = pygame.display.set_mode((640, 240))
sysfont = pygame.font.get_default_font()
print('system font :', sysfont)
t0 = time.time()
font = pygame.font.SysFont(None, 48)
print('time needed for Font creation :', time.time()-t0)
img = font.render('Welcome To', True, RED)
rect = img.get_rect()
pygame.draw.rect(img, BLUE, rect, 1)
font1 = pygame.font.SysFont('chalkduster.ttf', 72)
img1 = font1.render('@albro', True, BLUE)
font2 = pygame.font.SysFont('didot.ttc', 72)
img2 = font2.render('Hive Blog', True, GREEN)
fonts = pygame.font.get_fonts()
print(len(fonts))
for i in range(7):
print(fonts[i])
running = True
background = GRAY
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
screen.fill(background)
screen.blit(img, (20, 20))
screen.blit(img1, (20, 50))
screen.blit(img2, (20, 120))
pygame.display. update()
pygame.quit()
The result of running the code is as follows:

Edit text with keyboard
The keyboard event can be used to edit text. First I create the text and then render it into an image:
text = 'Welcome To @albro Game Programming Posts'
font = pygame.font.SysFont(None, 48)
img = font.render(text, True, RED)
Then I define the enclosing rectangle as well as the rectangle used to display the cursor:
rect = img.get_rect()
rect.topleft = (20, 20)
cursor = Rect(rect.topright, (3, rect.height))
Inside the event loop I watch for KEYDOWN events. If the key is BACKSPACE and the length of the string is greater than 0, I remove the last character, otherwise I add the new character to the text variable:
if event.type == KEYDOWN:
if event.key == K_BACKSPACE:
if len(text)>0:
text = text[:-1]
else:
text += event.unicode
Then I render the modified text, update the bounding rectangle, and place the cursor box at the end of the updated bounding rectangle:
img = font.render(text, True, RED)
rect.size=img.get_size()
cursor.topleft = rect.topright
Add a blinking cursor
To make the cursor more visible, I let it blink every 0.5 seconds. I do this using time.time():
screen.fill(background)
screen.blit(img, rect)
if time.time() % 1 > 0.5:
pygame.draw.rect(screen, RED, cursor)
pygame.display.update()

The result of running the code is as follows:
import pygame,sys
from pygame.locals import *
import time
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GRAY = (200, 200, 200)
pygame.init()
screen = pygame.display.set_mode((840, 240))
text = 'Welcome To @albro Game Programming Posts'
font = pygame.font.SysFont(None, 48)
img = font.render(text, True, RED)
rect = img.get_rect()
rect.topleft = (20, 20)
cursor = Rect(rect.topright, (3, rect.height))
running = True
background = GRAY
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_BACKSPACE:
if len(text)>0:
text = text[:-1]
else:
text += event.unicode
img = font.render(text, True, RED)
rect.size=img.get_size()
cursor.topleft = rect.topright
screen.fill(background)
screen.blit(img, rect)
if time.time() % 1 > 0.5:
pygame.draw.rect(screen, RED, cursor)
pygame.display.update()
pygame.quit()











Comments