欢迎光临散文网 会员登陆 & 注册

Python海龟画2维希尔伯特曲线

2023-03-17 21:51 作者:funnymason  | 我要投稿

很简单的题,这里用转移矩阵的思路实现,可以推广到任意分型

2维希尔伯特曲线分型转移关系

代码:

import turtle
#思路:
#把曲线分解为基本图形,找出基本图形在分形时转移关系,表达为矩阵
#把希尔伯特曲线一层层拆,通过解析希尔伯特编码深度优先的方式画出来
#比如以A为最外层画两层
#就是画转移矩阵对应图形,对应图形规模为原来1/3,然后用自身连接,更深层依次类推
#画自身的笔画需要计数
#先实现画4个基本图形的算法
#需要三个参数
#一个是画哪一个图形
#一个是画图形的哪一个笔画
#一个是笔画长度


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):
   #解析希尔伯特曲线要深度优先
   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)
           #改变笔画列表
           #再根据笔画列表确定下一划怎么画
       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))
           

#创建画布
turtle.screensize(2000,2000)
t=turtle.Pen()

#调用函数画曲线
draw_all(t,3,1,200)

暂停观看
turtle.exitonclick()


Python海龟画2维希尔伯特曲线的评论 (共 条)

分享到微博请遵守国家法律