这是一个人们常常提及的问题,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/n/374080.html