栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在显示更新之间使用pygame.time.wait()

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在显示更新之间使用pygame.time.wait()

您需要将算法与代码的绘制方面分开。

更新代码的一种简单方法是使用协程,该协程在递归

hanoi
函数的每个步骤中都将控制权交还给主循环,这又会绘制屏幕,​​并
hanoi
每秒将控制权交还给协程。

这是一个倒数的简化示例:

#-*- coding-utf8 -*-import pygameimport pygame.freetypepygame.init()screen = pygame.display.set_mode((300, 300))clock = pygame.time.Clock()font = pygame.freetype.SysFont(None, 30)def hanoi(num):    # We calculated something and want to print it    # So we give control back to the main loop    yield num    # We go to the next step of the recursive algorithm    yield from hanoi(num-1) #steps = hanoi(1000)ticks = Nonewhile True:    for event in pygame.event.get():        if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): exit()    # step every second only    if not ticks or pygame.time.get_ticks() - ticks >= 1000:        ticks = pygame.time.get_ticks()        screen.fill((200, 200, 200))        # the value from the next step of the coroutine        value = str(next(steps))        # render stuff onto the screen        font.render_to(screen, (100, 100), value)        pygame.display.flip()    clock.tick(60)

在代码中,您应该替换

    # updates and waits    printBackground()    printPieces(positions)    pg.time.wait(1000)

yield positions
控制返回到主循环和

hanoi(n-1, aux, destination, origin)

yield from hanoi(n-1, aux, destination, origin)

保持协程运行并致电

...screen.fill((200, 200, 200))positions = next(steps)printBackground()printPieces(positions)...

if
主循环中。

(如果算法完成,它将引发

StopIterationException
您可能想要捕获的)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611416.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号