DePianoman
DePianoman

Reputation: 170

Why does my program freeze in the middle of it, and then unfreeze when finished? - pygame

I'm trying to make a pygame program similar to "Sound of Sorting," and after around 5-6 seconds, it freezes until the sort is finished. The code is:

import pygame, random
pygame.init()

clock = pygame.time.Clock()

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

x = []
ll = int(input("How big is the list you want to make? (Can't be more than your computer monitor's height: "))
for i in range(ll):
    x.append(i + 1)
random.shuffle(x)

h = pygame.display.Info().current_h
if(ll > h):
    quit()

gameDisplay = pygame.display.set_mode((ll, ll))

pygame.display.set_caption("Sort")

gameExit = False

while not gameExit:
    for event in pygame.event.get():
        if(event.type == pygame.QUIT):
            gameExit = True

    for i in range(len(x)):
        pygame.draw.rect(gameDisplay, white, [i, ll - x[i], 1, x[i]])

    n = len(x)
    for i in range(n - 1):
        small = i;
        for j in range(i + 1, n):
            if(x[small] > x[j]):
                small = j;
        temp = x[small]
        x[small] = x[i]
        x[i] = temp

        gameDisplay.fill(black)
        for i in range(len(x)):
            pygame.draw.rect(gameDisplay, white, [i, ll - x[i], 1, x[i]])

        clock.tick(60)

        pygame.display.update()

    pygame.display.update()

pygame.quit()
quit()

I have no idea why it freezes, nor why it waits until the sort is finished before it stops freezing.

Upvotes: 0

Views: 75

Answers (1)

Robb
Robb

Reputation: 433

Your issue is that you are only checking the event loop at the beginning of each while loop pass. You spend all of your time inside the sorting for loop so if you don't want to wait to the end of the sorting you should check the events while you sort:

...
while not gameExit:
    # draw
    n = len(x)
    for i in range(n - 1): 
        # sort
        # draw
        for event in pygame.event.get():
            if(event.type == pygame.QUIT):
                gameExit = True

        if gameExit:
            break

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

Upvotes: 2

Related Questions