Skip to content

Instantly share code, notes, and snippets.

@System-Glitch
Created December 22, 2019 16:12
Show Gist options
  • Save System-Glitch/3fcb8297eb7f3f7281cf57245bda82e4 to your computer and use it in GitHub Desktop.
Save System-Glitch/3fcb8297eb7f3f7281cf57245bda82e4 to your computer and use it in GitHub Desktop.
Heighway dragon fractal recursive implementation in Python
import png #pip3 install pypng
import math
class Heighway:
def __init__(self, size = 1000):
self.size = size
def init_grid(self):
self.grid = []
for _ in range(self.size):
row = []
for _ in range(self.size):
row.append(255)
self.grid.append(row)
def next(self, x1, y1, x2, y2, k):
if k > 0:
xn = (x1 + x2) / 2 + (y2 - y1) / 2
yn = (y1 + y2) / 2 - (x2 - x1) / 2
self.next(x2, y2, xn, yn, k-1)
self.next(x1, y1, xn, yn, k-1)
else:
self.bresenham(x1, y1, x2, y2)
def bresenham(self, xa, ya, xb, yb):
xa = int(xa)
ya = int(ya)
xb = int(xb)
yb = int(yb)
dx = abs((int)(xb - xa))
sx = 1 if xa < xb else -1
dy = abs((int)(yb - ya))
sy = 1 if ya < yb else -1
err = int((dx if dx>dy else -dy)/2)
e2 = 0
while True:
self.grid[ya][xa] = 0
if xa == xb and ya == yb:
break
e2 = err
if e2 > -dx:
err -= dy
xa += sx
if e2 < dy:
err += dx
ya += sy
def draw(self, iterations, filename):
self.init_grid()
f = open(filename, 'wb')
w = png.Writer(self.size, self.size, greyscale=True)
s1 = self.size * 0.3
s2 = self.size - s1
self.next(s1, s1, s2, s2, iterations)
w.write(f, self.grid)
f.close()
# ----------------------------------------
f = Heighway()
for i in range(22):
f.draw(i, f'fractal_{i}.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment