bloodfill漫水填充海龟探索程序

bloodfill漫水填充海龟探索程序

以下程序是BUG程序,填充不完整,填充采用fill4即4方向填充,速度也慢,图像大了会有stack溢出,本人只是用来测试。

import turtle

def get_pixel_color(canvas, x, y):
    ids = canvas.find_overlapping(x, y, x, y)

    if len(ids) > 0:                 # 说明画布上有item,取最上面的item 
        item = ids[-1]
       
        color = canvas.itemcget(item,"fill") # 获取这个item的fill填充颜色
        color = color.upper()
        if color != '':r,g,b = canvas.winfo_rgb(color)
    else:                            # 否则画布上这个位置没有item,则取背景色     
        r,g,b = canvas.winfo_rgb(canvas._canvas.config('bg')[-1])
    r,g,b = r>>8,g>>8,b>>8
    return r,g,b
    
def fill(canvas,x,y,oldcolor,newcolor):
  
     if y<=abs(height//2) and x<=abs(width//2):
          y = -y
          ss = None
          all_items = cv.find_all()
          for item in all_items:
             zt = cv.itemconfig(item)['state'][-1]
             if zt=='hidden':continue
             ss = cv.find_overlapping(x,y,x,y)
             #print('ss=,',ss)
             if ss:break
         
          if ss == None or (isinstance(ss,tuple) and len(ss)==0 ):
              
             se = get_pixel_color(canvas, x,y)
            #print('se=',se)
             if se == oldcolor:
                i = cv.create_line(x,y,x+1,y+1,width=1,fill=newcolor)
                #print(cv.coords(i))
                cv.update()
                fill(canvas ,x,-y+1,oldcolor,newcolor)
                fill(canvas ,x,-y-1,oldcolor,newcolor)
                fill(canvas ,x+1,-y,oldcolor,newcolor)
                fill(canvas ,x-1,-y,oldcolor,newcolor)

turtle.delay(0)
turtle.speed(0)
width = turtle.window_width()
height = turtle.window_height()          
cv = turtle.getcanvas()
turtle.shape('circle')
turtle.shapesize(2) 
turtle.circle(10)
turtle.ht()
fill(cv,5,5,(255,255,255),'red')

李兴球

李兴球的博客是Python创意编程原创博客