首页 > 解决方案 > 如何在pygame中发出挥之不去的消息

问题描述

我刚开始使用 pygame,想知道消息如何在 pygame 中逗留而不影响循环。假设我希望消息显示 5 秒然后消失,但是当它发生时游戏循环仍将继续运行。我尝试使用 time.sleep 和时钟,但它们会完全暂停循环,直到消息停止出现。如何使消息在游戏循环仍在运行时显示?

简化示例:

def message_linger():
    #message output code here
    time.sleep(4)

def game_loop():
    #some pygame junk
    message_linger
    pygame.display.update()
    clock.tick(60)

game_loop()

标签: pythonpygame

解决方案


只需跟踪经过的时间并使用条件语句,如if passed_time < 5000: FONT.render_to(...).

import pygame as pg
from pygame import freetype


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
FONT = freetype.Font(None, 42)
start_time = pg.time.get_ticks()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill(BG_COLOR)
    if pg.time.get_ticks() - start_time < 5000:  # 5000 ms
        FONT.render_to(screen, (100, 100), 'the message', BLUE)
    pg.display.flip()
    clock.tick(60)

pg.quit()

推荐阅读