Python Turtle:递归函数

时间:2015-10-15 09:27:34

标签: python turtle-graphics

我无法弄清楚如何创建一个基于用户输入绘制资本的函数。如果用户输入为1,则绘制一个I,如果为2,则绘制2个I,如下所示。

enter image description here

我可以通过使用简单的乌龟方法手动执行前2个级别,但是如何递归执行此操作以便它可以执行更高级别的操作?

def my_turtle_function(n):
    my_win = turtle.Screen()
    my_turtle = turtle.Turtle()
    my_turtle.speed(2)
    my_turtle.left(90)
    if n == 1:
        my_turtle.forward(100)
        my_turtle.right(90)
        my_turtle.forward(100)
        my_turtle.forward(-200)
        my_turtle.forward(100)
        my_turtle.right(90)
        my_turtle.forward(200)
        my_turtle.right(90)
        my_turtle.forward(100)
        my_turtle.forward(-200)
        my_turtle.forward(100)
        my_turtle.right(90)
        my_turtle.forward(100)

2 个答案:

答案 0 :(得分:1)

import turtle


def move_me(trt, step, n):
    while n > 0:
        tmp = trt.heading()
        trt.lt(90)
        trt.fd(step)
        trt.rt(90)
        trt.fd(step)
        move_me(trt, step / 2, n - 1)
        trt.fd(-2 * step)
        move_me(trt, step / 2, n - 1)
        trt.fd(step)
        trt.rt(90)
        trt.fd(2 * step)
        trt.rt(90)
        trt.fd(step)
        move_me(trt, step / 2, n - 1)
        trt.fd(-2 * step)
        move_me(trt, step / 2, n - 1)
        trt.fd(step)
        trt.rt(90)
        trt.fd(step)
        n -= 1
        trt.seth(tmp)

my_win = turtle.Screen()
my_turtle = turtle.Turtle()
my_turtle.speed(10)
move_me(my_turtle, 200, 3)

enter image description here

答案 1 :(得分:0)

如果你想以递归方式进行,你必须使用不同的参数再次调用该函数,例如:与"级别"小一点,笔画只有一半。确保乌龟位于同一个地方并且在方法的开始和结束时朝向相同的方向,然后在拐角处再次调用该功能。

这里有一些伪代码

def my_turtle_function(t, length, n):
    if n > 0:
        move up and left by length, face north
        call my_turtle_function(t, length/2, n-1)
        move right, right by length, face north
        call my_turtle_function(t, length/2, n-1)
        move left, down, down, left by length, face north
        call my_turtle_function(t, length/2, n-1)
        move right, right by length, face north
        call my_turtle_function(t, length/2, n-1)
        move back to starting point

你也可以通过使用“我'和酒吧的两边。