1

I am trying to make a sorting visualization in python using pygame. I must draw the lines in a loop because they will be moving around in the array. Because of the movement I must also redraw the background every loop. However, this is causing some terrible flickering. Any way to stop this? Or am I just doing this completely wrong?

import pygame

import numpy as np

Width = 800
Height = 500
numlines = 50
linewidth = int(Width / numlines)

win = pygame.display.set_mode((Width, Height))
pygame.display.set_caption("Quicksort Visualization")

white = (255, 255, 255)
black = (0, 0, 0)

randnums = np.random.randint(1, Height - 10, numlines)


def draw_arr(win, arr):
    win.fill(black)
    nums = arr
    i = 1
    for num in nums:
        pygame.draw.line(
            win,
            white,
            (i * linewidth, Height),
            (i * linewidth, Height - num),
            linewidth,
        )
        pygame.display.flip()
        i = i + 1


def main(win, arr):
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        draw_arr(win, arr)
    pygame.quit()


main(win, randnums)

1 Answers1

0

The problem is caused by calling pygame.display.flip() in the loop. Multiple calls to pygame.display.update() or pygame.display.flip() per frame cause flickering. Every time when you call pygame.display.flip(), the display is updated. Since the display is cleared at the beginning of the loop (win.fill(black)), the scene is incompletely updated.

Call it once at the end of the application loop:

def draw_arr(win, arr):
    win.fill(black)
    nums = arr
    i = 1
    for num in nums:
        pygame.draw.line(
            win,
            white,
            (i * linewidth, Height),
            (i * linewidth, Height - num),
            linewidth,
        )
        # pygame.display.flip() <--- DELETE
        i = i + 1

    pygame.display.flip() # <--- INSERT
Rabbid76
  • 202,892
  • 27
  • 131
  • 174