Pygame-Two display updates at the same time with a pygame.time.wait() function between

我的未来我决定 提交于 2019-12-18 09:37:57

问题


I add a pygame.time.wait(2000) function between two display updates expecting that after a keydown, it will first show up one text, then after 2 seconds, the second one. But it end up showing up the two texts simultaneously two seconds after the trigger. How should I correctly use the function to reach my goal?

import pygame
from pygame.locals import *
from sys import exit

SCREEN_WIDTH = 448
SCREEN_HEIGHT = 384

pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
my_font = pygame.font.SysFont("arial", 16)
textSurfaceObj1 = my_font.render('Hello world!', True, (255,255,255))
textRectObj1 = textSurfaceObj1.get_rect()
textRectObj1.center = (100, 75)
textSurfaceObj2 = my_font.render('Hello world!', True, (255,255,255))
textRectObj2 = textSurfaceObj2.get_rect()
textRectObj2.center = (200, 150)


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == KEYDOWN:
            screen.blit(textSurfaceObj1, textRectObj1)
            pygame.display.flip()
            pygame.time.wait(2000)
            screen.blit(textSurfaceObj2, textRectObj2)
            pygame.display.flip()

回答1:


If your code works depends on the window manager you're using, but as you noticed, that's not good.

You need to wrap your head around the fact that your game runs in a loop, and everything you do to stop the loop (like wait or sleep) will not work.

In your code, you have three states:

1) print nothing
2) print the first text
3) print both texts

so and easy way to solve your problem is to simply keep track of the current state in a variable, like this:

import pygame
from sys import exit

SCREEN_WIDTH = 448
SCREEN_HEIGHT = 384

pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
my_font = pygame.font.SysFont("arial", 16)

text = my_font.render('Hello world!', True, (255,255,255))
text_pos1 = text.get_rect(center=(100, 75))
text_pos2 = text.get_rect(center=(200, 150))

state = 0
ticks = None
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN and state == 0:
            state = 1
            ticks = pygame.time.get_ticks()

    if state == 1 and ticks and pygame.time.get_ticks() > ticks + 2000:
        state = 2

    screen.fill((30, 30, 30))
    if state > 0: screen.blit(text, text_pos1)
    if state > 1: screen.blit(text, text_pos2)
    pygame.display.flip()


来源:https://stackoverflow.com/questions/53613168/pygame-two-display-updates-at-the-same-time-with-a-pygame-time-wait-function-b

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