我正在尝试实现一个简单的Pygame脚本,它应该:
- 首先,检查用户是否按下了 Space 键;
- 在按下 Space 键时,显示一些文本;然后
- 暂停2秒钟,然后将屏幕更新到其原始状态。
请注意,上述所有事件必须按顺序发生,且不能颠倒顺序。
我遇到了问题,程序首先暂停,然后只显示文本并在屏幕更新到其原始状态前出现了一个短暂的时间(或根本不显示)。
程序似乎跳过了第2步,然后才执行了第3步的暂停操作,而没有显示文本。我的代码如下:
import pygame
import sys
from pygame.locals import *
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
pygame.init()
wS = pygame.display.set_mode((500, 500), 0, 32)
# Method works as intended by itself
def create_text(x, y, phrase, color):
"""
Create and displays text onto the globally-defined `wS` Surface
(params in docstring omitted)
"""
# Assume that the font file exists and is successfully found
font_obj = pygame.font.Font("./roboto_mono.ttf", 32)
text_surface_obj = font_obj.render(phrase, True, color)
text_rect_obj = text_surface_obj.get_rect()
text_rect_obj.center = (x, y)
wS.blit(text_surface_obj, text_rect_obj)
while True:
wS.fill(BLACK)
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
# Snippet containing unexpected behavior
create_text(250, 250, "Hello world!", WHITE)
pygame.display.update()
pygame.time.delay(2000)
# Snippet end
if event.type == QUIT:
pygame.quit()
sys.exit(0)
pygame.display.update()
提前致谢!
pygame.time.delay(2000)
下面的两行代码。它们似乎是不必要的,可能会引起问题。 - skrxdelay()
方法调用下面的两行代码,我确实看到了“Hello World!”文本被blitted;但是,它只会显示一瞬间(一个帧?),而不是预期的2秒。 - Jerrybibodelay
调用后,程序的执行应该停止。顺便说一下,我一开始很难复现这个错误。我想我只看到过一次,而且时间非常短,但是再也无法复现了。也许重新构建程序并使用其中一个计时器会更好。 - skrx