【问题标题】:Pygame using time.sleep to wait for x seconds not executing code above itPygame 使用 time.sleep 等待 x 秒而不执行上面的代码
【发布时间】:2017-12-02 20:05:38
【问题描述】:

我正在尝试在 pygame 中重新创建 Pong,并尝试根据谁的得分将网的颜色更改为红色或绿色。我可以在有人得分后将其保持为红色或绿色,直到另一个人得分,但是,我想在 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 秒,然后更新记分牌并重新启动球,但是,整个事情会暂停并直接跳到将网颜色更改为黑色。我相信有更好的方法可以做到这一点,或者我使用 time.sleep 完全错误,但我不知道如何解决这个问题。

【问题讨论】:

  • 是否可以提供一个最小的工作示例而不是片段?乍一看,您的代码对我来说很合适。
  • 你不能使用time.sleep(),因为它会停止在程序中做任何事情的主循环。 mainloop 必须运行,您必须检查当前时间并在 3 秒后执行此部分。您可以使用pygame.time.get_ticks() 获取当前时间。

标签: python python-3.x pygame


【解决方案1】:

您不能在 PyGame(或任何 GUI 框架)中使用sleep(),因为它会停止更新其他元素的mainloop

您必须记住变量中的当前时间,然后在循环中将其与当前时间进行比较,看看是否还剩 3 秒。或者您必须创建自己的 EVENT,该事件将在 3 秒后触发 - 您必须在 for event 中检查此事件。

它可能需要对代码进行更多更改,所以我只能展示它的外观


使用时间/滴答声

# 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 ...

【讨论】:

猜你喜欢
  • 2012-02-12
  • 2020-06-14
  • 1970-01-01
  • 2020-12-12
  • 2013-06-13
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多