Pygame“弹出”文本 - 如何仅显示一段时间的图像?

问题描述 投票:0回答:2

我现在正在学习 pygame,想知道如何在屏幕上制作一个“弹出”文本,显示“+1 硬币”(或基本上任何内容)几秒钟,而不必使用 pygame.time.delay () 或 time.sleep() 因为它们会停止游戏,但我希望玩家能够继续玩,同时文本显示在屏幕上。

python pygame
2个回答
3
投票

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

  1. 使用

    pygame.time.get_ticks()
    测量时间并实现根据时间控制文本可见性的逻辑。
    pygame.time.get_ticks()
    返回自
    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()
    在事件队列中重复创建
    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
控制弹出时间):

PYGBAG 演示

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

0
投票

您可以使用

pyautogui

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

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

© www.soinside.com 2019 - 2024. All rights reserved.