1. 程式人生 > >輕松一刻 用代碼畫一個樹

輕松一刻 用代碼畫一個樹

screen back tle 鏈接 坐標 main class ack for

  1 # -*- encoding: utf-8 -*-
  2  
  3 
  4 #導包
  5 import turtle
  6 #隨機模塊
  7 import random
  8 #導入一個模塊的所有屬性
  9 from turtle import *
 10 from time import sleep
 11  
 12 
 13 #建立對象
 14 t = turtle.Turtle()
 15 #定義畫布
 16 w = turtle.Screen()
 17  
 18 
 19 #封裝樹的方法
 20 def tree(branchLen, t):
21   if branchLen > 3: 22     if 8 <= branchLen <= 12: 23       #畫枝葉和花 24       #random生成隨機整數,參數代表區間 25       if random.randint(0, 2) == 0: 26         #著色 27         t.color(snow) 28       else: 29         t.color(lightcoral) 30         t.pensize(branchLen / 3) 31      elif
branchLen < 8: 32         #樹幹鏈接 33         if random.randint(0, 1) == 0: 34           #著色 35           t.color(snow) 36         else: 37           t.color(lightcoral) 38           t.pensize(branchLen / 2) 39      else: 40         #畫邊界,輪廓 41         t.color(sienna) 42         #
換畫筆尺寸 43         t.pensize(branchLen / 10) 44 45 46      #進行繪制 47      t.forward(branchLen) 48      #定義坐標 49      a = 1.5 * random.random() 50      #向右位移 51      t.right(20*a) 52      b = 1.5 * random.random() 53      #遞歸調用 54      tree(branchLen-10*b, t) 55       #向左位移 56      t.left(40*a) 57      #繼續繪制 58      tree(branchLen-10*b, t) 59      t.right(20*a) 60      t.up() 61 `     #收尾 62      t.backward(branchLen) 63      t.down() 64 65 def petal(m, t): # 樹下花瓣 66 67   for i in range(m): 68         a = 200 - 400 * random.random() 69         b = 10 - 20 * random.random() 70         t.up() 71         t.forward(b) 72         t.left(90) 73         t.forward(a) 74         t.down() 75         t.color("lightcoral") 76         t.circle(1) 77         t.up() 78         t.backward(a) 79         t.right(90) 80         t.backward(b) 81 82 83 84 def main(): 85       #繪制屏幕畫布 86       t = turtle.Turtle() 87       #定義我的窗口 88       myWin = turtle.Screen() 89       getscreen().tracer(5, 0) 90        91       #設置屏幕尺寸 92       turtle.screensize(bg=wheat) 93       t.left(90) 94       t.up() 95       t.backward(150) 96       t.down() 97       #著色 98       t.color(sienna) 99       #調用樹的方法 100       tree(70, t) 101       petal(100, t) 102       #保存屏幕 103       myWin.exitonclick() 104 105 106 107 if __name__ == "__main__": 108       main()

有興趣就嘗試一下吧~

輕松一刻 用代碼畫一個樹