首页 > 解决方案 > 如何冻结pygame窗口?

问题描述

当我想冻结我的 pygame 窗口几秒钟时,我通常使用 time.sleep()。但是,如果我不小心按下了键盘上的任何键,它会在时间过去后检测到该键。有什么方法可以冻结我的 pygame 窗口,以便代码不会考虑按下的键?

标签: pythonpygame

解决方案


这是一个屏幕每帧都会改变颜色的例子。标题栏显示最后按下的键。

如果按下空格键,颜色更改将暂停三秒钟。按键被忽略,但在此期间可以处理其他事件。

这是通过设置自定义计时器并使用变量来跟踪暂停状态来实现的。

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

编辑:更改为在暂停期间按问题忽略按键。


推荐阅读