2017-05-05

Python 小烏龜(Turtle)

我的老天啊,怎麼又會遇到這隻可愛的小烏龜!

Python 提供 turtle 繪圖功能來建立影像。
import turtle
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.left(120)
turtle.forward(50)

turtle.penup()
turtle.forward(50)

turtle.pendown()
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.left(120)
turtle.forward(50)
turtle.right(120)

turtle.penup()
turtle.forward(100)
turtle.right(60)

turtle.pendown()
turtle.forward(50)
turtle.right(120)
turtle.forward(50)
turtle.right(120)
turtle.forward(50)
想像在烏龜尾巴綁一枝筆,然後可以控制烏龜前進(forward)、後退(back)、右轉(right)、左轉(left)、抬起尾巴(penup,不會劃線)、放下尾巴(pendown,劃線)、、、等許多動作。


Koch 曲線

畢業三百年後又遇到您了,有興趣的可以先看這裡
def draw(t, length, loop):
    leng = length / 3;
    if loop == 0:
        return
    elif loop == 1:
        dr(t, length)
        return
        
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
    t.left(angle)
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
    t.right(angle * 2)
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
    t.left(angle)
    if loop == 2:
        dr(t, leng)
    else:
        draw(t, leng, loop-1)
        
def dr(t, length):
    t.forward(length)
    t.left(angle)
    t.forward(length)
    t.right(angle * 2)
    t.forward(length)
    t.left(angle)
    t.forward(length)
    
import turtle
turtle.penup()
turtle.back(300)
turtle.pendown()
angle = 60
draw(turtle, length = 200, loop = 3)
簡單幾行程式就可以產生漂亮又複雜的圖案,碎形(fractal)真的是遞迴 Recursive 的極致。

angle=60, loop=1

angle=60, loop=2

angle=60, loop=3

angle=60, loop=4

angle=75, loop=3

雪花

import turtle
turtle.penup()
turtle.back(300)
turtle.left(90)
turtle.forward(200)
turtle.right(90)
turtle.pendown()
angle = 60
draw(turtle, length = 120, loop = 3)
turtle.right(120)
draw(turtle, length = 120, loop = 3)
turtle.right(120)
draw(turtle, length = 120, loop = 3)
---
---
---

沒有留言:

張貼留言