如何停止 pygame 中的函数执行

How to stop the execution of the function in pygame

我正在尝试使用 pygame 制作一个算法可视化工具,我从实施线性搜索开始。我面临的问题是,在可视化中,我正在更改矩形的颜色,但该动画在 while 循环内重复自身。这是代码:
我希望动画停止,以便观众可以真正看到发生了什么。此外,我计划添加更多算法。

ARRAY = [2, 10, 5, 8, 7, 3, 43, 54, 23, 1]

def main():
    global SCREEN, CLOCK
    pygame.init()
    SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    CLOCK = pygame.time.Clock()
    num_font = pygame.font.SysFont("roboto", NUM_FONT_SIZE)

    x = 3
    y = 10

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
                pygame.quit()

        showArray(x, y, num_font)
        linearSearch(x, y)
        pygame.display.update()
        CLOCK.tick(60)

def linearSearch(x, y):
    num = 23
    box = pygame.Rect(x, y, BOX_SIZE+5, BOX_SIZE)
    for i in ARRAY:
        if i == num:
             pygame.draw.rect(SCREEN, RED, box, 1)
             pygame.draw.rect(SCREEN, GREEN, box, 1)
        else:
            box.x += BOX_SIZE + 5
            CLOCK.tick_busy_loop(10)
            pygame.draw.rect(SCREEN, RED, box, 1)
            pygame.display.update()

 def showArray(x, y, num_font):
    box = pygame.Rect(x, y, BOX_SIZE+5, BOX_SIZE)
    for i in ARRAY:
        box.x += BOX_SIZE + 5
        pygame.draw.rect(SCREEN, WHITE, box, 1)
        nums = num_font.render(str(i), True, WHITE)
        SCREEN.blit(nums, (box.x + 5, box.y + 5))

这是输出图像

你有一个应用程序循环,所以使用它。更改函数 linearSearch。列表索引必须是函数的参数,但是必须从函数中删除 for 循环:

def linearSearch(x, y, list_i):
    i = ARRAY[list_i]
    num = 23
    box = pygame.Rect(x + (BOX_SIZE+5)*(list_i+1), y, (BOX_SIZE+5), BOX_SIZE)
    color = GREEN if i == num else RED
    pygame.draw.rect(SCREEN, color, box, 1)

在主应用程序循环中遍历列表:

def main():
    # [...]

    list_i = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
                pygame.quit()

        showArray(x, y, num_font)

        if list_i < len(ARRAY):
            linearSearch(x, y, list_i)
            list_i += 1

        pygame.display.update()
        CLOCK.tick(60)