簡體   English   中英

如何凍結pygame窗口?

[英]How to freeze pygame window?

當我想凍結我的 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()

編輯:更改為在問到問題的暫停期間忽略按鍵。

您必須使用 pygame.time.wait() 而不是 time.sleep()。 請注意,輸入必須以毫秒為單位設置。

請參閱文檔: time.wait()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM