如何在不追寻乌龟路径的情况下制作未填充的多边形?

问题描述

我正在做一个乌龟项目,用户可以在其中绘制自己的头像。

问题是,我希望用户能够决定他们所画的乌龟是否会被填充。

填充的部分很简单,因为认情况下,多边形将被填充, 但是我知道如何避免填充的唯一方法是回溯行,以使行的结尾与行的开头相遇。

是否有内置方法或更有效的方法来使空洞保持空白?

我当前方法的问题是每只乌龟的行数(参数)越多,程序运行的粘性就越大(该区域不会影响程序的平滑度)。

import turtle

wn = turtle.Screen()

pen = turtle.Turtle('circle')
pen.shapesize(0.1,0.1)

cor = []

# function to draw with the pen
def drag(x,y):
    wn.tracer(0)
    pen.goto(x,y)
    cor.append(pen.pos())

# function to break out of while loop
def fill():
    global done
    done = True

# function to break out of while loop and set fill to False
def nofill():
    global done,fill
    done = True
    fill = False
    
wn.listen()
wn.onkeypress(fill,'f')
wn.onkeypress(nofill,'n')

pen.ondrag(drag)

done = False
fill = True

while not done:
    wn.update()
    
pen.begin_poly()

if fill:
    for c in cor:
        pen.goto(c)
else:
    for c in cor[::-1]: # first go backards,then forward to avoid fill
        pen.goto(c)
    for c in cor:
        pen.goto(c)
        
pen.end_poly()

wn.register_shape("mypen",pen.get_poly())
wn.clear()

example = turtle.Turtle('mypen')

填充示例:

  • 运行上面的代码

  • 绘制形状。

  • 按f

enter image description here

没有填充的示例:

  • 运行上面的代码

  • 绘制形状。

  • 按n

enter image description here

解决方法

是否有内置方法或更有效的方法来保持 多空?

我不知道有什么功能可以避免乌龟光标上的闭合多边形-您的解决方案很聪明!下面是我对您的代码的简化以简化此方法:

from turtle import Screen,Turtle

def drag(x,y):
    ''' function to draw with the pen '''

    turtle.goto(x,y)

done = False
filled = True

def fill():
    ''' function to break out of while loop '''

    global done

    done = True

def nofill():
    ''' function to break out of while loop and set fill to False '''

    global done,filled

    done = True
    filled = False

screen = Screen()
screen.tracer(False)
screen.onkeypress(fill,'f')
screen.onkeypress(nofill,'n')
screen.listen()

turtle = Turtle('circle')
turtle.shapesize(0.1)
turtle.ondrag(drag)
turtle.begin_poly()

while not done:
    screen.update()

turtle.end_poly()

screen.clear()

polygon = turtle.get_poly()

if not filled:
    polygon = (*polygon,*polygon[::-1])

screen.register_shape("mypen",polygon)

example = Turtle('mypen')

screen.tracer(True)
screen.mainloop()

我当前方法的问题是行数更多 (参数)每只乌龟的线条越粘 程序运行

不幸的是,上面的代码并没有减少过多/过多的行数问题,也没有减少它的一般 stuckiness (无论 stucky 意味着什么,@ Nick。)