分形曲线/征税曲线问题

时间:2017-11-11 21:43:42

标签: python recursion turtle-graphics fractals

我遇到了分形曲线的问题。我在OS X El Capitan上的Python 2.7和3.6上都试过这个。我不能让乌龟移动。这是直接从本书中获取的代码。 screenshot of turtle not moving将它设置为0,根据书中的说法,它应该画一条直线。但它没有动。这本书给了我们代码:

from turtle import Turtle

def cCurve(t, x1, y1, x2, y2, level):
    def drawLine(x1, y1, x2, y2):
        t.up()
        t.goto(x1, y1)
        t.down()
        t.goto(x2, y2)

        if level == 0:
            drawLine(x1, y1, x2, y2)
        else:
            xm = (x1 + x2 + y1 - y2) //2
            ym = (x2 + y1 + y2 - x1) //2
            cCurve(t, x1 ,y1 ,xm, ym, level -1)
            cCurve(t, xm, ym, x2, y2, level -1)
def main():
    level = int(input("Enter the level(0 or greater):" ))
    t = Turtle()
    t.hideturtle()
    cCurve(t, 50, -50, 50, 50, level)


main()

1 个答案:

答案 0 :(得分:0)

在解决了@trincot指出的缩进问题之后,我想证明在编写这样的程序时,人们和书本常常会错过Turtle的Vec2D类的价值。尽管Vec2D并不完美,但缺少一种访问单个元素且不进行除法的好方法,因此您必须使用乘法,它可以通过处理点而不是单独的X和Y值来清理代码:

from turtle import Screen, Turtle, Vec2D

X, Y = range(2)

def cCurve(turtle, p1, p2, level):

    def drawLine(turtle, p1, p2):
        turtle.penup()
        turtle.goto(p1)
        turtle.pendown()
        turtle.goto(p2)

    if level == 0:
        drawLine(turtle, p1, p2)
    else:
        s = (p1 + p2) * 0.5  # sum / 2
        d = (p1 - p2) * 0.5  # difference / 2

        m = Vec2D(s[X] + d[Y], s[Y] - d[X])

        cCurve(turtle, p1, m, level - 1)
        cCurve(turtle, m, p2, level - 1)

def main():
    level = int(input("Enter the level (0 or greater): "))

    screen = Screen()

    cCurve(Turtle(visible=False), Vec2D(50, -50), Vec2D(50, 50), level)

    screen.mainloop()

main()

enter image description here

您可以将Vec2D导入与乌龟无关的程序。