Python自帶了一個turtle庫,就像名字turtle說的那樣,你能夠建立一個turtle,而後這個turtle能夠前進,後退,左轉,這個turtle有一條尾巴,可以放下和擡起,當尾巴放下的時候,turtle走過的地方就留下了痕跡,也就是這隻畫筆的原理。html
下面的表格是基本的一些turtle的方法,這裏簡單列舉了一點。python
命令 | 解釋 |
---|---|
turtle.Screen() | 返回一個singleton object of a TurtleScreen subclass |
turtle.forward(distance) | 向當前畫筆方向移動distance像素長 |
turtle.backward(distance) | 向當前畫筆相反方向移動distance像素長度 |
turtle.right(degree) | 順時針移動degree° |
turtle.left(degree) | 逆時針移動degree° |
turtle.pendown() | 移動時繪製圖形,缺省時也爲繪製 |
turtle.goto(x,y) | 將畫筆移動到座標爲x,y的位置 |
turtle.penup() | 移動時不繪製圖形,提起筆,用於另起一個地方繪製時用 |
turtle.speed(speed) | 畫筆繪製的速度範圍[0,10]整數 |
turtle.circle() | 畫圓,半徑爲正(負),表示圓心在畫筆的左邊(右邊)畫圓 |
下面是一個很簡單的turtle的例子,咱們使用turtle來畫一個螺旋的圖案,這個函數採用遞歸的方法,每次遞歸的畫筆減少了5個單位長度,進而造成了一個向內螺旋的圖案。app
import turtle my_turtle = turtle.Turtle() my_win = turtle.Screen() def draw_spiral(my_turtle, line_len): if line_len > 0 : my_turtle.forward(line_len) # turtle前進 my_turtle.right(90) # turtle向右轉 draw_spiral(my_turtle, line_len - 5) #turtle繼續前進向右轉 draw_spiral(my_turtle, 100) my_win.exitonclick()
接下來,咱們用turtle來畫一顆樹。過程是這樣的: branch_len
爲樹枝的長度,這裏的turtle也是採用遞歸的方法,在樹枝須要分叉的地方創建一顆新的子樹,並且是左右兩顆子樹,右子樹的長度比左子樹的長度要少5個單位。ide
import turtle def tree(branch_len, t): if branch_len > 5: t.forward(branch_len) t.right(20) tree(branch_len - 15, t) t.left(40) tree(branch_len - 10, t) t.right(20) t.backward(branch_len) def main(): t = turtle.Turtle() my_win = turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color("green") tree(75, t) my_win.exitonclick() main()
The Sierpinski triangle illustrates a three-way recursive algorithm. The procedure for drawing a Sierpinski triangle by hand is simple. Start with a single large triangle. Divide this large triangle into four new triangles by connecting the midpoint of each side. Ignoring the middle triangle that you just created, apply the same procedure to each of the three corner triangles函數
import turtle def draw_triangle(points, color, my_turtle): my_turtle.fillcolor(color) my_turtle.up() my_turtle.goto(points[0][0],points[0][1]) my_turtle.down() my_turtle.begin_fill() my_turtle.goto(points[1][0], points[1][1]) my_turtle.goto(points[2][0], points[2][1]) my_turtle.goto(points[0][0], points[0][1]) my_turtle.end_fill() def get_mid(p1, p2): return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) def sierpinski(points, degree, my_turtle): color_map = ['blue', 'red', 'green', 'white', 'yellow', 'violet', 'orange'] draw_triangle(points, color_map[degree], my_turtle) if degree > 0: sierpinski([points[0], get_mid(points[0], points[1]), get_mid(points[0], points[2])], degree-1, my_turtle) sierpinski([points[1], get_mid(points[0], points[1]), get_mid(points[1], points[2])], degree-1, my_turtle) sierpinski([points[2], get_mid(points[2], points[1]), get_mid(points[0], points[2])], degree-1, my_turtle) def main(): my_turtle = turtle.Turtle() my_win = turtle.Screen() my_points = [[-100, -50], [0, 100], [100, -50]] sierpinski(my_points, 3, my_turtle) my_win.exitonclick() main()