谢尔宾斯基三角形

这篇文章介绍了如何使用Python的turtle模块创建一个Sierpinski三角形,通过递归调用函数,实现了图形的分形绘制,展示了三次递归的思想并演示了颜色填充功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import turtle
t = turtle.Turtle()
t.left(90)
mywin = t.getscreen()
t.speed(0)

def drawtriangle(points,color,t):
    t.fillcolor(color)
    t.up()
    t.goto(points[0])
    t.down()
    t.begin_fill()
    t.goto(points[1])
    t.goto(points[2])
    t.goto(points[0])
    t.end_fill()

def getmid(p1,p2):
    return ((p1[0]+p2[0])/2,(p1[1]+p2[1])/2)

def sierpinski(points,degree,t):
    colormap = ['blue','red','green','yellow','violet','white','orange']
    drawtriangle(points,colormap[degree],t)
    if degree>0:
        sierpinski([points[0],getmid(points[0],points[1]),getmid(points[0],points[2])],degree-1,t)
        sierpinski([points[1],getmid(points[0],points[1]),getmid(points[1],points[2])],degree-1,t)
        sierpinski([points[2],getmid(points[2],points[1]),getmid(points[0],points[2])],degree-1,t)

mypoints = [(-400,-200),(0,400),(400,-200)]
sierpinski(mypoints,5,t)
mywin.exitonclick()

重点在把我三次递归思想;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值