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

Using pygame.time.wait() between display updates

我目前正在Pygame开发一个简单的汉诺塔动画,它应该显示汉诺塔的正确解决方案,每秒移动一个。

但是,在我的河内求解算法中,我尝试更新显示并在每次移动后使用 pygame.time.wait();并且程序不会更新一个动作并等待一秒钟,而是等待动作总数秒数,然后显示同时完成所有动作的塔。

我想知道的是我是否错误地使用了 wait 函数,或者在这种情况下是否还有其他有用的函数被我遗漏了。

代码如下:

def hanoi(n, origin, destination, aux):
    # solves the game with n pieces

    if n == 1:
        positions[0] = destination

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

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

        positions[n-1] = destination

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

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

和循环:

while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        if running:
            hanoi(numPieces, 0, 2, 1)
            running = False

谢谢!

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

更新代码的一种简单方法是使用协程,在递归 hanoi 函数的每一步,将控制权交还给主循环,主循环依次绘制屏幕,​​并且每秒将控制权交还给 hanoi 协程。

这是一个简单的倒计时示例:

#-*- coding-utf8 -*-
import pygame
import pygame.freetype

pygame.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 = None
while 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,你可能想要捕获它)。