Python pygame运行一段时间后不断崩溃

Python pygame运行一段时间后不断崩溃,python,crash,pygame,Python,Crash,Pygame,这个程序在运行几秒钟后不知何故一直崩溃。有人能帮我吗? 这是一个可视化排序算法的程序。如果我做错了很多事情,我很抱歉,但我刚刚开始使用pygame,我仍然不能完全确定一切是如何工作的。 谢谢你的帮助 import random import time import pygame pygame.init() display_width=1200 display_height=800 gamedisplay=pygame.display.set_mode((display_width,disp

这个程序在运行几秒钟后不知何故一直崩溃。有人能帮我吗? 这是一个可视化排序算法的程序。如果我做错了很多事情,我很抱歉,但我刚刚开始使用pygame,我仍然不能完全确定一切是如何工作的。 谢谢你的帮助

import random
import time
import pygame

pygame.init()

display_width=1200
display_height=800

gamedisplay=pygame.display.set_mode((display_width,display_height))
clock=pygame.time.Clock()

correct=[]
shuffled=[]
for i in range(100):
    correct.append(i+1)
    shuffled.append(i+1)
random.shuffle(shuffled)

block_width=display_width/(len(shuffled))

def bar(block_width,shuffled):
    for i in shuffled:
        colour=(i,i,255)
        pygame.draw.rect(gamedisplay, colour, 
[shuffled.index(i)+shuffled.index(i)*block_width,750,block_width,-i-i*2.5])

def inserting(shuffled):
    a=0
    for i in range(len(shuffled)):
        x=a
        while shuffled[x]>shuffled[x+1] or x+1==len(shuffled):
            change=shuffled[x]
            shuffled.remove(shuffled[x])
            shuffled.insert(x+1,change)
        if a+1!=len(shuffled)-1:
            a=a+1
        else:
            a=0
    return shuffled

def Loop(block_width,shuffled,correct):
    FPS=10
    while shuffled!=correct:
        shuffled=inserting(shuffled)
        bar(block_width,shuffled)
        pygame.display.update()
        time.sleep(1/FPS)
    bar(block_width,shuffled)
    pygame.display.update()
    print(shuffled)

Loop(block_width,shuffled,correct)

您需要在pygame.event.get:中为事件使用事件循环,或者调用每个帧,否则操作系统会认为程序已锁定。我建议以这种方式重新构造循环函数:

def Loop(block_width,shuffled,correct):
    clock = pygame.time.Clock()  # A clock to limit the frame rate.
    FPS=10
    while True:
        for event in pygame.event.get():
            # Quit if the user closes the window.
            if event.type == pygame.QUIT:
                return

        # Fill the background with a color each frame.
        gamedisplay.fill((30, 30, 30))
        # If not sorted, keep sorting.
        if shuffled != correct:
            shuffled = inserting(shuffled)
            bar(block_width,shuffled)
            pygame.display.update()

        clock.tick(FPS)

Loop(block_width,shuffled,correct)
pygame.quit()

建议对变量和函数使用带下划线的小写字母snake_case names,例如def loop:。上面的camelcase是用于类的。只有一个问题,sys是什么?实际上不需要sys.exit。我已经删除了它,因为当函数返回并且程序到达文件末尾时,游戏将像其他程序一样正常退出。只有在使用空闲IDE时才需要pygame.quit调用,因为它无法关闭窗口。