前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >94 - 绘制谢尔宾斯基三角形

94 - 绘制谢尔宾斯基三角形

原创
作者头像
ruochen
修改2021-06-28 10:20:03
6190
修改2021-06-28 10:20:03
举报
文章被收录于专栏:若尘的技术专栏

绘制谢尔宾斯基三角形

代码语言:txt
复制
import turtle

# 绘制单个三角形
# [[x1,y1], [x2,y2], [x3,y3]]
def draw_triangle(points, color, t):
    t.fillcolor(color)
    t.up()
    # 将画笔移动到第一个点
    t.goto(points[0][0], points[0][1])
    t.down()
    t.begin_fill()
    t.goto(points[1][0], points[1][1])
    t.goto(points[2][0], points[2][1])
    t.goto(points[0][0], points[0][1])
    t.end_fill()
    
# 计算两点的中位点坐标
def mid_point(p1, p2):
    return ((p1[0] + p2[0])/2, (p1[1] + p2[1])/2)

def sierpinski(points, degree, t):
    colormap = ['blue', 'red', 'green', 'yellow', 'violet', 'orange']
    # 绘制大的三角形
    draw_triangle(points, colormap[degree], t)
    if degree >= 0:
        # 绘制左下角三角形
        sierpinski([points[0], mid_point(points[0], points[1]), mid_point(points[0], points[2])], degree - 1, t)
        # 绘制上方的三角形
        sierpinski([points[1], mid_point(points[0], points[1]), mid_point(points[1], points[2])], degree - 1, t)
        # 绘制右下角三角形
        sierpinski([points[2], mid_point(points[2], points[1]), mid_point(points[0], points[2])], degree - 1, t)
        
t = turtle.Turtle()
win = turtle.Screen()
points = [[-200, -100], [0, 200], [200, -100]]
sierpinski(points, 4, t)
win.exitonclick()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 绘制谢尔宾斯基三角形
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档