user12460693
user12460693

Reputation:

About Loops in Turtle

I would like to ask a question about some kind of loop which i am trying to use in my program. So for this purpose i am going to share the code of the function for drawing a triangle which exists in my program;

def drawing_triangle():

    turtle.forward(50)
    turtle.left(120)
    turtle.forward(50)
    turtle.left(120)
    turtle.forward(50)
    turtle.left(120)
    turtle.penup()
    turtle.forward(50)
    turtle.forward(10)
    turtle.pendown()

So this is the function of drawing a triangle and when i try to run the program it gives me an output like this below;

output_theoneiget

As you can see in the picture, it prints the triangles side by side but i want them to start a new row at every four triangle like in this picture below;

output_theoneiwant

In conclusion, my question is how can i get an output like in the second picture?

Thanks in advance.

Upvotes: 0

Views: 95

Answers (1)

Erdős-Bacon
Erdős-Bacon

Reputation: 908

Have you tried reading over the docs for the turtle package yet? https://docs.python.org/3.7/library/turtle.html

I think the difficulty you're having comes from all the turtle's motion being relative to its current position. But for making a new "triangle line", you want to "reset" the turtle's position all the way back to the left.

Take a look at the command turtle.setposition(x, y) -- this sets the turtle's location in an absolute manner. Instead of moving relative to where it currently is, it just "jumps" to (x, y).

You could place that command in part of a for-loop after you've drawn a series of triangles to reset to the left. You'll have to manage your for-loop to iteratively set the height so each subsequent row is placed below the last, but that's the only real difficulty.

Alternatively, you could count how many triangles you've drawn so far in a given "triangle line", then relatively re-position backwards by moving left based on width/spacing and how many triangles have been drawn so far. But I think absolute positioning is probably the easier approach and a good technique to get used to anyway.

Upvotes: 1

Related Questions