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 = 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
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:
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
Post a Comment for "Pausing/ Unpausing In Pygame"