Reputation: 376
I am having trouble figuring out how to create a function that draws a capital I based on a user input. If the user input is 1, it draws one I, if it's 2 it draws 2 I's, in this pattern seen below.
I can manually do the first 2 levels just by using simple turtle methods but how do you recursively do this so it will do it for higher levels?
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)
Upvotes: 0
Views: 736
Reputation: 4687
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)
Upvotes: 1
Reputation: 82899
If you want to do it recursively, you have to call the function again, with different parameters, e.g. with the "level" being one smaller, and the strokes being only half as long. Make sure that the turtle is in the same place and facing the same direction at the start and at the end of the method, then just call the function again when you are at the corners.
Here's some pseudo-code
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
You can also make the code a bit shorter by using loops for the two halves of the 'I' and the two sides of the bar.
Upvotes: 0