How do you make Pygame stop for a few seconds?

做~自己de王妃 提交于 2021-02-05 09:27:53

问题


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().


回答1:


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


来源:https://stackoverflow.com/questions/65083381/how-do-you-make-pygame-stop-for-a-few-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!