【问题标题】:Time delay in python/pygame without disrupting the game?python / pygame中的时间延迟而不破坏游戏?
【发布时间】:2014-12-22 22:09:23
【问题描述】:

我正在编写我正在制作的游戏的介绍代码,这里的介绍是将一系列图像以 4 秒的时间延迟传送。问题是,使用 time.sleep 方法也会弄乱主循环,因此程序会在这段时间内“挂起”。请问有什么建议吗? [Intro 和 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()

【问题讨论】:

  • sys.exit() 退出程序。之后的代码没有运行。

标签: python time pygame timedelay


【解决方案1】:

既不使用time.sleep(),也不使用time.time()pygame。改用pygame.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()

【讨论】:

    【解决方案2】:

    你可以添加一些逻辑,如果 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()
    

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 2013-10-23
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多