简体   繁体   English

如何冻结pygame窗口?

[英]How to freeze pygame window?

When I want to freeze my pygame window for a few seconds I usually use time.sleep().当我想冻结我的 pygame 窗口几秒钟时,我通常使用 time.sleep()。 However, if I accidentaly press any key on my keyboard meanwhile it detects the key after the time has passed.但是,如果我不小心按下键盘上的任何键,它会在时间过去后检测到该键。 Is there any way to freeze my pygame window so that the code won't consider the key pressed?有什么方法可以冻结我的 pygame 窗口,以便代码不会考虑按下的键?

Here is an example where the screen will change color every frame.这是屏幕每帧都会改变颜色的示例。 The title bar displays the last key pressed.标题栏显示最后按下的键。

If the space bar is pressed, the color change is paused for three seconds.如果按下空格键,颜色更改会暂停三秒钟。 Key presses are ignored, but other events may be handled during this period.按键被忽略,但在此期间可能会处理其他事件。

This is accomplished by setting up a custom timer and using a variable to track the paused state.这是通过设置自定义计时器并使用变量跟踪暂停状态来实现的。

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

EDIT: Change to ignore key-presses during the paused period as the question asked.编辑:更改为在问到问题的暂停期间忽略按键。

You have to use pygame.time.wait() rather than time.sleep().您必须使用 pygame.time.wait() 而不是 time.sleep()。 Be aware that the input has to be set in millisecond.请注意,输入必须以毫秒为单位设置。

See documentation: time.wait()请参阅文档: time.wait()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM