Pygame "pop up" 正文

Pygame "pop up" text

我正在学习 pygame 并且想知道,我怎样才能在屏幕上显示“+1 硬币”(或基本上任何东西)的“弹出”文本几秒钟,而无需必须使用 pygame.time.delay() 或 time.sleep() 因为它们会停止游戏,但我希望玩家能够继续玩,同时文本显示在屏幕上。

您可以使用 pyautogui

尝试类似的操作
if something_happens:
       pyautogui.alert("you have done this")

还有很多其他方法可以做到这一点,如果您有兴趣可以查看

如果你想在 Pygame 中随着时间的推移控制某些东西,你有两个选择:

  1. 使用pygame.time.get_ticks() to measure time and implement logic that controls the visibility of the text depending on the time. pygame.time.get_ticks() returns the number of milliseconds since pygame.init()。获取文本弹出的当前时间并计算文本必须消失的时间:

    draw_text = true
    hide_text_time = pygame.time.get_ticks() + 1000 # 1 second
    
    if draw_text and pygame.time.get_ticks() > hide_text_time:
        draw_text = false 
    
  2. 使用定时器事件。在事件队列中使用 pygame.time.set_timer() to repeatedly create a USEREVENT。时间必须以毫秒为单位设置。在文本弹出时启动一个定时器事件,在事件发生时隐藏文本:

    draw_text = true
    hide_text_event = pygame.USEREVENT + 1
    pygame.time.set_timer(hide_text_event, 1000, 1) # 1 second, one time
    
    # applicaition loop
    while True:
    
        # event loop
        for event in pygame.event.get():
            if event.type == hide_text_event:
                draw_text = False
    

有关完整示例,请参阅问题的答案:

  • .

最小示例(弹出时间可以用变量pop_up_seconds控制):

import pygame

pygame.init()
window = pygame.display.set_mode((400, 200))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()

text = font.render("+1", True, (0, 255, 0))
text_pos_and_time = []
pop_up_seconds = 1

player = pygame.Rect(0, 80, 40, 40)
coins = [pygame.Rect(i*100+100, 80, 40, 40) for i in range(3)]

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    player.x = (player.x + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 3) % 300    

    current_time = pygame.time.get_ticks()
    for coin in coins[:]:
        if player.colliderect(coin):
            text_pos_and_time.append((coin.center, current_time + pop_up_seconds * 1000))
            coins.remove(coin)

    window.fill(0)    
    pygame.draw.rect(window, "red", player)
    for coin in coins:
        pygame.draw.circle(window, "yellow", coin.center, 20)
    for pos_time in text_pos_and_time[:]:
        if pos_time[1] > current_time:
            window.blit(text, text.get_rect(center = pos_time[0]))
        else:
            text_pos_and_time.remove(pos_time)    
    pygame.display.flip()

pygame.quit()
exit()