這是一個人們常常提及的問題,Python里的畫樹程序到底在哪裡?
一、turtle庫-原生Python畫樹
turtle庫是Python自帶的一個繪圖庫,可以在Python中直接使用。這個庫可以讓我們簡單方便地在屏幕上畫出各種各樣的形狀,包括樹。
import turtle
def tree(branchLen, t):
if branchLen > 5:
t.forward(branchLen)
t.right(20)
tree(branchLen-15, t)
t.left(40)
tree(branchLen-15, t)
t.right(20)
t.backward(branchLen)
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("green")
tree(75,t)
myWin.exitonclick()
這個程序使用turtle庫畫出來的樹形狀是非常簡單的,但卻足以滿足初學者的需要。程序採用遞歸的方式,每次分成左右兩個子樹再繼續遞歸下去,直到停止條件滿足。我們可以通過調整參數值來改變樹的形狀。
二、pygame庫-擴展Python繪圖功能
pygame庫是Python的一個第三方繪圖庫,可以擴展Python繪圖功能,使得我們可以方便地在屏幕上繪製更加複雜的形狀,包括樹。下面的代碼演示了如何使用pygame庫繪製樹形狀。
import pygame
import math
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
def tree(branchLen,theta,x,y,heading,depth):
if depth > 0:
x1 = x + int(branchLen * math.cos(heading * math.pi / 180.0))
y1 = y + int(branchLen * math.sin(heading * math.pi / 180.0))
pygame.draw.line(screen, green, [x, y], [x1, y1], 2)
tree(branchLen * 0.75, theta, x1, y1, heading - theta, depth - 1)
tree(branchLen * 0.75, theta, x1, y1, heading + theta, depth - 1)
def tree_m():
pygame.init()
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Tree")
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(white)
tree(110, 30, 250, 250, -90, 9)
pygame.display.flip()
clock.tick(60)
pygame.quit()
tree_m()
這個程序比之前的程序更加複雜,採用的是分形法。程序從根節點開始,不斷分出子節點並繪製出整棵樹。通過遞歸的方式,程序能夠繪製出複雜的樹形狀。通過調整參數值,我們可以產生不同形狀的樹。
三、matplotlib庫-專業繪圖庫
matplotlib庫是專業的繪圖庫,主要用於繪製圖表和圖形。儘管matplotlib主要用於繪製2D圖像和基本的3D圖像,但它同樣也可以用於繪製樹形狀。下面的代碼示例演示了如何使用matplotlib庫來繪製帶有綠色樹葉的棕色樹榦。
import matplotlib.pyplot as plt
def tree(x,y,base, length, angle):
if length <= 0 : return
tilt = angle * 3.14 / 180.0
x2 = x + length * math.cos(tilt)
y2 = y + length * math.sin(tilt)
plt.plot([x,x2],[y,y2],linewidth=3.0,color=[0.5,0.4,0.3])
tree(x2,y2,base, length - base, angle + 20)
if length < 30: color = [0.2,0.5,0.1]
else: color = [0.0,0.5,0.0]
plt.plot(x2, y2,marker='o',markersize=length*0.05,color=color)
plt.axis("off")
tree(0, 0, 10, 50, 90)
plt.show()
matplotlib庫可以繪製出更加真實的樹形狀,並且可以控制其大小和顏色。這個程序先初始位置,然後使用線條繪製出樹榦。接着,程序遞歸地繪製出樹葉,通過調整參數來進行顏色和大小的控制。
原創文章,作者:BMHPL,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/374080.html