2014-10-27 688 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功能來代替。