Search code examples
pythontimerpygame

Doing something after a period of time: Pygame


I wanted to do something after a period of time. On stack overflow I found a question that helps solve that, (Link) but when I run the program the code works, however it goes away after a millisecond. Whereas I want it to stay there after the amount of time I want it to wait. In this case for a test run I am blitting some text onto the screen. Here is the code:

import pygame
# Importing the modules module.

pygame.init()
# Initializes Pygame

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((800, 600))
# Sets the screen to pygame looks and not normal python looks.

pygame.display.set_caption("Test Run")
# Changes the title

# Heading
headingfont = pygame.font.Font('Bouncy-PERSONAL_USE_ONLY.otf', 45)
headingX = 230
headingY = 10

class Other():
    def show_heading():
        Heading = headingfont.render("Health Run!", True, (255, 255, 255))
        screen.blit(Heading, (headingX, headingY))


pygame.time.set_timer(pygame.USEREVENT, 100)

running = True
while running:
    screen.fill((0,0,0))
 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.USEREVENT:
                Other.show_heading()

    #Update Display
    pygame.display.update()

Solution

  • If you want to draw the text permanently, you need to draw it in the application loop. Set a Boolean variable "draw_text" when the timer event occurs. Draw the text depending on draw_text in the application loop:

    draw_text = False
    
    running = True
    while running:
        screen.fill((0,0,0))
     
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
            if event.type == pygame.USEREVENT:
                draw_text = True
    
        if draw_text:
            Other.show_heading()
    
        #Update Display
        pygame.display.update()
    

    For more information about timers and timer events, see Spawning multiple instances of the same object concurrently in python, How can I show explosion image when collision happens? or Adding a particle effect to my clicker game and many more.