pythonturtle-graphicspython-turtle

How do I find the shortest way to make a pattern using turtle in Python?


Here is a pattern that I made:

import turtle
t = turtle.Turtle()

for i in range(4):
    t.forward(150)
    t.right(90)

t.forward(50)
t.right(90)
t.forward(100)
t.backward(50)
t.left(90)
t.forward(100)
t.backward(50)
t.right(90)
t.forward(100)
t.backward(50)
t.right(90)
t.forward(100)

This question might be silly, but how do I find out the shortest way to make a pattern in turtle? Also, how do I shorten this code?


Solution

  • There is no general algorithm for simplifying arbitrary drawings, but most basic turtle patterns such as this involve a simple pattern rotated about the center. The simplest solution almost always involves 3 steps:

    1. Draw the fundamental shape once
    2. Position the turtle such that it's ready to draw the same shape in the next step of the rotation
    3. Add a loop to draw the shape and reposition N times

    In this case:

    1. Draw a rectangle with one side twice as long as the other
    2. After completing the rectangle, move the turtle away from the rectangle a half length and point it facing along the short side (hard to explain, and this is the tricky part of this pattern)
    3. Loop the above process 4 times.

    I actually figured out the tricky step 2 mostly by trial and error. I observed the direction the turtle was pointing in and reasoned about which steps were necessary to point it in the proper direction in order to draw the next shape, then played around until it worked.

    from turtle import Screen, Turtle
    
    
    t = Turtle()
    size = 100
    
    for _ in range(4):
        for _ in range(2):
            t.forward(size)
            t.left(90)
            t.forward(size // 2)
            t.left(90)
    
        t.right(90)
        t.forward(size // 2)
        t.left(180)
    
    Screen().exitonclick()