python/pygame中的时间延迟是否会中断游戏?
我正在为我正在制作的一个游戏的介绍编写代码,这里的介绍是以4秒的时间延迟快速播放一系列图像。问题是,使用time.sleep方法也会弄乱主循环,因此程序会在这段时间内“挂起”。有什么建议吗?[简介和TWD是声音对象]python/pygame中的时间延迟是否会中断游戏?,python,time,pygame,timedelay,Python,Time,Pygame,Timedelay,我正在为我正在制作的一个游戏的介绍编写代码,这里的介绍是以4秒的时间延迟快速播放一系列图像。问题是,使用time.sleep方法也会弄乱主循环,因此程序会在这段时间内“挂起”。有什么建议吗?[简介和TWD是声音对象] a=0 while True: for event in pygame.event.get(): if event.type==QUIT: pygame.quit() sys.exit()
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()
a=0
尽管如此:
对于pygame.event.get()中的事件:
如果event.type==退出:
pygame.quit()
sys.exit()
简介停止
TWD.stop()
如果a1:
时间。睡眠(4)
游戏介绍
如果a==4:
简介停止
TWD.play()
pygame.display.update()
您可以在中添加一些逻辑,如果4秒钟过去,这些逻辑只会前进a
。
为此,您可以使用时间模块并获得一个起点last\u time\u 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()
导入时间
a=0
last_time_ms=int(四舍五入(time.time()*1000))
尽管如此:
diff_time_ms=int(四舍五入(time.time()*1000))-最后一次
如果(差异时间>=4000):
a+=1
last_time_ms=int(四舍五入(time.time()*1000))
对于pygame.event.get()中的事件:
如果event.type==退出:
pygame.quit()
sys.exit()
简介停止
TWD.stop()
如果使用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)
FPS=30#每秒帧数
介绍持续时间=4#以秒为单位播放介绍的时间
TICK=USEREVENT+1#事件类型
pygame.time.set_timer(滴答,1000)#每秒触发事件(滴答)
clock=pygame.time.clock()
以秒为单位的时间=0
如果为True:#对于每个帧
对于pygame.event.get()中的事件:
如果event.type==退出:
简介停止
TWD.stop()
pygame.quit()
sys.exit()
elif event.type==勾选:
时间单位为秒+=1
如果时间(以秒为单位)小于介绍持续时间:
screen.blit(pygame.image.load(图像[时间单位为秒]).convert(),(0,0))
游戏介绍
elif时间(以秒为单位)=介绍持续时间:
简介停止
TWD.play()
pygame.display.flip()
时钟滴答声(FPS)
如果需要比1秒更精细的时间粒度,请使用pygame.time.get_ticks()
。sys.exit()
退出程序。之后的代码不会运行。