2014-10-27 189 views
0

我正在编写我正在制作的游戏介绍的代码,这里介绍的是在它们之间延时4秒的一系列图像。问题是,使用time.sleep方法也会使主循环混乱,程序因此“挂起”了那段时间。有什么建议吗? [简介和TWD是健全的对象]python/pygame中的时间延迟而不会中断游戏?

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() 
+0

'sys.exit()'退出程序。它之后的代码没有运行。 – jfs 2014-10-28 09:31:03

回答

1

你可以在加入一些逻辑只会提前a如果4个秒钟过去了。 要做到这一点,你可以使用时间模块,并获得一个起点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

既不使用也不time.sleep()time.time()pygame。如果你需要一秒钟更细的时间粒度

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():使用pygame.time功能来代替。