Hi,
I have been learning python and I have recently written a little
program that creates Hilbert curves which I submit to this list for
critique and review:
# Hilbert Curve
# David Zuccaro
# 18/09/2014
import sys
import pygame
import math
class cursor:
def __init__(self, a): # a should be a list of 2 numbers ie a
point.
self.a = a
def line(self, a):
# draw a line from he current position from the new
position; update current position
pygame.draw.lines(window, (255, 255, 255), True,
[[self.a[0], self.a[1]], [self.a[0] + a[0], self.a[1] + a[1]]], 1)
self.a[0] = self.a[0] + a[0]
self.a[1] = self.a[1] + a[1]
def hilbert(self, kind, order):
row = ((1,0,0,2), (0,1,1,3), (3,2,2,0), (2,3,3,1)) #
hilbert curve definition table 0 = A 1 = B ...
dir = ((0,3,2), (3,0,1), (1,2,3), (2,1,0)) #
definition of A, B, C, D
orient = ((0,-1), (-1,0), (0,1), (1,0)) # definition of
up, left, down, right
dist = 30 # length of segment
if order > 0:
for j in range(4):
self.hilbert(row[kind][j], order - 1) # keep on
hilberting until order = 0
if j < 3:
self.line([x * dist for x in
orient[dir[kind][j]]])
#this was the previous code but I thought it would be cleaner if
# more abstruse to do this all in one line ^
# if dir[kind][j] == 0:
# self.line(0, -dist) #up
# if dir[kind][j] == 1:
# self.line(-dist, 0) #left
# if dir[kind][j] == 2:
# self.line(0,dist) #down
# if dir[kind][j] == 3:
# self.line(dist, 0) #right
pygame.init()
#create the screen
window = pygame.display.set_mode((1900, 1000))
david = cursor([10,970]) # starting point increasing y moves
down screen
david.hilbert(0, 5) # create a fifth order hilbert curve
#draw it to the screen
pygame.display.flip()
#input handling (somewhat boilerplate code):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
#end
Output is here:
http://members.optuszoo.com.au/~david.zuccaro/hilbert2.png
https://en.wikipedia.org/wiki/Hilbert_curve