0
点赞
收藏
分享

微信扫一扫

递归三角形

年迈的代码机器 2022-05-03 阅读 128
python

谢尔宾斯基三角形

以下是笔者自己摸索写出来的代码,语言是python3。谢尔宾斯基三角形的实现使用了递归,递归的自定义函数实现的主体功能是给定三角形的三个顶点的坐标,画出其三条边的中点连接而成的新三角形。

import math
from turtle import *
from random import *
def draw(a,b,c,n):
    if n<1:
        return
    else:
        ax, ay = a
        bx, by = b
        cx, cy = c
        d=dx,dy=(ax+bx)/2,(ay+by)/2
        e=ex, ey = (bx + cx) / 2, (by + cy) / 2
        f=fx, fy = (ax + cx) / 2, (ay + cy) / 2

        fillcolor(randint(0, 255), randint(0, 255), randint(0, 255))
        begin_fill()
        goto(dx,dy)
        pendown()
        goto(ex, ey)
        goto(fx, fy)
        goto(dx, dy)
        penup()
        end_fill()

        draw(a,d,f,n-1)
        draw(d, b, e, n - 1)
        draw(f, e, c, n - 1)
r=200
a=(-r/2,0)
b=(0,r*(3**0.5)/2)
c=(r/2,0)
ax,ay=a
bx,by=b
cx,cy=c
colormode(255)
pencolor(255,0,0)
fillcolor(0,255,0)
penup()
goto(ax,ay)
pendown()
goto(bx,by)
goto(cx,cy)
goto(ax,ay)
penup()
draw(a,b,c,4)
goto(0,-10)
mainloop()

这是参考的代码网站链接

举报

相关推荐

空心三角形

三角形面积

三角形判断

【数字三角形】

星号三角形

绘制三角形

0 条评论