Reputation: 51
We've just started programming at uni. One of our tasks is to create a fractal tree with the L-system with a turtle in python. This one:
1. variables : X F
2. constants : + − [ ]
3. start : X
4. rules : (X → F-[[X]+X]+F[+FX]-X), (F → FF)
5. angle : 25°
Code:
def fraktal_plante(padde, depth):
Xmerke(padde, depth-1) # X
def Xmerke(padde, depth):
if depth > 0:# X ->
padde.forward(10) # F
padde.right(25) # -
padde.setposition()
padde.setheading() # [
padde.setheading() # [
Xmerke(padde, depth-1) # X
padde.heading()
padde.goto() # ]
padde.left(25) # +
Xmerke(padde, depth-1) # X
padde.heading() # ]
padde.left(25) # +
padde.forward(10) # F
padde.setposition()
padde.setheading() # [
padde.left(25) # +
padde.forward(10) # F
Xmerke(padde, depth-1) # X
padde.heading()
padde.goto() # ]
padde.right(25) # -
Xmerke(padde, depth-1) # X
def Fmerke (padde, depth):
if depth > 0: # Y ->
padde.forward(10) # F
padde.forward(10) # F
As you can see it's messy. I am wondering how to make the turtle remember its position and heading " [ " for then to return to it afterwards " ] ".
I am really new to this so please answer in a clear and easy way to understand.
Upvotes: 3
Views: 3287
Reputation: 123473
You can get a turtle's current heading by calling turtle.heading()
. Likewise, its current position is returned by turtle.position()
. Therefore you can use them to save its current state, and then later use those values to restore it. Here's a trivial example illustrating using them to do what you want:
from __future__ import print_function
def get_turtle_state(turtle):
""" Return turtle's current heading and position. """
return turtle.heading(), turtle.position()
def restore_turtle_state(turtle, state):
""" Set the turtle's heading and position to the given values. """
turtle.setheading(state[0])
turtle.setposition(state[1][0], state[1][1])
if __name__ == '__main__':
import turtle
tortoise = turtle.Turtle()
saved_state = get_turtle_state(tortoise)
print('saved state:', saved_state) # -> (0.0, (0.00,0.00))
tortoise.forward(100)
tortoise.left(90)
print('changed state:', get_turtle_state(tortoise)) # -> (90.0, (100.00,0.00))
restore_turtle_state(tortoise, saved_state)
print('restored state:', get_turtle_state(tortoise)) # -> (0.0, (0.00,0.00))
turtle.getscreen().ontimer(turtle.bye, 2000) # End script after a delay.
turtle.mainloop()
Upvotes: 3