Skip to content

Instantly share code, notes, and snippets.

@eliblaney
Created September 23, 2019 22:10
Show Gist options
  • Save eliblaney/3607367fde9997cd9992e7d7f67a2b15 to your computer and use it in GitHub Desktop.
Save eliblaney/3607367fde9997cd9992e7d7f67a2b15 to your computer and use it in GitHub Desktop.
# dragoncurve.py
# Written by Eli Blaney
#
# Draws the dragon curve.
# Uses Python 3.
#
# Copyright (c) 2019 Eli Blaney.
# Licensed under WTFPL.
# www.wtfpl.net
import turtle
# Helper funciton to create the
# turtle that will draw the dragon curve
def createTurtle():
t = turtle.Turtle()
t.ht()
t.speed(0)
t.right(90)
return t
### This is algorithm 1, taken from Wikipedia. ###
### It uses a formula to calculate the direction ###
### of each step of the dragon curve. ###
def formulaDragon(step_size):
t = createTurtle()
n = 0
while(True):
turn = (((n & -n) << 1) & n) != 0
if(turn):
t.left(90)
else:
t.right(90)
t.forward(step_size)
n += 1
### This is my original algorithm to ###
### calculate the dragon curve. It ###
### is based on R/L sequence logic ###
# Creates each iteration of directions
def nextDragon(str):
if(len(str) == 0):
return "R";
swap = lambda c : ("L" if c == "R" else "R")
return str + "R" + "".join(list(map(swap, str[::-1])))
# Compiles the iterations and draws the curve
def dragon(step_size, instant, iterations):
t = createTurtle()
if(instant):
turtle.tracer(0, 0)
path = nextDragon('')
for _ in range(iterations):
path = nextDragon(path)
for c in path:
if c == "R":
t.right(90)
t.forward(step_size)
elif c == "L":
t.left(90)
t.forward(step_size)
turtle.update()
### PROGRAM ENTRANCE POINT ###
# Formulaic algorithm = wikipedia formula = formulaDragon
inputChoice = input("Enable formulaic algorithm? (Y/n) ").lower()
choice = inputChoice != "n" and inputChoice != "no" and inputChoice != "false"
if(choice):
# Because the formulaic algorithm executes infinitely,
# iterations and fast render mode aren't applicable
# Step size = length of each line
step_size = int(input("Step size: "))
formulaDragon(step_size)
else:
# Fast render = disable turtle rendering until finished
inputInstant = input("Fast render? (y/N) ").lower()
instant = not (inputInstant != "y" and inputInstant != "yes" and inputInstant != "true")
# Step size = length of each line
step_size = int(input("Step size: "))
# Iterations = how many dragon curve sequences
# to generate before stopping execution
iterations = int(input("Iterations: "))
dragon(step_size, instant, iterations)
### PROGRAM EXIT ###
input("Press enter to continue...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment