Gamma Ghost
Gamma Ghost

Reputation: 11

Changing turtle look direction in Python?

In python's turtle graphics, i am having a turtle run through the 'for' loop. It is important that at the end, the turtle is looking the same direction as when it started, how can this be done with the following code:

 for x in range (op):
 x=random.randint(1,inp)
 kjr.speed(0)
 kjr.begin_fill()
 kjr.pendown()
 color=random.choice(cr)
 kjr.color(color)
 kjr.forward(x)
 kjr.left(90)
 y=random.randint(1,inptwo)
 kjr.forward(y)
 kjr.left(90)
 kjr.forward(x)
 kjr.left(90)
 kjr.forward(y)
 kjr.end_fill()
 kjr.penup()
 kjr.goto(x,y)

Upvotes: 0

Views: 785

Answers (3)

Shadid
Shadid

Reputation: 4272

You need to store the initial position of your turtle. You can do something like this

heading = turtle.heading()

then run through the for loop with your turtle

for x in range (op):
  x=random.randint(1,inp)
  kjr.speed(0)
  kjr.begin_fill()
  kjr.pendown()
  color=random.choice(cr)
  kjr.color(color)
  kjr.forward(x)
  kjr.left(90)
  y=random.randint(1,inptwo)
  kjr.forward(y)
  kjr.left(90)
  kjr.forward(x)
  kjr.left(90)
  kjr.forward(y)
  kjr.end_fill()
  kjr.penup()
  kjr.goto(x,y)

and once you are done go back to initial position

turtle.seth(heading)

Upvotes: 0

cdlane
cdlane

Reputation: 41925

It's not clear whether you want to restore the heading as the last step of your loop, or restore it after the loop completes. If you want to do it within the loop, since you do three right angles, kjr.left(90), you only need do a fourth to return your heading to where you started:

kjr.speed('fasest')

for x in range(op):
    x = random.randint(1, inp)

    color = random.choice(cr)
    kjr.color(color)
    kjr.pendown()

    kjr.begin_fill()
    kjr.forward(x)
    kjr.left(90)
    y = random.randint(1, inptwo)
    kjr.forward(y)
    kjr.left(90)
    kjr.forward(x)
    kjr.left(90)
    kjr.forward(y)
    kjr.end_fill()

    kjr.penup()
    kjr.goto(x, y)
    kjr.left(90)  # make turtle look in same direction as top of loop

You don't need save and restore the heading in this case. However, if you want to restore the heading after the loop, then you are best off saving the heading, not the position, before the loop, and restoring the heading after the loop as @mko (+1) suggests.

Upvotes: 0

Oo.oO
Oo.oO

Reputation: 13435

# store the value
heading = turtle.heading()    
...
# for loop
... 
turtle.seth( heading ) 

Upvotes: 2

Related Questions