我正在尝试在pygame中重新创建乒乓球,并试图根据谁的分数将网的颜色更改为红色或绿色。我能够在某人得分后保持红色或绿色,直到另一个人得分为止,但是,我想在3秒钟后将净颜色更改为黑色。我尝试使用Time.sleep(3),但是每当我这样做时,网将保持黑色。
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)
理想情况下,它应该将红色变成3秒钟,然后更新记分板并重新启动球,但是,整个过程都停了下来,然后直接跳过将净颜色更改为黑色。我相信有一种更好的方法可以做到这一点,或者也许我正在使用时间。完全错了,但我不知道如何解决这个问题。
您不能在pygame(或任何GUI框架)中使用sleep()
,因为它停止了更新其他元素的mainloop
。
您必须在变量中记住当前时间,然后在循环中与当前时间进行比较,以查看是否剩下3秒。或者,您必须创建自己的事件,该事件将在3秒后发射 - 您必须在for event
中检查此事件。
它可能需要更多的代码更改,因此我只能显示它看起来像
使用时间/tick
# 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 ...
使用事件
# 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 ...