Here's my check_for_pause() function:
#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
Run Code Online (Sandbox Code Playgroud)
however this keeps making my program become unresponsive whenever I try to pause it! Basically, I want the variable "paused" to be either True or False. When the space bar is pressed, it should change to whichever one it isn't currently. Because I'm using check_for_pause() in another never-ending loop, I need to make it so that the function only stops executing when the space bar is released, otherwise if the user holds the space bar for more than a split second it will keep switching between True and False.
有什么想法为什么我的程序在运行时会变得无法响应?我知道这与等待空格键被释放的位有关,因为当我删除那段代码然后我的程序运行正常(但显然暂停功能不起作用).
你有一个主循环可能看起来像这样......
while True:
check_for_pause()
# Update the game
# Draw the game
Run Code Online (Sandbox Code Playgroud)
当您检查暂停,并按下空格键时,暂停将设置为True.然后,你有这个循环......
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
Run Code Online (Sandbox Code Playgroud)
这个循环的问题是你假设pygame.key.get_pressed()将继续返回最新信息.但是,查看pygame源代码,它似乎使用了SDL_GetKeyState,它作为其文档的一部分说.
Note: Use SDL_PumpEvents to update the state array.
Run Code Online (Sandbox Code Playgroud)
换句话说,重复调用pygame.key.get_pressed()将不会给你更新的键状态,如果你不另外调用类似的东西pygame.event.pump(),它实际上用新的键状态更新pygame.因此,您可以通过将泵功能引入循环来快速解决此问题,因为目前它只是永远运行.
话虽如此:不要这样做.如果你这样做,你的游戏在暂停时将无法做任何事情:这包括显示"暂停"屏幕,继续在后台播放音乐等.你想要做的是跟踪是否游戏暂停,如果是,则更改游戏的更新方式.
在游戏中您更新内容的部分,某些项目应该只在游戏暂停时才会发生.就像是...
paused = False
while True:
# This function should just return True or False, not have a loop inside of it.
paused = check_for_paused()
if not paused:
# This function moves your enemies, do physics, etc.
update_game()
draw_game()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,主循环仍将发生,游戏将继续绘制,输入将继续处理.然而,敌人和玩家将不会移动,因此游戏可以说是"暂停".
最后,还有一个事实是你依赖于get_key_pressed(),你可能不想这样做.请参阅我给出的其他类似答案,原因是您应该使用事件队列.
| 归档时间: |
|
| 查看次数: |
2056 次 |
| 最近记录: |