Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import turtle
import random
class Tree:
"""木のクラス"""
def __init__(self, x=0, y=0, n=5, length=40):
self.n = n
self.length = length
self.t = turtle.Turtle()
self.t.pu()
self.t.setposition(x, y)
self.t.pd()
self.t.hideturtle()
self.t.speed(0)
self.t.setheading(90)
self.bloom_point = []
def grow(self, ):
self.tree(self.n, self.length)
def tree(self, n, length):
self.t.pd()
self.t.pensize(n)
self.t.forward(length)
if n > 0:
# 分岐点の座標を記録
branch_point = self.t.pos()
branch_number = random.randint(2, 4)
for _ in range(branch_number):
branch_angle = random.uniform(-45, 45)
branch_length = length * random.uniform(0.75, 0.9)
self.t.right(branch_angle)
self.tree(n - 1, branch_length)
self.t.left(branch_angle)
self.t.pu()
self.t.setpos(branch_point)
else:
# 枝の先端を記録
self.bloom_point.append(self.t.pos())
# 花が咲く
def bloom(self, ):
self.t.pu()
for position in self.bloom_point:
# 花の場所に移動
self.t.setpos(position)
# 花が咲く
self.t.dot(8, "pink")
if __name__ == "__main__":
turtle.setup(300, 300)
sakura = Tree(y=-150)
sakura2 = Tree(x=10, y=-120)
sakura.grow()
sakura2.grow()
sakura.bloom()
sakura2.bloom()
turtle.done()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.