Module PyGame. Graphic text. Counter of game

12.5.2.4 display graphic text on the screen
12.5.3.7 implement an algorithm for calculating game results

Module PyGame. Graphic text. Counter of game

To display text in the pygame window, you need to create a separate object with text and convert it into a graphic object.
For instance to show: 

  • the character/player names,
  • scores of players,
  • instructions for the game,
  • start/game over texts, etc.

How to output text in pygame

To do this, follow the following five steps:

Step 1: Create an object of the Font class using the font.Font() pygame method.

font = pygame.font.SysFont(system_font , size, bold, italic)
font = pygame.font.Font(face_font , size)
# SysFont - allows you to use the fonts installed in the system
# Font - allows you to use the fonts installed in the system allows you to use external fonts or the default font - None
# bold - bold font or not bold (1 or 0), default 0 - not applied
# italic - italic font or not italic (1 or 0), default 0 - not applied
# face_font - a font of pygame (value None) or user font

Example,

font = pygame.font.SysFont("Times New Roman" , 54)

font = pygame.font.Font("Bottom_Rock.ttf" , 54)

Step 2: Create a text surface object, text, using the pygame font object's render() method, which converts the text to a bitmap.

text = font.render(text_string, smoothing, color, background_color)
# text_string - outputting text
# smoothing - True or False (1 or 0)
# color - (R, G, B)
# background color - the back color of the surface text

Step 3: Create a rectangular object for the text surface object using the get_rect() method of the pygame text surface object.

text_size = text.get_size() # text_size[0] - width, text_size[1] - height
# or
text_size = text.get_rect() # text_size[2] - width, text_size[3] - height
# or
text_w = text.get_width()
text_h = text.get_height()

Step 4: Set the position of a rectangular object, for example, determine the object's coordinates to display text in the center of the pygame window.

text_x = width // 2 - text.get_width() // 2
text_y = height // 2 - text.get_height() // 2

Step 5: Show the Text surface object into a display surface object using the blit() method of the display surface object in the main pygame loop.

screen.blit(text, (text_x, text_y))

How to input text in pygame

To input text in a Pygame window, you can use the built-in pygame.key.get_pressed() method and pygame.key.name() function. Here is an example of how you can use these functions to input text in a Pygame window:

Step 1. First, you need to create a dictionary that maps keycodes to characters.

key_map = {
    pygame.K_a: 'a',
    pygame.K_b: 'b',
    pygame.K_c: 'c',
    # ... add more keys as needed
}

Step 2. You need to create a variable to store the input text and set it to an empty string.

text = ""

Step 3. In your game loop, you can check for key presses using the pygame.key.get_pressed() method. This method returns a list of boolean values representing the state of all the keys on the keyboard.

keys = pygame.key.get_pressed() # get the state of all keys

Step 4. You can then iterate over the dictionary and check if the corresponding key is pressed. If it is, you can add the associated character to your input text.

for key, character in key_map.items():
    if keys[key]:
        text += character

Step 5. You may also want to add functionality for backspace and return, by checking for the keycode and editing the text accordingly.

if keys[pygame.K_BACKSPACE]:
    text = text[:-1]
if keys[pygame.K_RETURN]:
    # Do something with the input text

Step 6. Finally, you can render the text using the render() method of the pygame.font.Font object and blit it to the screen.

text_surface = font.render(text.upper(), True, (255, 255, 255))
screen.blit(text_surface, (x, y))

Examples

Task 1. Output text "Hello, NIS!" in the center of the pygame window in a rectangular frame. Use function for creating text surface.

Decision

import pygame

pygame.init()
size = width, height = 400, 200
screen = pygame.display.set_mode(size)

def draw(): # function for creating text surface and output rectangle around text
    screen.fill((0, 0, 0))
    font = pygame.font.SysFont("Calibri bold", 54) # define font and size
    text = font.render("Hello, NIS!", 1, (100, 255, 100)) # create graphic text
    text_x = width // 2 - text.get_width() // 2
    text_y = height // 2 - text.get_height() // 2
    text_w = text.get_width()
    text_h = text.get_height()
    screen.blit(text, (text_x, text_y))

    pygame.draw.rect(screen, (0, 255, 0), (text_x - 10, text_y - 10,
                                           text_w + 20, text_h + 20), 1)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    draw()
    pygame.display.flip()

pygame.quit()

Task 2. Output animated by Blue color text "Hello, NIS!" (font Bottom_Rock.ttf) in the center of the pygame window in a rectangular frame. Start color is used (255, 0, 0).

Decision

import pygame

# Initialize Pygame
pygame.init()

size = width, height = 400, 200
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Animated Text")

# Define the text, font, and initial color
text = "Hello, NIS!"
font = pygame.font.Font("Bottom_Rock.ttf", 54)
color = (255, 0, 0)  # Red

# Main game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # Animate the color of the text
    color = (color[0], color[1], color[2] + 3)  # Increase the blue value
    if color[2] > 255:
        color = (255, 0, 0)  # Reset to red
    
    # Render the text
    text_surface = font.render(text, True, color)
    
    # Clear the screen and draw the text
    screen.fill((0, 0, 0))
    text_x = width // 2 - text_surface.get_width() // 2
    text_y = height // 2 - text_surface.get_height() // 2
    screen.blit(text_surface, (text_x, text_y))
    
    pygame.display.flip()
    # Delay to slow down the animation
    pygame.time.delay(20)

