1

我想在 2 秒内将一个矩形从 alpha = 0 淡化到 alpha = 255。使用以下代码,我可以让矩形淡入,但我不知道让持续时间准确(尽可能准确)2 秒。

pygame.init()

#frames per second setting
FPS = 30
fpsClock = pygame.time.Clock()

#Set up window
screen = pygame.display.set_mode((1280,800))
shape = screen.convert_alpha()

#Colors
alpha = 0
WHITE = (255, 255, 255,alpha)
BLACK = (0,0,0)

#Stimuli
stimulus = pygame.Rect(100,250,100,100)

def fade():
    """Fades in stimulus"""
    global alpha
    alpha = alpha + 5   <--- (Do I change this increment?)
    #Draw on surface object
    screen.fill(BLACK)
    shape.fill(BLACK)
    pygame.draw.rect(shape,(255, 255, 255,alpha),stimulus)
    screen.blit(shape,(0,0))
    pygame.display.update(stimulus)
    fpsClock.tick(FPS)

while True:
    fade()

此外,如果我使用全屏,我应该使用标志 HWSURFACE 和 DOUBLEBUF 吗?谢谢。

4

1 回答 1

2

我会尝试测量自操作开始以来经过的实际时间,并alpha与剩余时间成正比。

类似的东西:

import time

def fade():
    DURATION = 2.0 # seconds
    start_time = time.clock()
    ratio = 0.0 # alpha as a float [0.0 .. 1.0]
    while ratio < 1.0:
        current_time = time.clock()
        ratio = (current_time - start_time) / DURATION
        if ratio > 1.0: # we're a bit late
            ratio = 1.0
        # all your drawing details go in the following call
        drawRectangle(coordinates, alpha = 255 * ratio)
        fpsClock.tick(FPS)

这样,如果tick工作不完美(确实如此),您的 alpha 会遵循其缺陷,而不是累积错误。当 2 秒结束时,您可以保证绘制了一个完全不透明的矩形。

于 2012-11-20T03:50:38.320 回答