【问题标题】:How to freeze pygame window?如何冻结pygame窗口?
【发布时间】:2020-03-23 21:14:41
【问题描述】:

当我想冻结我的 pygame 窗口几秒钟时,我通常使用 time.sleep()。但是,如果我不小心按下键盘上的任何键,它会在时间过去后检测到该键。有什么方法可以冻结我的 pygame 窗口,以便代码不会考虑按下的键?

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    你必须使用 pygame.time.wait() 而不是 time.sleep()。请注意,输入必须以毫秒为单位进行设置。

    查看文档:time.wait()

    【讨论】:

      【解决方案2】:

      这是一个屏幕每帧都会改变颜色的示例。标题栏显示最后按下的键。

      如果按下空格键,颜色更改会暂停三秒钟。按键被忽略,但在此期间可能会处理其他事件。

      这是通过设置自定义计时器并使用变量来跟踪暂停状态来实现的。

      import pygame
      import itertools
      
      CUSTOM_TIMER_EVENT = pygame.USEREVENT + 1
      my_colors = ["red", "orange", "yellow", "green", "blue", "purple"]
      # create an iterator that will repeat these colours forever
      color_cycler = itertools.cycle([pygame.color.Color(c) for c in my_colors])
      
      pygame.init()
      pygame.font.init()
      clock = pygame.time.Clock()
      screen = pygame.display.set_mode([320,240])
      pygame.display.set_caption("Timer Example")
      done = False
      paused = False
      background_color = next(color_cycler)
      while not done:
          for event in pygame.event.get():
              if event.type == pygame.QUIT:
                  done = True
              elif event.type == CUSTOM_TIMER_EVENT:
                  paused = False
                  pygame.display.set_caption("")
                  pygame.time.set_timer(CUSTOM_TIMER_EVENT, 0)  # cancel the timer
              elif not paused and event.type == pygame.KEYDOWN:
                  if event.key == pygame.K_SPACE:
                      pygame.time.set_timer(CUSTOM_TIMER_EVENT, 3000)  
                      pygame.display.set_caption("Paused")
                      paused = True
                  else:
                      pygame.display.set_caption(f"Key: {event.key} : {event.unicode}")
          if not paused:
              background_color = next(color_cycler)
          #Graphics
          screen.fill(background_color)
          #Frame Change
          pygame.display.update()
          clock.tick(5)
      pygame.quit()
      

      编辑:更改为在暂停期间按问题忽略按键。

      【讨论】:

        猜你喜欢
        • 2020-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多