python的turtle模組肯定很棒吧!這次,我們要利用turtle來完成乙個櫻花樹的繪製。我們要用def和for語句迴圈。
難度等級:
python資源共享群:626017123
工具:turtle、random
我用的是python 3.8.0b3 shell,開始寫**吧!
# 櫻花樹
import randomimport turtle
jess = turtle.turtle()jess.hideturtle()jess.left(90)jess.penup()jess.goto(0, -100)jess.pendown()
# 「畫樹」函式# 引數分別是樹枝長度、畫筆def tree(branchlen, t): if (branchlen > 3): if (8 <= branchlen and branchlen <= 12) : if (random.randint(0, 2) == 0) : jess.pencolor('snow') else : jess.pencolor('lightcoral') jess.pensize((branchlen / 3)) elif (branchlen < 8) : if (random.randint(0, 1) == 0) : jess.pencolor('snow') else : jess.pencolor('lightcoral') jess.pensize((branchlen / 2)) else : jess.pencolor('sienna') jess.pensize((branchlen / 10)) jess.forward(branchlen) a = (1.5 * (random.random())) jess.right((20 * a)) b = (1.5 * (random.random())) # 在tree函式內部調自己,這種方式叫遞迴呼叫 # 遞迴可以大幅提公升程式設計效率 tree(branchlen - 10 * b, t) jess.left((40 * a)) tree(branchlen - 10 * b, t) jess.right((20 * a)) jess.penup() jess.backward(branchlen) jess.pendown()
# 繪製樹下花瓣,引數分別是畫板數、畫筆
def petal(m, t): for i in range(m): a = (200 - 400 * (random.random())) b = (10 - 20 * (random.random())) jess.penup() jess.forward(b) jess.left(90) jess.forward(a) jess.pendown() jess.pencolor('lightcoral') jess.circle(1) jess.penup() jess.backward(a) jess.right(90) jess.backward(b)
def main(): jess = turtle.turtle() jess.hideturtle() jess.speed(0) jess.goto(0, 0) jess.penup() jess.backward(150) jess.pendown() jess.pencolor('sienna') tree(60, jess) petal(100, jess) turtle.done()
main()
你有沒有發現,它每次畫的都不一樣嗎?是因為我們用了random,讓它隨機畫。
Python畫櫻花樹
python的turtle模組肯定很棒吧!這次,我們要利用turtle來完成乙個櫻花樹的繪製。我們要用def和for語句迴圈。難度等級 python資源共享群 626017123 工具 turtle random 我用的是python 3.8.0b3 shell,開始寫 吧!櫻花樹 import r...
python畫板 畫櫻花
話不多說,直接上原始碼,如下 import turtle as t import random import time 畫櫻花的軀幹 60,t deftree branch,t time.sleep 0.0005 if branch 3 if8 branch 12 if random.randint...
如何基於python實現畫不同品種的櫻花樹
動態生成櫻花 效果圖 這個是動態的 實現 import turtle as t import random import time 畫櫻花的軀幹 60,t def tree branch,t time.sleep 0.0005 if branch 3 if 8 branch 12 if random...