在 Pygame 中暂停/取消暂停 [英] pausing/ Unpausing in Pygame
问题描述
这是我正在尝试更改的蛇游戏代码的一部分,以便我可以暂停,我正在设法暂停,但是我无法取消暂停(游戏冻结),我正在尝试使用键 p 暂停和 u 取消暂停(之前的键用于移动和退出,它们按预期工作).有什么办法可以做到不冻结?此外,欢迎解释为什么它现在不起作用.
This is the part of mine snake game code that I'm trying to change so I can pause, I'm managing to pause with it, but I'm failing in unpausing(the game freezes), I'm trying to use the key p to pause and u to unpause(the previous keys are for movement and quitting, they function as intended). Any way to do that without freezing? Also, any explanation on why it's not working now is welcomed.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quiting()
elif event.type == pygame.KEYDOWN:
# Choose direction by user input, block opposite directions
key_right = event.key in (pygame.K_RIGHT, pygame.K_d)
key_left = event.key in (pygame.K_LEFT, pygame.K_a)
key_down = event.key in (pygame.K_DOWN, pygame.K_s)
key_up = event.key in (pygame.K_UP, pygame.K_w)
if key_right and direction != "L":
direction = "R"
elif key_left and direction != "R":
direction = "L"
elif key_down and direction != "U":
direction = "D"
elif key_up and direction != "D":
direction = "U"
elif event.key == pygame.K_ESCAPE:
quiting() # It will quit when esc is pressed
while event.key == pygame.K_p: # Pausing
if event.key == pygame.K_u: # Unpausing
break
推荐答案
不要使用 while
而是使用变量 paused = True
来控制移动对象的函数
Don't use while
but variable paused = True
to control functions which move object
paused = False
while True:
for event in pygame.event.get()
if event.key == pygame.K_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
player.move()
enemy.move()
如果您想使用一键暂停/取消暂停
If you want to use one key to pause/unpause
if event.key == pygame.K_p: # Pausing/Unpausing
paused = not paused
这篇关于在 Pygame 中暂停/取消暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!