Skip to content

Instantly share code, notes, and snippets.

@QuantumFractal
Created September 8, 2016 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuantumFractal/96c4c20aff02ba647acfe9674febc85c to your computer and use it in GitHub Desktop.
Save QuantumFractal/96c4c20aff02ba647acfe9674febc85c to your computer and use it in GitHub Desktop.
sierpinski generation
import turtle
import math
WIDTH, HEIGHT = 800, 600
ANGLE = 60
SCALAR = 1.585
DEPTH = 8
def main():
wn = turtle.Screen()
wn.delay(0)
wn.bgcolor("lightgreen")
cursor = turtle.Turtle()
cursor.speed(0)
cursor.penup()
cursor.pensize(2)
cursor.setx(-WIDTH // 2)
cursor.sety(-HEIGHT // 2 - 20)
cursor.pendown()
cursor.color("green")
grammar = {"rules": {'A': '+B-A-B+',
'B': '-A+B+A-'},
"variables": ('A', 'B'),
"constants": ('+', '-')}
print("[------Generic System Plotter------]")
print("variables: " + str(grammar["variables"]))
print("constants: " + str(grammar["constants"]))
print("rules: ")
for k, v in grammar["rules"].items():
print("\t {} -> \"{}\"".format(k, v))
print("depth: " + str(DEPTH))
print("\nGenerating instructions...")
instructions = generate_sierpinski(DEPTH, 'A', grammar)
print("Result: \n" + instructions)
DISTANCE = WIDTH / (2 ** DEPTH)
tasks = {"A": lambda t: t.forward(DISTANCE),
"B": lambda t: t.forward(DISTANCE),
"-": lambda t: t.right(ANGLE),
"+": lambda t: t.left(ANGLE)}
print("\nDrawing instructions...")
draw_instructions(instructions, tasks, cursor)
print("\nDONE!")
wn.mainloop()
def draw_instructions(instructions, tasks, cursor):
for token in instructions:
if token in tasks:
tasks[token](cursor)
def generate_sierpinski(depth, token, grammar):
if depth == 0:
return token
if token in grammar["constants"]:
return token
if token in grammar["variables"]:
rule = grammar["rules"][token]
expression = ''
for character in rule:
expression += generate_sierpinski(depth - 1, character, grammar)
return expression
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment