Skip to content

Instantly share code, notes, and snippets.

@pnf
Created June 24, 2013 14:03
Show Gist options
  • Save pnf/5850269 to your computer and use it in GitHub Desktop.
Save pnf/5850269 to your computer and use it in GitHub Desktop.
Print out a fractal tree
#!/usr/bin/env python
from math import *
import sys
# draw line from x,y of length s at angle theta, spawn growth of length s*r, theta+/-q unless n==0
def grow(x, y, theta, s, q, r, n):
ret = [(x,y,theta,s)]
n = n-1
if n>0:
x2 = x + s*cos(theta)
y2 = y + s*sin(theta)
ret.extend(grow(x2,y2,theta+q,s*r,q,r,n))
ret.extend(grow(x2,y2,theta-q,s*r,q,r,n))
return ret
def signum(x): return (x>0)-(x<0)
def stroke(dx,dy) :
return (('\\', '|', '/'),
('-', '*', '-'),
('/', '|', '\\'))[dy+1][1-dx]
def draw(p):
(x,y,theta,s) = p
(x,y) = (int(x+0.5),int(y+0.5))
ret = [(x,y,'*')] # point at x,y
dx = signum(int(10*cos(theta)+0.5))
dy = signum(int(10*sin(theta)+0.5))
ds = sqrt(dx*dx + dy*dy)
sym = stroke(dx,dy)
while s>ds:
s = s - ds
x = x+dx
y = y+dy
ret.append((x,y,sym))
return ret
if __name__ == "__main__":
q = pi/4.
r = 0.5
n = 8
t = pi/2.
s = 2. ** n
ps = grow(0,0,t,s,q,r,n)
#print ps
ss = []
for p in ps:
ss.extend(draw(p))
#print ss
xmin = min([p[0] for p in ss])-1
ymax = max([p[1] for p in ss])
# sort points descending in y, ascending in x
cmp=lambda p1,p2: signum(signum(p1[0]-p2[0]) - 10*signum(p1[1]-p2[1]))
ss.sort(cmp=cmp)
#print ss
lastx = xmin
lasty = ymax
for (x,y,c) in ss:
if x==lastx and y==lasty: continue
if y<lasty:
lasty=y
lastx=xmin
sys.stdout.write("\n")
sys.stdout.write(" "*(x-lastx-1) + c)
lastx=x
sys.stdout.write("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment