python / pygame的时间延迟而不会破坏游戏?

时间:2014-10-27 16:43:23

标签: python time pygame timedelay

我正在为我正在制作的游戏编写引入的代码,这里介绍的是在它们之间延迟4秒的一系列图像。问题是,使用time.sleep方法也会混淆主循环和程序,因此"挂起"在那个时期。有什么建议吗? [简介和TWD是声音对象]

a=0
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
            Intro.stop()
            TWD.stop()
    if a<=3:
        screen.blit(pygame.image.load(images[a]).convert(),(0,0))
        a=a+1
        if a>1:
                time.sleep(4)
    Intro.play()
    if a==4:
            Intro.stop()
            TWD.play()

    pygame.display.update()

2 个答案:

答案 0 :(得分:1)

你可以添加一些逻辑,只有4秒后才会提前a。 为此,您可以使用时间模块并获得起点last_time_ms 每次循环时,我们都会找到新的当前时间并找到此时间与last_time_ms之间的差异。如果大于4000毫秒,则递增a

我使用毫秒,因为我发现它通常比秒更方便。

import time

a=0
last_time_ms = int(round(time.time() * 1000))
while True:
    diff_time_ms = int(round(time.time() * 1000)) - last_time_ms
    if(diff_time_ms >= 4000):
        a += 1
        last_time_ms = int(round(time.time() * 1000))
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
            Intro.stop()
            TWD.stop()
    if a <= 3:
        screen.blit(pygame.image.load(images[a]).convert(),(0,0))
        Intro.play()
    if a == 4:
        Intro.stop()
        TWD.play()

    pygame.display.update()

答案 1 :(得分:1)

time.sleep()time.time()都不使用pygamepygame.time。请改用FPS = 30 # number of frames per second INTRO_DURATION = 4 # how long to play intro in seconds TICK = USEREVENT + 1 # event type pygame.time.set_timer(TICK, 1000) # fire the event (tick) every second clock = pygame.time.Clock() time_in_seconds = 0 while True: # for each frame for event in pygame.event.get(): if event.type == QUIT: Intro.stop() TWD.stop() pygame.quit() sys.exit() elif event.type == TICK: time_in_seconds += 1 if time_in_seconds < INTRO_DURATION: screen.blit(pygame.image.load(images[time_in_seconds]).convert(),(0,0)) Intro.play() elif time_in_seconds == INTRO_DURATION: Intro.stop() TWD.play() pygame.display.flip() clock.tick(FPS) 函数:

pygame.time.get_ticks()

如果您需要比一秒更精细的时间粒度,请使用{{1}}。

相关问题