如果您运行以下代码,它会创建我尝试创建的两个并排图纸。我需要弄清楚如何在第一次绘制它之后使递归方法停止。
import turtle
def drawTriangle(size):
turtle.left(30)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(120)
turtle.up()
turtle.forward(size)
turtle.right(30)
turtle.down()
def drawTriangles(size, depth):
if (depth < 1):
pass
else:
drawTriangle(size)
drawTriangles(size / 2, depth - 1)
turtle.up()
turtle.left(30)
turtle.forward(-size)
turtle.right(120)
turtle.forward(size * 2)
turtle.left(90)
turtle.down()
drawTriangle(size)
drawTriangles(size / 2, depth - 1)
turtle.up()
turtle.left(30)
turtle.forward(-size)
turtle.left(60)
turtle.forward(size * 2)
turtle.right(90)
turtle.down()
turtle.home()
turtle.left(90)
turtle.down()
turtle.speed("normal")
drawTriangles(100, 4)
input("pause")
答案 0 :(得分:1)
首先尝试一下。你真的很亲密。这似乎是一个有趣的项目。 :)
我已修复您的代码并将其包含在下方。您需要做的就是添加一个特殊条件来检查您是否在“基础”三角形上。如果是这样,请返回!
import turtle
def drawTriangle(size):
turtle.left(30)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(120)
turtle.up()
turtle.forward(size)
turtle.right(30)
turtle.down()
def drawTriangles(size, depth, baseTriangle = False):
if (depth < 1):
pass
else:
drawTriangle(size)
drawTriangles(size / 2, depth - 1)
if baseTriangle:
return
turtle.up()
turtle.left(30)
turtle.forward(-size)
turtle.right(120)
turtle.forward(size * 2)
turtle.left(90)
turtle.down()
drawTriangle(size)
drawTriangles(size / 2, depth - 1)
turtle.up()
turtle.left(30)
turtle.forward(-size)
turtle.left(60)
turtle.forward(size * 2)
turtle.right(90)
turtle.down()
turtle.home()
turtle.left(90)
turtle.down()
turtle.speed("normal")
drawTriangles(100, 4, baseTriangle = True)
input("pause")
答案 1 :(得分:0)
如果我猜测,可能是因为你正在调用以下两次(在drawTriangles()中)并且size变量的值在这两次调用之间不会改变。
drawTriangle(size)
drawTriangles(size / 2, depth - 1)
答案 2 :(得分:0)
这是我的解决方案。我已经整理了一些逻辑,所以,如果深度不为零,则绘制三角形并且触发递归两次,对于绘制三角形的每个顶角一次。最后,龟被移回到它开始的地方。
乌龟正常“向上”,只能在drawTriangle函数中“放下”。 drawTriangle函数现在也将乌龟返回到它开始的位置。
注意整数除法。在做其他任何事情之前,我已将大小转换为浮动。
import turtle
def drawTriangle(size):
turtle.down()
turtle.left(30)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(150)
turtle.up()
def drawTriangles(size, depth):
size = float(size)
if (depth > 0):
drawTriangle(size)
turtle.left(30)
turtle.forward(size)
turtle.right(30)
drawTriangles(size / 2, depth - 1)
turtle.right(90)
turtle.forward(size)
turtle.left(90)
drawTriangles(size / 2, depth - 1)
turtle.left(150)
turtle.forward(size)
turtle.right(150)
turtle.home()
turtle.left(90)
turtle.speed("normal")
drawTriangles(150.0, 5)
input("pause")