【发布时间】:2018-11-09 23:37:30
【问题描述】:
我正在尝试实现一个简单的 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)下的两行。看起来它们是不必要的,可能会导致问题。 -
@skrx 一旦我删除了
delay()方法调用下面的两行,我确实看到Hello World!文本被blitted;但是,它只会显示瞬间(一帧?),而不是预期的 2 秒。 -
这很奇怪。程序的执行应该在
delay调用之后停止。顺便说一句,我一开始就很难重现这个错误。我想我在很短的时间内看过一次,但无法再次复制它。也许重组程序并使用其中一个timers 会更好。
标签: python python-3.x pygame