Skip to content Skip to sidebar Skip to footer

Pygame Using Time.sleep To Wait For X Seconds Not Executing Code Above It

I am trying to recreate Pong in pygame and have tried to change the color of the net to red or green, based on who scores. I am able to keep it red or green after someone scores, u

Solution 1:

You can't use sleep() in PyGame (or any GUI framework) because it stops mainloop which updates other elements.

You have to remember current time in variable and later in loop compare it with current time to see if 3 seconds left. Or you have to create own EVENT which will be fired after 3 second - and you have to check this event in for event.

It may need more changes in code so I can show only how it can look like


Using time/ticks

# create before mainloop with default value 
update_later = Noneelif pong.hitedge_right:     
   game_net.color = (255,0,0)     
   update_later = pygame.time.get_ticks() + 3000# 3000ms = 3s# somewhere in loopif update_later isnotNoneand pygame.time.get_ticks() >= update_later:
   # turn it off
   update_later = None

   scoreboard.sc1 +=1print(scoreboard.sc1)
   # ... rest ...

Using events

# create before mainloop with default value 
UPDATE_LATER = pygame.USEREVENT + 1elif pong.hitedge_right:     
   game_net.color = (255,0,0)     
   pygame.time.set_timer(UPDATE_LATER, 3000) # 3000ms = 3s# inside `for `event` loopif event.type == UPDATE_LATER:
   # turn it off
   pygame.time.set_timer(UPDATE_LATER, 0)

   scoreboard.sc1 +=1print(scoreboard.sc1)
   # ... rest ...

Post a Comment for "Pygame Using Time.sleep To Wait For X Seconds Not Executing Code Above It"