这里是我的check_for_pause()函数:为什么我的暂停系统不工作? (pygame的)
#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
然而,这一直让我的程序无响应每当我试图暂停!基本上,我希望变量“paused”为True或False。当按下空格键时,它应该更改为当前不在的那个。因为我在另一个永无止境的循环中使用了check_for_pause(),所以我需要这样做,以便函数只在空格键释放时才停止执行,否则如果用户将空格键保留一秒以上,它将会继续在True和False之间切换。
任何想法为什么我的程序在运行时无响应?我知道这是关于等待空格键被释放的位,因为当我删除那段代码时,我的程序运行正常(但显然暂停功能不起作用)。
是否有你不使用事件队列的原因?当按下某个键时,该键的一个* single *事件将被发送到队列,这与释放时相同。使用队列将确保您的暂停切换仅触发一次。 –
“但是,当我试图暂停时,这会使我的程序无法响应!”那当然是的。你正在运行一个循环,直到你释放空格键才会返回,所以程序不可能响应其他任何事情,因为它仍然在循环中运行代码。 – abarnert
(这正是_why_你应该为几乎任何GUI应用程序使用事件循环设计。) – abarnert