我正在为我正在制作的游戏的介绍编写代码,这里的介绍是位图传输一系列图像,图像之间有 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()
您可以添加一些逻辑,只有在 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()
请勿将
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()
。
如果您设置了 tps,那么您可以通过每次迭代将变量加 1 来计数 1 秒:
clock = pygame.time.Clock()
count = 0
a=0
while True:
clock.tick(60) # It's best to set this to the refresh rate of ur monitor
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()
if count == 60: # incriment a every second
count = 0
a += 1
count += 1
pygame.display.update()