Python海龜畫2維希爾伯特曲線
很簡單的題,這里用轉(zhuǎn)移矩陣的思路實(shí)現(xiàn),可以推廣到任意分型

代碼:
import turtle
#思路:
#把曲線分解為基本圖形,找出基本圖形在分形時轉(zhuǎn)移關(guān)系,表達(dá)為矩陣
#把希爾伯特曲線一層層拆,通過解析希爾伯特編碼深度優(yōu)先的方式畫出來
#比如以A為最外層畫兩層
#就是畫轉(zhuǎn)移矩陣對應(yīng)圖形,對應(yīng)圖形規(guī)模為原來1/3,然后用自身連接,更深層依次類推
#畫自身的筆畫需要計(jì)數(shù)
#先實(shí)現(xiàn)畫4個基本圖形的算法
#需要三個參數(shù)
#一個是畫哪一個圖形
#一個是畫圖形的哪一個筆畫
#一個是筆畫長度
initial_matrix=[[0,1,2,3],[2,1,0,3],[2,3,0,1],[0,3,2,1]]
transfer_matrix=[[3,0,0,1],[2,1,1,0],[1,2,2,3],[0,3,3,2]]
def get_stroke(item_type, item_stroke):
? ?first_point = initial_matrix[item_type][item_stroke]
? ?last_point = initial_matrix[item_type][item_stroke + 1]
? ?# 需要向上:0到1,3到2
? ?if (first_point == 0 and last_point == 1) or (first_point == 3 and last_point == 2):
? ? ? ?return 1
? ?# 需要向下:1到0,2到3
? ?if (first_point == 1 and last_point == 0) or (first_point == 2 and last_point == 3):
? ? ? ?return 3
? ?# 需要向左:1到2,0到3
? ?if (first_point == 1 and last_point == 2) or (first_point == 0 and last_point == 3):
? ? ? ?return 0
? ?# 需要向右:2到1,3到0
? ?if (first_point == 2 and last_point == 1) or (first_point == 3 and last_point == 0):
? ? ? ?return 2
def draw_init(t,item_type,item_stroke,item_length):
? ?if item_stroke==3:
? ? ? ?return
? ?t.setheading(90 * get_stroke(item_type, item_stroke))
? ?t.forward(item_length)
def draw_all(t,layer_num,max_item,max_length):
? ?#解析希爾伯特曲線要深度優(yōu)先
? ?stroke_list=[0]*layer_num
? ?for i in range(0, 4 ** layer_num):
? ? ? ?buff = i
? ? ? ?for j in range(1, layer_num + 1):
? ? ? ? ? ?stroke_list[layer_num- j] = buff % 4
? ? ? ? ? ?buff = int(buff / 4)
? ? ? ? ? ?#改變筆畫列表
? ? ? ? ? ?#再根據(jù)筆畫列表確定下一劃怎么畫
? ? ? ?stroke_len = 0
? ? ? ?for stroke_len_ in range(0, len(stroke_list)):
? ? ? ? ? ?if stroke_list[stroke_len_] != 3:
? ? ? ? ? ? ? ?stroke_len = stroke_len_ + 1
? ? ? ?stroke = 3
? ? ? ?item_type = ?max_item
? ? ? ?for stroke_ in range(0, stroke_len):
? ? ? ? ? ?stroke = stroke_list[stroke_]
? ? ? ? ? ?if stroke_ != stroke_len - 1:
? ? ? ? ? ? ? ?item_type = transfer_matrix[item_type][stroke_list[stroke_]]
? ? ? ?draw_init(t, item_type, stroke, float(max_length)/(2**layer_num-1))
? ? ? ? ? ?#創(chuàng)建畫布
turtle.screensize(2000,2000)
t=turtle.Pen()#調(diào)用函數(shù)畫曲線
draw_all(t,3,1,200)暫停觀看
turtle.exitonclick()