gpt4 book ai didi

python - Pygame Surface 非顺序更新

转载 作者:太空狗 更新时间:2023-10-29 17:29:58 26 4
gpt4 key购买 nike

我正在尝试实现一个简单的 Pygame 脚本,它应该:

  1. 首先,检查用户何时按下 Space 键;
  2. Space 键按下时, 显示一些文本;然后
  3. 暂停 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()

提前致谢!

最佳答案

出于某种原因,该程序对我有效,我唯一更改的是字体。这与@Omega0x013 所做的相同,但您拥有无限的帧率。它起作用是因为FPS.tick() 返回自上次调用以来的时间量,如果您未指定帧速率,则它不会保留程序。

import pygame
import sys
from pygame.locals import *
displayText = False
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(None,30)
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)

FPS = pygame.time.Clock()
while True:
wS.fill(BLACK)
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
totalTime = 0
FPS.tick()
displayText = True

if event.type == QUIT:
pygame.quit()
sys.exit(0)
if displayText:
totalTime += FPS.tick()
create_text(250, 250, "Hello world!", WHITE)
if totalTime >= 2000:
displayText = False
pygame.display.update()

关于python - Pygame Surface 非顺序更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50616126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com