How to freeze pygame window?

青春壹個敷衍的年華 提交于 2021-01-07 03:44:59

问题


When I want to freeze my pygame window for a few seconds I usually use 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?


回答1:


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.




回答2:


You have to use pygame.time.wait() rather than time.sleep(). Be aware that the input has to be set in millisecond.

See documentation: time.wait()



来源:https://stackoverflow.com/questions/60821636/how-to-freeze-pygame-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!