2017-06-02 116 views
1

我使用Python和Pygame製作遊戲,並且我使用time.time來定時用戶瀏覽關卡。不過,我也有一個暫停菜單。當暫停菜單打開時,我怎麼能這樣做,time.time不會繼續?暫停time.time流

+0

您不需要暫停'time.time'本身來暫停遊戲中的定時器。 – user2357112

+0

如果您捕捉當前時間並從總時間中減去它,然後當玩家重新開始遊戲時,您將再次啓動計時器以獲取剩餘量? – ATLUS

回答

0

我想我會這樣做:使用clock.tick()返回的時間來增加每個幀的計時器,如果遊戲沒有暫停,並且當用戶暫停並取消暫停遊戲時調用它,而沒有參數放棄遊戲暫停時所經過的時間。

import sys 
import pygame as pg 


pg.init() 
screen = pg.display.set_mode((640, 480)) 
clock = pg.time.Clock() 
font = pg.font.Font(None, 30) 
timer = 0 
dt = 0 
paused = False 
running = True 

while running: 
    for event in pg.event.get(): 
     if event.type == pg.QUIT: 
      running = False 
     elif event.type == pg.KEYDOWN: 
      paused = not paused 
      # This is needed to discard the time that 
      # passed while the game was paused. 
      clock.tick() 

    if not paused: 
     timer += dt # Add delta time to increase the timer. 

     screen.fill((30, 30, 30)) 
     txt = font.render(str(round(timer, 2)), True, (90, 120, 40)) 
     screen.blit(txt, (20, 20)) 

     pg.display.flip() 
     dt = clock.tick(30)/1000 # dt = time in seconds since last tick. 

pg.quit() 
sys.exit()