pygame.quit()

Task 3. Create text movement from right to left.

Decision

import pygame

# Initialize Pygame
pygame.init()

screen = pygame.display.set_mode((400, 100))
pygame.display.set_caption("Moving Text")
clock = pygame.time.Clock()
text = "Hello, World!"
font = pygame.font.Font(None, 36)
x = 400  # Initial x position off the screen
y = 40  # Initial y position
text_surface = font.render(text, True, (255, 255, 255))
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    x -= 1  # Move the text to the left
    if x + text_surface.get_width() < 0:
        x = 400  # Reset the x position when it goes off the screen
    # Render the text
    text_surface = font.render(text, True, (255, 255, 255))
    
    # Clear the screen and draw the text
    screen.fill((0, 0, 0))
    screen.blit(text_surface, (x, y))
    clock.tick(50)
    pygame.display.flip()
pygame.quit()

Task 4. Create click counter in pygame.
Displays a number on the screen that starts from 0. When the user clicks the mouse, the number displayed is incremented by 1. The number is rendered as text on the screen using the specified font and position and the screen is updated.

Decision

import pygame

# Initialize Pygame
pygame.init()

screen = pygame.display.set_mode((400, 100))
pygame.display.set_caption("Counter Example")

# Create a variable to hold the counter value
counter = 0
# Define the font for the counter text
font = pygame.font.Font(None, 36)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # Increment the counter when the mouse is clicked
            counter += 1
    
    # Render the counter text
    text_surface = font.render(str(counter), True, (255, 0, 0))
    
    # Clear the screen and draw the text
    screen.fill((0, 0, 0))
    screen.blit(text_surface, (50, 50))
    
    pygame.display.flip()
pygame.quit()

Task 5. Write the program to input name of the user in the pygame window. After pressing key Enter, output Your name: ...

Decision

import pygame

# Initialize Pygame
pygame.init()


key_map = {
    pygame.K_a: 'a',
    pygame.K_b: 'b',
    pygame.K_c: 'c',
    # ... add more keys as needed
}
screen = pygame.display.set_mode((400, 100))
pygame.display.set_caption("Input text")
text = "Enter your name: "
# Define the font for the text
font = pygame.font.Font(None, 24)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            keys = pygame.key.get_pressed()  # get the state of all keys
            for key, character in key_map.items(): # iterate all letters in dictionary key_map
                if keys[key]: # check any letters in dictionary
                    text += character # add to text
            if keys[pygame.K_BACKSPACE]:  # delete the last letter
                text = text[:-1]
            elif keys[pygame.K_RETURN]:  # returm result
                text = text[6:]
    # Render the upper letters
    text_surface = font.render(text.upper(), True, (255, 255, 255))
    screen.fill((0, 0, 0))
    screen.blit(text_surface, (20, 20))
    
    pygame.display.flip()
pygame.quit()

Key-map dictionary

key_map = {
    pygame.K_a: 'a', pygame.K_b: 'b', pygame.K_c: 'c',
    pygame.K_d: 'd', pygame.K_e: 'e', pygame.K_f: 'f',
    pygame.K_g: 'g', pygame.K_h: 'h', pygame.K_i: 'i',
    pygame.K_j: 'j',   pygame.K_k: 'k',  pygame.K_i: 'i',
    pygame.K_m: 'm', pygame.K_n: 'n', pygame.K_o: 'o',
    pygame.K_p: 'p', pygame.K_q: 'q', pygame.K_r: 'r',
    pygame.K_s: 's', pygame.K_t: 't', pygame.K_u: 'u',
    pygame.K_v: 'v', pygame.K_w: 'w', pygame.K_x: 'x',
    pygame.K_y: 'y', pygame.K_z: 'z'
    # ...add more keys as needed
}


Questions:

  1. How do I display text on the screen using Pygame?
  2. How do I change the font and color of the text displayed with Pygame?
  3. How do I center text on the screen using Pygame?
  4. How do I make text blink or change color over time using Pygame?
  5. How can I make text scroll across the screen using Pygame?

Exercises:


Tasks:

T1. Display a message in the center of the pygame window using the blit() method and a pre-rendered surface containing the text.

T2. Create a scrolling text effect by repeatedly updating the position of a surface containing the text and redrawing it on the pygame window.

T3. Allow the user to enter text using the pygame.key.get_pressed() method and the pygame.key.name() function, and display their input in real-time on the pygame window.

T4. Create a text input box using the pygame.draw.rect() method and the pygame.key.get_focused() function, and use the entered text to trigger in-game events or actions.

T5. Use the output text to generate dynamic in-game dialogue, by loading the text from a file and displaying it on the screen as a conversation progresses.

T6. Use the output text to display the game score, time remaining, and other important information by using the blit() method and a pre-rendered surface containing the text.

T7. Use the output text to create interactive buttons, by checking for mouse clicks on the text and performing an action when clicked.

 

Категория: Programming languages | Добавил: bzfar77 (15.01.2023)
Просмотров: 461 | Теги: get_rect, blit, get_height, text, PyGame, Font, get_width, render | Рейтинг: 0.0/0
Всего комментариев: 0
avatar