r/learnpython • u/Confident-Acadia4217 • 7d ago
pythagoras tree
I made code for one "branch" of the Pythagoras tree, and I have no idea how to make the full tree. Can someone help? My code:
from turtle import*
x=100
while True:
for i in range (4):
fd(x)
rt(90)
rt(90)
fd(x)
lt(45)
xNaDwa= x*x/2
y= xNaDwa**0.5
x=y
3
Upvotes
View all comments
1
u/Sufficient-Tale6131 7d ago •
Recursion is the way, and since you already draw the square with rt(90) the turns work out pretty neatly. Roughly: def tree(size, depth). If depth is 0 just return. Otherwise draw the square like you do now, then fd(size) so you're at the top-left corner. lt(45) and call tree(size * 0.7071, depth - 1), that's the left branch. Then rt(90) and fd(size * 0.7071), which puts you at the tip of the triangle already facing the right way, and call tree again for the right branch. After that undo the moves in reverse: bk(size * 0.7071), lt(45), bk(size).
The important part is that every call leaves the turtle exactly where and how it found it, otherwise the branches drift. Start with lt(90) so it grows upward, and put tracer(0) at the start and update() at the end, depth 8 or so is painfully slow to watch otherwise.