Search code examples
pythonalgorithmpygamevisualizer

How to stop the execution of the function in pygame


I am trying to make an Algorithm Visualizer with pygame and I started by implementing Linear Search. The problem I am facing is that, in the visualization I am changing colour of the rectangle but that animation is repeating itself as it is inside the while loop. Here is the code:
I want that the animation should stop so that the viewer can actually see what happened. Further I am planning to add more algorithms.

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

Here is the image of the output image of output


Solution

  • You have an application loop, so use it. Change the function linearSearch. The list index has to be an argument to the function, but remove the for loop has to be removed form the function:

    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)
    

    Iterate through the list in the main application loop:

    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)