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

标签 python pygame towers-of-hanoi

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

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

我想知道的是我是否错误地使用了等待函数,或者在这种情况下我是否缺少任何其他有用的函数。

代码如下:

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)

使用让出位置将控制权交还给主循环

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)。

关于python - 在显示更新之间使用 pygame.time.wait(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53586802/

相关文章:

python 解析 print 或变量中的变量

python - 删除字符时向后打印字符串

python - 碰撞检测在 pygame 中不起作用

python - PyGame 无法在使用 Python3.4 的 Eclipse 中工作

java - Java汉诺塔时间分析

python - 在 Python 中对整数进行十六进制化

python - 我应该在 Python 中为专家系统使用知识引擎吗?

python - Pygame headless (headless)设置

python - python 中的汉诺塔,代码为 "counter"

java - 尝试让用户输入正常工作