2016-04-03 185 views
2

Python版本:3.5.1和PyGame版本:1.9.2a0在pygame中闪烁图像

我的主要目标是在屏幕上闪烁图像。开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秒刷新一次图像?或者,这实际上是最实际的方法吗?

+0

请注意,python Ints不限于32位:它们会自动转换为“bigints”。另外请注意,在60fps时,您的游戏需要运行大约2.3年,然后才需要超过32位。 –

+0

有趣的一点大安。还有Racialz,如果你担心它,你可以有一个if语句来重置它。如果frameCount> 1000000:frameCount = 0编辑:其中一个答案解决了我以前说 –

回答

1

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

这个变量将帮助我们跟踪已经过了多久。 while while循环之前:

elapsed_time = 0 

为了找出帧需要的时间。 MY_CLOCK是pygame的时钟对象,60是任意

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

而且你可以有一个if语句某处while循环:

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值。我使用了内联条件,这是有效的,但没有必要。

0

我不知道这对您有多大帮助,但是为了防止您的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 
+0

谢谢,这些都是有帮助的,我想知道如果蟒蛇有一些像你提到的技巧 – Keatinge

0

你可以尝试使用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