python - 如何冻结pygame窗口?
问题描述
当我想冻结我的 pygame 窗口几秒钟时,我通常使用 time.sleep()。但是,如果我不小心按下了键盘上的任何键,它会在时间过去后检测到该键。有什么方法可以冻结我的 pygame 窗口,以便代码不会考虑按下的键?
解决方案
这是一个屏幕每帧都会改变颜色的例子。标题栏显示最后按下的键。
如果按下空格键,颜色更改将暂停三秒钟。按键被忽略,但在此期间可以处理其他事件。
这是通过设置自定义计时器并使用变量来跟踪暂停状态来实现的。
import pygame
import itertools
CUSTOM_TIMER_EVENT = pygame.USEREVENT + 1
my_colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# create an iterator that will repeat these colours forever
color_cycler = itertools.cycle([pygame.color.Color(c) for c in my_colors])
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
pygame.display.set_caption("Timer Example")
done = False
paused = False
background_color = next(color_cycler)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == CUSTOM_TIMER_EVENT:
paused = False
pygame.display.set_caption("")
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 0) # cancel the timer
elif not paused and event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 3000)
pygame.display.set_caption("Paused")
paused = True
else:
pygame.display.set_caption(f"Key: {event.key} : {event.unicode}")
if not paused:
background_color = next(color_cycler)
#Graphics
screen.fill(background_color)
#Frame Change
pygame.display.update()
clock.tick(5)
pygame.quit()
编辑:更改为在暂停期间按问题忽略按键。
推荐阅读
- php - Laravel 5.8 Auth guard [api] 未定义
- javascript - 尝试从 JavaScript 读取本地文件时访问被拒绝
- java - 如何在类实例之间共享相同的变量?
- express - 用于身份验证的异步中间件的开玩笑测试
- macros - Gnu Assembler:评估宏参数中的符号?
- excel - 如何检查过滤器中的值是否存在?
- c# - 如何从后面的代码中获取价值以进行确认对话框
- android - 基于导航抽屉选择kotlin的浮动动作按钮代码行为
- date - 当相关日期没有数据(过去和未来)时,如何使用相同的度量进行计算?
- java - 我需要帮助 ERROR E/AndroidRuntime: FATAL EXCEPTION: main