這裏是我的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