【问题标题】:Flash an image in pygame在pygame中闪烁图像
【发布时间】:2016-04-03 09:07:37
【问题描述】:

Python 版本:3.5.1 和 PyGame 版本:1.9.2a0

我的主要目标是在屏幕上闪烁图像。开 0.5 秒,关 0.5 秒。

我知道以下可以工作 60fps

frameCount = 0
imageOn = False
while 1:

    frameCount += 1



    if frameCount % 30 == 0:   #every 30 frames
        if imageOn == True:   #if it's on
            imageOn = False   #turn it off
        elif imageOn == False:   #if it's off
            imageOn = True   #turn it on



    clock.tick(60)

但我认为计算 int 中的帧数并不实际。最终我的帧号将太大而无法存储在 int 中。

如何在不将当前帧(在本例中为 frameCount)存储为整数的情况下每 x 秒闪烁一次图像?或者这实际上是最实用的方法吗?

【问题讨论】:

  • 请注意,python Ints 不限于 32 位:它们会自动转换为“bigint”。另请注意,在 60 fps 时,您的游戏需要运行大约 2.3 年才能需要超过 32 位。
  • 有趣点大安。同样,Racialz,如果您担心它,您可以有一个 if 语句可以重置它。 if frameCount > 1000000: frameCount = 0 编辑:答案之一解决了我之前所说的

标签: python python-3.x pygame


【解决方案1】:

避免让你的游戏依赖于帧速率,因为它会根据帧速率改变一切,如果计算机无法运行帧速率,整个游戏就会变慢。

这个变量将帮助我们跟踪过去了多长时间。 在while循环之前:

elapsed_time = 0

找出一帧所需的时间。 my_clock 是一个 pygame 时钟对象,60 是任意的

elapsed_time += my_clock.tick(60) # 60 fps, time is in milliseconds

你可以在你的 while 循环中的某处有一个 if 语句:

if elapsed_time > 500 # milliseconds, so .5 seconds
    imageOn = False if imageOn else True
    elapsed_time = 0 # so you can start counting again

编辑:我建议查看 Chritical 的答案,以获得更简单的方法来更改 imageOn 的 True False 值。我使用了内联条件,它有效,但没有必要。

【讨论】:

    【解决方案2】:

    您可以尝试使用 pygame timers

    import pygame
    from pygame.locals import *
    
    def flashImage():
        imageOn = not imageOn
    
    pygame.init()
    pygame.time.set_timer(USEREVENT+1, 500)  # 500 ms = 0.5 sec
    imageOn = False
    while 1:
        for event in pygame.event.get():
            if event.type == USEREVENT+1:
                flashImage()
            if event.type == QUIT:
                break
    

    【讨论】:

      【解决方案3】:

      我不知道这对您有多大帮助,但为了防止您的 frameCount 变得太大,您可以在更改 imageOn 的状态时使其等于 0,例如

      if frameCount % 30 == 0:
          if imageOn == True:
              imageOn = False
              frameCount = 0
          elif imageOn == False:
              imageOn = True
              frameCount = 0
      

      但是,如果没有其他人以更好的方式回答问题,我只建议将此作为最后的手段。希望这会有所帮助,即使是一点点!

      编辑:我刚刚意识到,您还可以通过简单地制作imageOn = not imageOn:来更简洁地构建您的代码:

      if frameCount % 30 == 0:
          imageOn = not imageOn
          frameCount = 0
      

      【讨论】:

      • 谢谢,这两个都很有帮助,我想知道python是否有你提到的一些技巧
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多