欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

学习笔记(04):Python 面试100讲(基于Python3.x)-绘制谢尔宾斯基三角形

程序员文章站 2022-04-26 09:40:03
...

立即学习:https://edu.csdn.net/course/play/26755/340208?utm_source=blogtoedu

代码为

import turtle
#绘制三角形,左边为[[x1,y1], [x2,y2], [x3,y3]]
def draw_triangle(points, color, t):
    d.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])#绘制了3条边
    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 - 1], 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[0],points[2]), mid_point(points[1],points[2])], degree-1, t)
    
t = turtle.Turtle()
win = turtle.Screen()
points = [[-200,-100], [0,200], [200,-100]]
sierpinski(points, 4, t)
win.exitonclick()

结果为

学习笔记(04):Python 面试100讲(基于Python3.x)-绘制谢尔宾斯基三角形

 
相关标签: 研发管理