How to run a function after a certain time in Pygame?

Asked

Viewed 960 times

2

I’m making a game with Python, in which character jumps obstacles and falls after a few seconds. In javascript I used the setTimeOut function for this. In Python I tried to do the same thing with time.Sleep(), Timer(), set_timer() and loop for. The intention is for the character to jump, spend some time in the air, and then fall; but instead the entire program pauses (including the movement of the scenery and obstacles).

Excerpt from my Python code

        if(leituradoTeclado.sePegeUpPressionada(event) and iniciarJogo == True):
            personagem.pular()
            time.sleep(5)
            personagem.cair()

1 answer

3


You can’t use the time.sleep() because it will stop the entire execution of the program. Instead, always let the controller return to your event loop, and do everything you can through events. You can’t let the program ever stop, because it always has to be redesigning the screen x times per second. So whatever you’re going to do, you have to do slowly and let the loop run to continue.

A very clean way of doing it is to use the pygame.time.set_timer() which allows you to place an event of your own in the pygame event queue after a certain time.

Since you didn’t share full code, I wrote an example, to jump with the w key:

def trata_eventos():
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
             sys.exit()
        if event.type == pygame.KEYDOWN:
             if event.key == pygame.K.w:
                 personagem.pular()
                 # programa o pygame para gerar o evento daqui a 5 segundos
                 pygame.time.set_timer(pygame.USEREVENT+1, 5000)
        if event.type == pygame.USEREVENT+1: 
             # evento disparou! desabilita o evento:
             pygame.time.set_timer(pygame.USEREVENT+1, 0) 
             personagem.cair()

def desenha_tela(): # desenha o quadro atual
    # ... desenha o fundo, e todos os personagens em sua posicao atual ...
    personagem.desenhar() 
    pygame.display.flip() 

while True: # loop principal; cada repetição é um quadro a ser desenhado
    trata_eventos()
    desenha_tela()
    clock.tick(60) # espera para manter 60FPS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.