2017-07-02 71 views
0

這個程序以某種方式在運行幾秒後不斷崩潰。有人能幫我嗎? 這是一個可視化排序算法的程序。我很抱歉,如果我做了很多錯誤的事情,但我剛開始使用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) 

回答

1

你要麼需要使用一個事件循環(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() 
+0

[PEP 8](https://www.python.org/dev/peps/pep-0008/#naming-conventions)建議snake_case名稱中使用(小寫和下劃線)表示變量和函數,例如'def loop():'。上駱駝是上課的。 – skrx

+0

只是一個問題,什麼是sys? –

+0

你實際上並不需要'sys.exit()'在這裏(我已經移除了它),因爲當函數返回並且程序到達文件末尾時,遊戲將像其他任何程序一樣正常退出。只有在使用IDLE IDE時才需要調用'pygame.quit()',因爲它不能關閉窗口。 – skrx