Reputation:
I'm having trouble writing a recursive function that draws circles to a certain 'depth'.
import turtle
# These are basic instructions that do not affect the drawing if changed, only the appearance of the entities within the window
turtle.mode('logo')
turtle.speed(1)
turtle.shape('classic')
turtle.title("Circle")
def recCircle(d, r):
if d == 0:
pass
if d == 1:
print("Drawing to the depth of: ", d)
turtle.down()
turtle.circle(r)
turtle.up()
else:
print("Drawing to the depth of: ", d)
turtle.circle(r)
turtle.seth(90)
turtle.down()
recCircle(d - 1, (r / 2)) # Draw the leftmost circle
turtle.seth(360)
turtle.up
turtle.seth(270)
turtle.forward(2 * r)
turtle.down()
recCircle(d - 1, - r / 2) # Draw the rightmost circle
turtle.up()
turtle.seth(360)
turtle.forward(2*r)
def main():
d = 3 #depth of recursion
r = 100 #radius of circle
recCircle(d, r)
turtle.done()
main()
I believe the problem lies around line 20
turtle.circle(r)
I can not figure out how to return the turtle to the same location and orientation.
turtle.home or turtle.goto as I'm trying not to use those
Upvotes: 0
Views: 1574
Reputation: 41872
Specific issues with your code:
turtle.mode('logo')
I understand the desire to work with North == 0 but in the case of this design, it's not to your advantage and I'd stay with the default orientation. This won't work:
turtle.up
It needs to be turtle.up()
. I don't see how you got your example output with this in the code as it should throw an error. This is OK:
turtle.seth(270)
as long as you're assuming a vertical orientation. But in general, if we want to draw at any angle, you can't use setheading()
as it's as absolute as turtle.goto()
or turtle.home()
. But this, seems strange:
turtle.seth(360)
vs. simply turtle.setheading(0)
. A key concept when doing a drawing like this is to return the turtle to where it started, either implicitly in the drawing command, or explicitly by undoing anything you did to position the turtle. Below's my complete rework of your code:
from turtle import Screen, Turtle
def recCircle(depth, radius):
if depth == 0:
return
print("Drawing to the depth of: ", depth)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
if depth > 1:
length = 11 * radius / 8 # no specific ratio provided, so eyeballed
turtle.left(45)
turtle.forward(length)
turtle.right(45)
recCircle(depth - 1, radius / 2) # Draw the leftmost circle
turtle.backward((2 * length ** 2) ** 0.5)
recCircle(depth - 1, radius / 2) # Draw the rightmost circle
turtle.right(45)
turtle.forward(length)
turtle.left(45)
screen = Screen()
screen.title("Circle")
turtle = Turtle('classic')
turtle.speed('fast')
depth = 3 # depth of recursion
radius = 100 # radius of circle
recCircle(depth, radius)
screen.exitonclick()
Upvotes: 1