Neste artigo, veremos como brincar com textos usando o módulo Pygame. Estaremos lidando aqui com inicializar a fonte, renderizar o texto, editar o texto usando o teclado e adicionar uma nota de cursor piscante. 

Instalação

Para instalar este módulo, digite o comando abaixo no terminal.

pip install pygame

Inicialização de fonte

Agora podemos prosseguir com a parte de inicialização da fonte. O método pygame.font.init() é usado para inicializar a fonte e o método pygame.font.get_init() é usado para verificar se a fonte foi inicializada ou não. Ambos os métodos não requerem nenhum argumento. Se a fonte foi inicializada com sucesso, o método pygame.font.get_init() retorna verdadeiro. 

Impressão de texto na janela

Aqui, veremos como obter fonte e texto personalizados na tela. Vamos definir a posição dos textos a serem exibidos na tela usando as coordenadas xey. Primeiro, vamos criar os arquivos de fontes e, em seguida, renderizar os textos. A tela. A função blit() é usada para copiar os objetos de superfície de texto para os objetos de superfície de exibição nas coordenadas centrais.

# import pygame
import pygame
 
# initializing pygame
pygame.font.init()
 
# check whether font is initialized
# or not
pygame.font.get_init()
 
# create the display surface
display_surface = pygame.display.set_mode((500, 500))
 
# change the window screen title
pygame.display.set_caption('Our Text')
 
# Create a font file by passing font file
# and size of the font
font1 = pygame.font.SysFont('freesanbold.ttf', 50)
font2 = pygame.font.SysFont('chalkduster.ttf', 40)
 
# Render the texts that you want to display
text1 = font1.render('GeeksForGeeks', True, (0, 255, 0))
text2 = font2.render('GeeksForGeeks', True, (0, 255, 0))
 
# create a rectangular object for the
# text surface object
textRect1 = text1.get_rect()
textRect2 = text2.get_rect()
 
# setting center for the first text
textRect1.center = (250, 250)
 
# setting center for the second text
textRect2.center = (250, 300)
 
while True:
 
    # add background color using RGB values
    display_surface.fill((255, 0, 0))
 
    # copying the text surface objects
    # to the display surface objects
    # at the center coordinate.
    display_surface.blit(text1, textRect1)
    display_surface.blit(text2, textRect2)
 
    # iterate over the list of Event objects
    # that was returned by pygame.event.get()
    # method.
    for event in pygame.event.get():
 
        if event.type == pygame.QUIT:
           
            # deactivating the pygame library
            pygame.quit()
 
            # quitting the program.
            quit()
 
        # update the display
        pygame.display.update()

Saída:

Entrada do cursor na janela

Vamos adicionar a nota do cursor intermitente aqui. Nosso cursor continuará piscando a cada 0,5 seg. Também podemos editar nosso texto.

# import pygame module
import pygame
 
# import time module
import time
 
# initialize the pygame module
pygame.init()
 
# set the window screen size
display_screen = pygame.display.set_mode((500, 500))
 
# add some text
text = 'Hello Guys!!'
 
# add default font style with font
# size
font = pygame.font.SysFont(None, 40)
 
# render the text
img = font.render(text, True, (255, 0, 0))
 
rect = img.get_rect()
rect.topleft = (20, 20)
cursor = pygame.Rect(rect.topright, (3, rect.height))
 
running = True
 
while running:
     
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
 
        # detect if key is physically
        # presssed down
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                if len(text) > 0:
                     
                    # stores the text except last
                    # character
                    text = text[:-1]
 
            else:
                text += event.unicode
                 
            img = font.render(text, True, (255, 0, 0))
            rect.size = img.get_size()
            cursor.topleft = rect.topright
 
    # Add background color to the window screen
    display_screen.fill((200, 255, 200))
    display_screen.blit(img, rect)
     
    # cursor is made to blink after every 0.5 sec
    if time.time() % 1 > 0.5:
        pygame.draw.rect(display_screen, (255, 0, 0), cursor)
         
    # update display
    pygame.display.update()
 
pygame.quit()

Saída:

Caixa de entrada na janela

Aqui veremos como ler o texto usando o teclado no pygame. Vamos mostrar nosso texto dentro de um retângulo. Quando o mouse passa sobre o retângulo, a cor do retângulo muda. Comentários foram adicionados ao código para uma compreensão clara. 

# import pygame module
import pygame
 
# import sys library
import sys
 
# initializing pygame
pygame.init()
 
clock = pygame.time.Clock()
 
# Set the window screen size
display_screen = pygame.display.set_mode((500, 500))
 
# add font style and size
base_font = pygame.font.Font(None, 40)
 
 
# stores text taken by keyboard
user_text = ''
 
# set left, top, width, height in
# Pygame.Rect()
input_rect = pygame.Rect(200, 200, 140, 32)
color_active = pygame.Color("lightskyblue")
color_passive = pygame.Color("gray15")
color = color_passive
 
active = False
 
while True:
     
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
 
        # when mouse collides with the rectangle
        # make active as true
        if event.type == pygame.MOUSEBUTTONDOWN:
            if input_rect.collidepoint(event.pos):
                active = True
 
        # if the key is physically pressed down
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                 
                # stores text except last letter
                user_text = user_text[0:-1]
            else:
                user_text += event.unicode
 
    display_screen.fill((0, 0, 0))
 
    if active:
        color = color_active
    else:
        color = color_passive
 
    pygame.draw.rect(display_screen, color, input_rect)
     
    # render the text
    text_surface = base_font.render(user_text, True, (255, 255, 255))
    display_screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5))
    input_rect.w = max(100, text_surface.get_width() + 10)
    pygame.display.flip()
    clock.tick(60)

Saída:

 Atenção geek! Fortaleça suas bases com o Python Programming Foundation Course e aprenda o básico.