2013-08-02 214 views
0

我的目標是創建一個名爲findList()的函數,該函數保存點和屏幕表面的給定參數。在pygame中填充給定的顏色

我的目標是計算該點的顏色,然後返回填充顏色的列表。

例如,如果有一個屏幕上有一個紅色圓圈,並且該點位於紅色圓圈內,我希望能夠返回一個包含該圓圈所有點的列表。

基本上,點擴大,避免所有其他顏色和屏幕的邊緣,直到它不能再擴大;然後函數返回所有創建點的列表。

這裏是我的嘗試:

def findList(point,screen): 
    directions=[(0,0)] 
    myList=[] 
    myList.append(point) 
    startColour=screen.get_at(point) 
    i=0 
    loop=0 
    while True: 
     loop=loop+1 
     print(loop) 
     directions=[] 
     print("Length of myList: "+str(len(myList))) 
     for i in range(len(myList)): 
      if myList[i][0]+1<WINDOWWIDTH and screen.get_at((myList[i][0]+1,myList[i [1]))==startColour and myList[i][0]+1 not in myList and myList[i][0]+1 not in directions: 
       directions.append((myList[i][0]+1,myList[i][1])) 
      if myList[i][0]-1>0 and screen.get_at((myList[i][0]-1,myList[i][1]))==startColour and myList[i][0]-1 not in myList and myList[i][0]-1 not in directions: 
       directions.append((myList[i][0]-1,myList[i][1])) 
      if myList[i][1]+1<WINDOWHEIGHT and screen.get_at((myList[i][0],myList[i][1]+1))==startColour and myList[i][1]+1 not in myList and myList[i][1]+1 not in directions: 
       directions.append((myList[i][0],myList[i][1]+1)) 
      if myList[i][1]-1>0 and screen.get_at((myList[i][0],myList[i][1]-1))==startColour and myList[i][1]-1 not in myList and myList[i][1]-1 not in directions: 
       directions.append((myList[i][0],myList[i][1]-1)) 

     print(len(directions)) 
     for i in directions: 
      myList.append(i) 
     if len(directions)==0: 
      break 
    print("Exited loop.") 
    return myList 

我知道的編碼風格是可怕的,其中很大一部分可能是無用的,但一般的問題是功能(可能)的作品,但刻意緩慢,似乎增加以前添加的像素很多,直到我可憐的小上網本不能再處理它正在使用的100 000個點。

如果有人可以爲更好的功能提出一些建議,那真的會對我有幫助,因爲只有13歲,我對這些混亂的代碼感到困惑(請注意ifs中的4個條件)。

回答

0

本質上,你所要求的是'Flood-Fill'算法的第一部分,這是Microsoft Paint用來使用新顏色填充區域的程序。該算法首先找到相同顏色的所有連接像素,然後更改其顏色。查看wikipedia pagestackoverflow question獲取python實現。

至於你的代碼,有幾件事情可以改進。我會建議:

  1. 使用set()而不是列表。這樣您就不必處理重複的點
  2. 只能使用if/elif而不是if。這將減少計算時間。
  3. 您的if陳述非常複雜但非常冗餘。您可能想要嘗試將它們分解爲嵌套的if/elif語句組。

四處尋找洪水填充算法,並嘗試重寫你有什麼。查看其他一些示例可能會幫助您顯着簡化代碼。

+0

感謝您的建議,我意識到如果條件,但我會環顧網絡上的這些'洪水填充'算法你說。 – user2592835

+0

你確定他不是在尋找BFS算法嗎?這就是我用來做掃雷的一次... –

+0

我會看看'BFS'算法,但我的主要問題是找到一個不遞歸的算法。 – user2592835