您需要将算法与代码的绘制方面分开。
更新代码的一种简单方法是使用协程,该协程在递归
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您可能想要捕获的)。



