【发布时间】:2013-09-23 20:15:19
【问题描述】:
这是我的 check_for_pause() 函数:
#Check if the user is trying to pause the game
def check_for_pause():
keys=pygame.key.get_pressed() #Get status of all keys
if keys[K_SPACE]: #The space bar is held down
global paused #Make global so it can be edited
if paused==True: #It was paused, so unpause it
paused=False
elif paused==False: #It was playing, so pause it
paused=True
#Don't let the main loop continue until the space bar has been released again, otherwise the variable will flicker between True and False where the loop runs so fast!
space_bar_pressed=keys[K_SPACE]
while space_bar_pressed: #Repeat this loop until space_bar_pressed is False
keys=pygame.key.get_pressed()
if not keys[K_SPACE]: #Space bar has been released so set space_bar_pressed to False
space_bar_pressed=False
但是,每当我尝试暂停它时,这都会使我的程序变得无响应!基本上,我希望变量“暂停”为真或假。按下空格键时,它应该更改为当前不是的那个。因为我在另一个永无止境的循环中使用了 check_for_pause(),所以我需要使它仅在释放空格键时才停止执行,否则如果用户按住空格键超过一秒钟,它将不断在真假之间切换。
任何想法为什么我的程序在运行时变得无响应?我知道这与等待空格键被释放的位有关,因为当我删除那段代码时,我的程序运行良好(但显然暂停功能不起作用)。
【问题讨论】:
-
您不使用事件队列是否有原因?当一个键被按下时,该键的 single 事件被发送到队列中,释放时也是如此。使用队列将确保您的暂停开关只触发一次。
-
“但是,每当我尝试暂停它时,这都会使我的程序变得无响应!”嗯,当然可以。您正在运行一个循环,该循环在您释放空格键之前不会返回,因此程序可能无法响应其他任何内容,因为它仍在运行循环中的代码。
-
(这正是 为什么您应该为几乎所有 GUI 应用程序使用事件循环设计。)
-
一个问题是您正在检查键是否被按住。您想要切换
KEYDOWN事件。否则,您每秒会进行多次切换。