Python and Turtle Difficulty Level 6,recursion Hexaflake Fractal with Python Turtle (Source Code)

Hexaflake Fractal with Python Turtle (Source Code)

Draw hexaflake fractal that consists of hexagons with recursion. The following figures show hexaflake in different recursion depths.

Hexaflake Recursion Depth 0
Hexaflake Recursion Depth 1
Hexaflake Recursion Depth 2
Hexaflake Recursion Depth 3
Hexaflake Recursion Depth 4
Hexaflake Recursion Depth 5

Source Code:

import turtle

screen = turtle.Screen()
screen.title('Hexaflake Fractal - PythonTurtle.Academy')
screen.setup(1000,1000)
screen.setworldcoordinates(-1000,-1000,1000,1000)
turtle.speed(0)
turtle.hideturtle()
turtle.fillcolor('blanched almond')
turtle.pencolor('sandy brown')
screen.tracer(0,0)

def hexagon(x,y,r): #x,y is the center
    turtle.up()
    turtle.goto(x,y)
    turtle.seth(90)
    turtle.fd(r)
    turtle.left(120)
    turtle.down()
    turtle.begin_fill()
    for _ in range(6):
        turtle.fd(r)
        turtle.left(60)
    turtle.end_fill()

    
def hexaflake(x,y,r,n):
    if n==0:
        hexagon(x,y,r)
        return
    hexaflake(x,y,r/3,n-1)
    direction = 90
    for _ in range(6):
        turtle.up()
        turtle.goto(x,y)
        turtle.seth(direction)
        turtle.fd(r*2/3)
        hexaflake(turtle.xcor(),turtle.ycor(),r/3,n-1)
        direction += 60

hexaflake(0,0,900,5)
screen.update()

Related Post