Search code examples
pythonrecursionturtle-graphicsfractals

Python Turtle: Is it possible to use layers in fill command


I have recently been developing a software which will be used for creating fractal images. But I realized for it to fill the shapes it will need to be done in layers otherwise it will overwrite sections. Here is my current code:

import turtle
def CreatePolygon (turt, Side, Size):
    if Size <= 1:
        return
    else:
        #This will create a polygon of a certain size.
        #And iterate smaller polygons inside each polygon thus creating a fractal.
        for i in range (0, Side):
            turt.forward(Size)
            turt.left(360/Side)
            CreatePolygon(turt, Side, Size/(Side-1))

Size = 250
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
#Calling The Function
CreatePolygon (t, 5, Size)

My main intention is for the polygons to be filled by different colours which I understand how to do. The issue lies in the filled polygon being overwritten once the larger polygon it is inside gets filled. I'm not sure how to fix this issue as the requirements are:

  • Smaller Item Gets Filled First (Inside Bigger Item).
  • Bigger Item Gets Filled In Second While Not Filling In Where The Smaller Item Filled In.

Solution

  • We don't have layers in Python turtle but we can still achieve the effect you want with a little bit of duplication and rearrangement of code:

    from turtle import Screen, Turtle
    
    COLORS = ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan']
    
    def CreatePolygon(turt, sides, size, color=0):
        if size <= 1:
            return
    
        # This will create a polygon of a certain size.
        turt.fillcolor(COLORS[color])
    
        turt.begin_fill()
        for _ in range(sides):
            turt.forward(size)
            turt.left(360 / sides)
        turt.end_fill()
    
        # And iterate smaller polygons inside each polygon thus creating a fractal.
        for _ in range(sides):
            turt.forward(size)
            turt.left(360 / sides)
            CreatePolygon(turt, sides, size / (sides - 1), color + 1)
    
    screen = Screen()
    turtle = Turtle(visible=False)
    
    # Calling The Function
    screen.tracer(False)
    CreatePolygon(turtle, 5, 250)
    screen.tracer(True)
    
    screen.exitonclick()
    

    We have to draw the larger polygon first, fill it, and then recursively draw the smaller polygons.

    enter image description here