The mods over at r/dailyprogrammer have been releasing new problems every week pretty consistently for the last month, providing a nice stream of challenges to work on. The challenge posted yesterday was constructing a fractal in ASCII text. I decided I wanted to make a Pythagoras tree fractal, but found it wasn't really feasible to make one using a 2D array of ASCII characters so I decided to animate a fractal using the turtle package in Python. If you don't know what the turtle package is, I didn't either until I took Udacity's programming foundations with python. It is a simple line drawing library that can do some neat things--like drawing fractals--using recursion.
Here's the code I used to draw the Pythagoras tree to 12 levels of depth:
import turtle
import math
def fractal(aturt, depth, maxdepth):
if depth > maxdepth:
return
length = 180*((math.sqrt(2)/2)**depth)
anotherturt = aturt.clone()
aturt.forward(length)
aturt.left(45)
fractal(aturt, depth+1, maxdepth)
anotherturt.right(90)
anotherturt.forward(length)
anotherturt.left(90)
anotherturt.forward(length)
if depth != maxdepth:
turt3 = anotherturt.clone()
turt3.left(45)
turt3.forward(180*((math.sqrt(2)/2)**(1+depth)))
turt3.right(90)
fractal(turt3, depth+1, maxdepth)
anotherturt.left(90)
anotherturt.forward(length)
def draw_fractal():
window = turtle.Screen()
turt = turtle.Turtle()
turt.hideturtle()
turt.penup()
turt.goto(-75, -225)
turt.pendown()
turt.speed(0)
turt.left(90)
fractal(turt, 1, 12)
window.exitonclick()
draw_fractal()
And the result!
Hello,
ReplyDeletethanks for your code, I tried to run your code, but I got an error message:Traceback (most recent call last):
File "", line 1, in
import pitagorastree.py
File "/home/timi/pitagorastree.py", line 6
def fractal(aturt, depth, maxdepth):
^
IndentationError: unexpected indent
Intenta ajustando el espaciado que tiene delante de def fractal. es un error en eso al parecer.
Delete