I'm trying to implement an L-System generated Hilbert curve ,making use of python turtle graphics and recursion. My code seems to be working for the first two levels of recursion n=1 and n=2 but beyond that , the graphics just entangled (although I´m able to observe further modules within them), and I can´t seem to grasp what might be wrong here, do I need some intermediate steps to regenerate the Hilbert modules for deeper levels of recursion? Please see my code below , its relatively simple:
import turtle
def Hilbert_curve(A,rule,t,n):
if n>=1:
if rule:
t.left(90)
Hilbert_curve(A,not rule,t, n-1)
t.forward(A)
t.right(90)
Hilbert_curve(A, rule,t, n-1)
t.forward(A)
Hilbert_curve(A,rule,t, n-1)
t.right(90)
t.forward(A)
Hilbert_curve(A,not rule,t, n-1)
t.left(90)
else:
t.right(90)
Hilbert_curve(A,rule,t, n-1)
t.forward(A)
t.left(90)
Hilbert_curve(A,not rule,t, n-1)
t.forward(A)
Hilbert_curve(A,not rule,t, n-1)
t.left(90)
t.forward(A)
Hilbert_curve(A, rule,t, n-1)
t.right(90)
def main():
A=10
t=turtle.Turtle()
my_win=turtle.Screen()
n=2
rule=True
Hilbert_curve(A,rule,t,n)
my_win.exitonclick()
main()
The problem is with your
else
clause. Therule
is already inverted coming in to the function, so you need to treat therule
the same as the then clause:However, if we change
rule
from a boolean to a number,parity
, that's either 1 or -1, and then multiplyparity
by the angle, we can eliminate one of the two clauses of the orignalif
statement: