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

最佳答案

您可能需要使用事件循环(for event in pygame.event.get():)或在每个帧中调用 pygame.event.pump() ,否则操作系统会认为程序已锁定。我建议以这种方式重组Loop函数:

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

关于python - pygame运行一段时间后不断崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44868625/

相关文章:

xcode - 界面构建器在启动时崩溃

python - Pygame 填充和 blit 不编辑屏幕

python - 类型错误 : unbound method sprites()

python - 具有重力的 Sprite 不随重力移动

python - 正则表达式选择和替换双括号内的空格

python - to_sql 引发模糊 KeyError : <class 'numpy.float64' >

Python:避免使用多个嵌套的 for 循环来迭代字符串

python - 将 RGB 颜色转换为调色板中最接近的颜色(网络安全颜色)?

android - Appsflyer崩溃:致命异常:MultipleInstallBroadcastReceiver.java第43行的java.lang.NoSuchMethodError

objective-c - 了解 Objective-C 抛出调用堆栈