Created
February 7, 2017 17:10
-
-
Save alcarney/6e84961e5ce51c45248f5a5dcadaf59d to your computer and use it in GitHub Desktop.
Using an L-System this draws the Sierpinski Triangle to a given level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import turtle | |
def run_system(seed, rule, iterations): | |
""" | |
Given the inital seed for the system and the rule function | |
run the system for the given number of iterations | |
""" | |
string = seed | |
for _ in range(iterations): | |
string = "".join(rule(c) for c in string) | |
return string | |
def visualise_system(seed, rule, iterations, visual_rules): | |
# Run the system to get the state of the system to viusalise | |
string = run_system(seed, rule, iterations) | |
print(string) | |
# Fire up the turtle | |
turtle.st() | |
turtle.degrees() | |
turtle.home() | |
turtle.setheading(0) | |
turtle.clear() | |
#turtle.tracer(False) | |
for c in string: | |
visual_rules[c]() | |
def sierpinski_triangle(iterations): | |
def rule(c): | |
if c == 'F': | |
return 'F-G+F+G-F' | |
if c == 'G': | |
return 'GG' | |
return c | |
visual_rules = {'F': lambda: turtle.fd(10), | |
'G': lambda: turtle.fd(10), | |
'+': lambda: turtle.left(120), | |
'-': lambda: turtle.right(120)} | |
visualise_system('F-G-G', rule, iterations, visual_rules) | |
sierpinski_triangle(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment