官术网_书友最值得收藏!

1.7 完整代碼

下面是繪制科赫雪花的完整代碼:

"""
koch.py
 
一個(gè)繪制科赫雪花的程序。
 
開(kāi)發(fā)者:Mahesh Venkitachalam
"""
 
 
import turtle
import math
 
#以遞歸的方式繪制科赫雪花
def drawKochSF(x1, y1, x2, y2, t):
    d = math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
    r = d/3.0
    h = r*math.sqrt(3)/2.0
    p3 = ((x1 + 2*x2)/3.0, (y1 + 2*y2)/3.0)
    p1 = ((2*x1 + x2)/3.0, (2*y1 + y2)/3.0)
    c = (0.5*(x1+x2), 0.5*(y1+y2))
    n = ((y1-y2)/d, (x2-x1)/d)
    p2 = (c[0]+h*n[0], c[1]+h*n[1])
    if d > 10:
        # 第1個(gè)片段
        drawKochSF(x1, y1, p1[0], p1[1], t)
        # 第2個(gè)片段
        drawKochSF(p1[0], p1[1], p2[0], p2[1], t)
        # #第3個(gè)片段
        drawKochSF(p2[0], p2[1], p3[0], p3[1], t)
        # 第4個(gè)片段
        drawKochSF(p3[0], p3[1], x2, y2, t)
    else:
        # 繪制中間的角
        t.up()
        t.setpos(p1[0], p1[1])
        t.down()
        t.setpos(p2[0], p2[1])
        t.setpos(p3[0], p3[1])
        # 繪制兩側(cè)的邊
        t.up()
        t.setpos(x1, y1)
        t.down()
        t.setpos(p1[0], p1[1])
        t.up()
        t.setpos(p3[0], p3[1])
        t.down()
        t.setpos(x2, y2)
 
# 函數(shù)main()
def main():
    print('Drawing the Koch Snowflake...')
    t = turtle.Turtle()
    t.hideturtle()
 
    # 繪制科赫雪花
    try:
        drawKochSF(-100, 0, 100, 0, t)
        drawKochSF(0, -173.2, -100, 0, t)
        drawKochSF(100, 0, 0, -173.2, t)
    except:
        print("Exception, exiting.")
        exit(0)
 
    # 等用戶在屏幕上單擊后退出
    turtle.Screen().exitonclick()
 
# 調(diào)用函數(shù)main()
if __name__ == '__main__':
    main()
主站蜘蛛池模板: 竹山县| 大理市| 蒙城县| 黄冈市| 江川县| 秭归县| 绥江县| 疏附县| 卢龙县| 青铜峡市| 两当县| 昂仁县| 胶州市| 肇源县| 瑞昌市| 酒泉市| 南靖县| 阳谷县| 隆昌县| 柞水县| 灌阳县| 鄂伦春自治旗| 垦利县| 乃东县| 永清县| 江北区| 栾城县| 光山县| 山阳县| 五寨县| 武城县| 吉林市| 石台县| 永川市| 鞍山市| 浦城县| 阿巴嘎旗| 津南区| 汨罗市| 遂昌县| 修文县|