Warm tip: This article is reproduced from serverfault.com, please click

How do you make Pygame stop for a few seconds?

发布于 2020-12-01 01:10:40

I know this is a simple problem and I could just use the time function or something, but it's somehow still a problem to me. So I have this:

    letter = pygame.image.load('w00.png')
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    letter = pygame.image.load('e-2.png')
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    letter = pygame.image.load('l-2.png')
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    letter = pygame.image.load('c-2.png')
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    letter = pygame.image.load('o-2.png')
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    letter = pygame.image.load('m-2.png')
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    letter = pygame.image.load('e-2.png')
    screen.blit(letter, (letter_x, 625))

Between every time I blit the letter(I'm trying to make a sentence write itself one letter by one letter), I want it to stop for about 0.5 sec before it continues. Problem is, everything I tried hasn't work very well.

The time.sleep() function and the pygame.time.delay() function and the pygame.time.wait() function all don't work because all of those functions for some reason run before anything loads. This is all inside of a function. (def function():)

I know that those functions run before anything loads because 1. It runs the def function(): the same as before and 2. It takes precisely the amount of time I put in the time.sleep() longer to load.

Thanks.

EDIT:

I've tried it out and apparently it doesn't even run the function before it runs the pygame.time.wait().

Questioner
Duck Duck
Viewed
0
Rabbid76 2020-12-01 23:19:18

The display is updated only if either pygame.display.update() or pygame.display.flip() is called. Further you've to handles the events by pygame.event.pump(), before the update of the display becomes visible in the window.

See pygame.event.pump():

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

If you want to display a text and delay the game, then you've to update the display and handle the events. See Why doesn't PyGame draw in the window before the delay or sleep?.

Anyway I recommend to load the images beforehand and do the animation in a loop:

filenames = ['w00.png', 'e-2.png', 'l-2.png', 'c-2.png', 'o-2.png', 'm-2.png', 'e-2.png']
letters = [pygame.image.load(name) for name in filenames]
for letter in letters:
    pygame.event.pump()
    screen.blit(letter, (letter_x, 625))
    letter_x += 30
    pygame.display.flip()
    pygame.time.delay(500) # 500 milliseconds = 0.5 seconds