PyGame同时使用一个pygame.time.等等()函数介于

2024-10-03 15:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我加了一个pygame.time.等等(2000)两次显示更新之间的函数,期望在按下一个键后,它将首先显示一个文本,然后在2秒钟后显示第二个文本。但它最终会在触发两秒钟后同时显示这两个文本。我应该如何正确使用函数来达到我的目标?你知道吗

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

Tags: 文本importeventtruegetmydisplayscreen
1条回答
网友
1楼 · 发布于 2024-10-03 15:27:31

代码是否有效取决于您使用的窗口管理器,但正如您所注意到的,这并不好。你知道吗

你需要了解这样一个事实:你的游戏是在一个循环中运行的,你所做的一切阻止循环(比如waitsleep)都不会起作用。你知道吗

在代码中,有三种状态:

1)不打印
2) 打印第一个文本
3) 打印两个文本

因此,解决问题的简单方法是简单地跟踪变量中的当前状态,如下所示:

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

相关问题 更多 >