我试图制作一个类似于"排序声音的#pygame程序,"大约5-6秒后,它会冻结,直到排序结束。代码是:
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()
我不知道为什么它会冻结,也不知道为什么它等到排序结束才停止冻结。
答案 0 :(得分:2)
您的问题是您只在每个while循环传递开始时检查事件循环。你把所有的时间都花在了排序循环中,所以如果你不想等到排序结束,你应该在排序时检查事件:
...
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()
...