Как остановить выполнение функции в Pygame - PullRequest
1 голос
/ 09 апреля 2020

Я пытаюсь создать визуализатор алгоритмов с помощью pygame, и я начал с реализации линейного поиска. Проблема, с которой я сталкиваюсь, заключается в том, что в визуализации я меняю цвет прямоугольника, но эта анимация повторяется, как и внутри, пока l oop. Вот код:
Я хочу, чтобы анимация остановилась, чтобы зритель мог увидеть, что произошло. В дальнейшем я планирую добавить больше алгоритмов.

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

Вот изображение с выхода image of output

1 Ответ

1 голос
/ 09 апреля 2020

У вас есть приложение l oop, так что используйте его. Измените функцию linearSearch. Индекс списка должен быть аргументом функции, но удалить for l oop необходимо удалить из функции:

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)

Итерация по списку в главном приложении l oop:

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