我的目標是創建一個名爲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個條件)。
感謝您的建議,我意識到如果條件,但我會環顧網絡上的這些'洪水填充'算法你說。 – user2592835
你確定他不是在尋找BFS算法嗎?這就是我用來做掃雷的一次... –
我會看看'BFS'算法,但我的主要問題是找到一個不遞歸的算法。 – user2592835