【问题标题】:filling a given colour in pygame在pygame中填充给定的颜色
【发布时间】:2013-08-02 12:00:58
【问题描述】:

我的目标是创建一个名为findList() 的函数,它保存一个点和屏幕表面的给定参数。

我的目标是计算该点的颜色,然后返回填充颜色的列表。

例如,如果屏幕上有一个红色圆圈,并且该点位于红色圆圈内,我希望能够返回一个包含该圆圈所有点的列表。

基本上,该点会扩大,避开所有其他颜色和屏幕边缘,直到它不能进一步扩大;然后函数返回所有创建点的列表。

这是我尝试过的:

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 个条件)。

【问题讨论】:

    标签: python image colors pygame


    【解决方案1】:

    本质上,您所要求的是“Flood-Fill”算法的第一部分,这是 Microsoft Paint 等程序用来用新颜色填充区域的程序。该算法首先找到所有相同颜色的连接像素,然后改变它们的颜色。查看wikipedia page 或stackoverflow question 了解python 实现。

    至于您的代码,有几处可以改进。我建议:

    1. 使用set() 而不是列表。这样您就不必处理重复的点
    2. 仅使用if/elif 子句而不是ifs。这将减少计算时间。
    3. 您的if 语句非常复杂但非常多余。您可能想尝试将它们分解为一组嵌套的 if/elif 语句。

    四处寻找 Flood-Fill 算法并尝试重写您拥有的算法。查看其他一些示例可能会帮助您显着简化代码。

    【讨论】:

    • 感谢您的建议,我了解 if 条件,但我会在互联网上查找您所说的这些“洪水填充”算法。
    • 你确定他不是在寻找 BFS 算法吗?这就是我曾经用来制作扫雷的东西......
    • 我会看看“BFS”算法,但我的主要问题是找到一种非递归算法。
    • BFS 不是递归的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多