问题
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, until a different person scores, however, I want to change the net color back to black after 3 seconds. I tried using time.sleep(3) but whenever I did it, the net will stay as black. `
elif pong.hitedge_right:
game_net.color = (255,0,0)
time.sleep(3)
scoreboard.sc1 +=1
print(scoreboard.sc1)
pong.centerx = int(screensize[0] * 0.5)
pong.centery = int(screensize[1] * 0.5)
scoreboard.text = scoreboard.font.render('{0} {1}'.formatscoreboard.sc1,scoreboard.sc2), True, (255, 255, 255))
pong.direction = [random.choice(directions),random.choice(directions2)]
pong.speedx = 2
pong.speedy = 3
pong.hitedge_right = False
running+=1
game_net.color=(0,0,0)
Ideally, it should turn red for 3 seconds, then update the scoreboard and restart the ball, however, instead, the entire thing pauses and it skips straight to changing the net color to black. I believe there is a better way of doing this, or maybe I am using time.sleep totally wrong, but I have no idea how to fix this.
回答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 = None
elif pong.hitedge_right:
game_net.color = (255,0,0)
update_later = pygame.time.get_ticks() + 3000 # 3000ms = 3s
# somewhere in loop
if update_later is not None and pygame.time.get_ticks() >= update_later:
# turn it off
update_later = None
scoreboard.sc1 +=1
print(scoreboard.sc1)
# ... rest ...
Using events
# create before mainloop with default value
UPDATE_LATER = pygame.USEREVENT + 1
elif pong.hitedge_right:
game_net.color = (255,0,0)
pygame.time.set_timer(UPDATE_LATER, 3000) # 3000ms = 3s
# inside `for `event` loop
if event.type == UPDATE_LATER:
# turn it off
pygame.time.set_timer(UPDATE_LATER, 0)
scoreboard.sc1 +=1
print(scoreboard.sc1)
# ... rest ...
来源:https://stackoverflow.com/questions/47604195/pygame-using-time-sleep-to-wait-for-x-seconds-not-executing-code-above-it