在 Pygame 中 2 秒后一个接一个地显示列表项

Display list items one after another after 2 sec in Pygame

这是列表

places = ["London", "India", "America", "Australia", "Cambodia", "China", 
          "Dubai", "Egypt",  "France", "Germany", "Japan", "Jordan", 
          "Korea", "Myanmar", "Peru", "Russia", "Singapore", "Spain"]

我将列表随机化:

random_place = random.choice(places)

这里我尝试显示列表中的随机项目。我试过使用 for 循环和 time.sleep 函数,但它没有用。

def text():
    game_font = pygame.freetype.SysFont("monospace", 35)
    text_surface, rect = game_font.render(random_place, (0, 0, 0))
    screen.blit(text_surface, (680, 420))
   
# Game loop
running = True
while running:
    screen.fill((255, 194, 102))  # RGB
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
   
    card()
    text()
    pygame.display.update()

如果有人能解决这个问题就太好了。

使用定时器事件。在 pygame 中存在一个定时器事件。在事件队列中使用 pygame.time.set_timer() to repeatedly create a USEREVENT。时间必须以毫秒为单位设置。

选择一张新的随机卡,当定时器事件发生时:

random_place = random.choice(places)

timer_interval = 2000 # 2000 milliseconds = 2 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, timer_interval)

running = True
while running:
    screen.fill((255, 194, 102))  # RGB
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == timer_event:
            random_place = random.choice(places)

    card()
    text()
    pygame.display.update()

请注意,在 pygame 中可以定义客户事件。每个事件都需要一个唯一的 ID。用户事件的 ID 必须介于 pygame.USEREVENT (24) 和 pygame.NUMEVENTS (32) 之间。在这种情况下,pygame.USEREVENT+1 是定时器事件的事件 ID。

我已将两个小代码块添加到您的代码中以实现此功能。它使用 time.time() 方法在游戏循环的每次迭代中检索当前时间(以秒为单位):

import pygame
import random
import time

pygame.init()
pygame.font.init()

screen = pygame.display.set_mode((1000, 800))

places = ["London", "India", "America", "Australia", "Cambodia", "China", 
          "Dubai", "Egypt",  "France", "Germany", "Japan", "Jordan", 
          "Korea", "Myanmar", "Peru", "Russia", "Singapore", "Spain"]

def text():
    game_font = pygame.freetype.SysFont("monospace", 35)
    text_surface, rect = game_font.render(random_place, (0, 0, 0))
    screen.blit(text_surface, (680, 420))

interval = 2 # Set interval in seconds
last_time = time.time() # Get the current time in seconds
random_place = random.choice(places)

# Game loop
running = True
while running:
    screen.fill((255, 194, 102))  # RGB
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
   
#    card()
    # If 2 seconds has past since the last update to last_time
    if time.time() - last_time >= interval: 
        random_place = random.choice(places)
        last_time = time.time()
        
    text()
    pygame.display.update()

pygame.quit()

输出: