Python海龟借用sprites的fill命令绘制洪水填充封闭区域源代码

Python海龟借用sprites的fill命令绘制洪水填充封闭区域源代码

Python洪水填充画封闭图形填充演示by李兴球

import random
import turtle
from sprites import fill,Key,Mouse,mouse_pos

ysb = ['red','orange','yellow','green','cyan',
       'blue','purple','pink','brown','lime']

screen = turtle.Screen()    
screen.xy_grid()
screen.setup(480,720)
turtle.shape('blank')
turtle.hideturtle()
turtle.goto(0,100)
turtle.pd()
turtle.pensize(2)
turtle.circle(100)    
turtle.penup()
fill(50,150,mode=0)      # 在(50,150)坐标开始填充,模式为2
fill(-50,150,fillcolor='red',mode=2)      # 在(50,150)坐标开始填充,模式为2
fill(50,250,fillcolor='blue',mode=2)      # 在(50,150)坐标开始填充,模式为2
fill(-50,250,fillcolor='green',mode=2)      # 在(50,150)坐标开始填充,模式为2
ft = ('黑体',14,'normal')
s = '请画封闭图形,然后单击右键填充'
turtle.home();turtle.write(s,align='center',font=ft)

spacekey = Key('space')           # 实例化空格键
leftkey = Mouse()                 # 实例化鼠标左键
rightkey = Mouse(3)               # 实例化鼠标右键
turtle.ht()                       # 隐藏海龟
turtle.pensize(4)
turtle.pencolor('red')
screen.listen()                   # 监听按键检测
screen.colormode(255)
while True:
    turtle.goto(mouse_pos())
    if spacekey.isdownup():         # 如果按空格键,更换画笔颜色
        turtle.pencolor(random.choice(ysb))
    if leftkey.down():              # 如果单击左键,则落笔 
        turtle.pendown()
    else:
        turtle.penup()              # 否则抬笔
    if rightkey.isdownup():         # 如果单击右键并松开,则填充
        fx,fy = rightkey.pos
        r  = random.randint(0,255)
        g  = random.randint(0,255)
        b  = random.randint(0,255)
        fill(fx,fy,fillcolor=(r,g,b),mode=2) # 默认模式为2,共有0,1,2共有3种模式,请自行尝试
        
    screen.update()

李兴球

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