这是我的蛇游戏代码的一部分,我试图改变所以我可以暂停,我已经设法暂停,但我没有失败(游戏冻结) ),我试图使用键p暂停和你取消暂停(之前的键用于移动和退出,它们按预期运行)。没有冻结的任何方式吗?此外,欢迎任何关于它为什么现在不起作用的解释。
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
答案 0 :(得分:3)
请勿使用while
但使用变量paused = True
来控制移动对象的函数
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 event.key == pygame.K_p: # Pausing/Unpausing
paused = not paused
答案 1 :(得分:0)
Furas的方法运行良好,但是这是您可以在项目变大时使用的替代方法。
有效地在精灵上设置一个名为self.toggle
的属性,并且只有在按下False并按下一个键时,该切换属性才是您的玩家可以移动的。当按下暂停键时,self.toggle
变为真,你不能再移动了。
E.x:
class Thing():
self.toggle = True
# Some lines later...
if event.key == pygame.K_LEFT and not thingsprite.toggle:
# Move Code here
# Some lines later
if keys[pygame.K_TAB]:
thingsprite.toggle = True
# Therefore thingsprite cannot move left anymore
# Alt method if you have more than one sprite
for sprite in spritegroup:
sprite.toggle = True