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