Issue
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
Solution
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
Answered By - furas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.