Pausing/ Unpausing In Pygame
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
Solution 1:
Don't use while
but variable paused = True
to control functions which move object
paused = FalsewhileTrue:
foreventin pygame.event.get()
ifevent.key == pygame.K_p: # Pausing
paused = Trueifevent.key == pygame.K_u: # Unpausing
paused = Falseifnot paused:
player.move()
enemy.move()
If you want to use one key to pause/unpause
ifevent.key == pygame.K_p: # Pausing/Unpausing
paused = not paused
Solution 2:
Furas's method works well, but here is an alternate method that you could use when your project grows larger.
Effectively you set an attribute called self.toggle
on your sprites, and only when that toggle attribute if False and a key is pressed is when your player can move. When the key to pause is pressed, self.toggle
becomes True and you cannot move anymore.
E.x:
classThing():
self.toggle = True# Some lines later...if event.key == pygame.K_LEFT andnot thingsprite.toggle:
# Move Code here# Some lines laterif keys[pygame.K_TAB]:
thingsprite.toggle = True# Therefore thingsprite cannot move left anymore# Alt method if you have more than one spritefor sprite in spritegroup:
sprite.toggle = True
Post a Comment for "Pausing/ Unpausing In Pygame"