Search code examples
pythonfor-loopturtle-graphicspython-turtle

How do I get this turtle problem to properly increment?


Complete beginner to coding and Python here, so bear with me. I'm trying to solve this question:

A sprite is a simple spider shaped thing with n legs coming out from a center point. The angle between each leg is 360 / n degrees.

I'm having trouble with my move variable. I can get it to work for a single value, but I want it to work for any value input by the user.

import turtle
wn = turtle.Screen()
sprite = turtle.Turtle()

str_legs = input("How many legs does the sprite have?")
print(int(str_legs))

move = (360/int(str_legs)) 
for s in range (int(str_legs)): 
    sprite.fd(100)
    sprite.home()
    sprite.right(move)    
    move = ?

wn.exitonclick()

Solution

  • The problem is that home() always puts the turtle in the same heading and position (facing right). Instead, try to figure out how to return home but preserve the heading the turtle had when it started the current leg.

    import turtle
    
    legs = 8
    leg_size = 100
    degrees_per_turn = 360 / legs
    
    sprite = turtle.Turtle()
    
    for _ in range(legs):
        sprite.forward(leg_size)
        sprite.backward(leg_size)
        sprite.right(degrees_per_turn)
    
    turtle.exitonclick()
    

    If you want to stick with home(), you can turn one turn amount times the number of turns completed so far:

    # ...
    
    for i in range(legs):
        sprite.forward(leg_size)
        sprite.home()
        sprite.right(degrees_per_turn * (i + 1))
    
    # ...
    

    That said, I think the top version is cleaner, and take note because it's a common pattern in turtle applications. In general, the idea is to use relative functions rather than absolute functions. forward(), backward() and right() are examples of relative functions (they take the current position or heading into consideration), while home(), setposition() and setheading() are absolute functions (they disregard the current position or heading). It's like the difference between += (relative) and = (absolute) when working with integers.

    Although I didn't bother doing so here, typically, you'll want to penup() when heading back to home and pendown() again once you've repositioned the turtle.

    As a final side note, avoid input() until everything is totally working otherwise. It's tedious to have to type a number in every time you run the code during development, and it makes it harder for others to reproduce bugs if they're not sure what to type in if you post the code as a question.