python - 如何在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()
解决方案
只需跟踪经过的时间并使用条件语句,如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()
推荐阅读
- javascript - 使用 Jest 和 Supertest 测试 React 时出现服务器导出问题
- javascript - Summernote:TextArea 不加载 SQL 数据,但文字可以
- javascript - 有没有一种方法可以在不确认 AWS Cognito 用户池中用户的账户状态的情况下验证电子邮件?
- html - 如何修复表格中的 CSS“空白:nowrap”?
- sql-server - 将多行合并为单个表上的一行
- vue.js - 如何使用 VueJS 在 Sweetalert2 中显示多个选择选项?
- amazon-web-services - 亚马逊 API:如何使用亚马逊的 MWS API 通过 ASIN 获取产品信息?
- c++ - 可以在c ++中以两种方式编写双指针吗?
- c# - 如何在 PictureBox 上绘制网格以保留其包含的图像?
- python-3.x - 如何在 break 命令后重新启动 while 循环?