Have Tracy draw a stack of squares and circles from the bottom of the canvas to the top.

Keep in mind:

Each shape should have a height and width of 50 pixels
Shapes should be stacked in the center of the canvas
The first shape in the bottom of the stack should be a square (see the image below)
Hints:

To keep your code from getting cluttered, create 2 functions- one to draw a square and one to draw a circle! Don’t forget naming rules!
You can move Tracy to the next position inside your functions
Tracy draws circles starting at the bottom center of the circle when she’s facing right
A for loop can help repeat your shape stack to the top of the canvas!

1 answer

To create a stack of squares and circles using a turtle graphics library (like Python's turtle module), you need to define functions for drawing squares and circles. You can then use a loop to stack them on top of each other. Here's a simple implementation to help you get started:

import turtle

# Initialize the turtle
tracy = turtle.Turtle()
tracy.speed(1)

# Function to draw a square
def draw_square():
    for _ in range(4):
        tracy.forward(50)  # Move forward 50 pixels
        tracy.right(90)    # Turn right 90 degrees
    tracy.penup()
    tracy.forward(50)    # Move up to the next shape position
    tracy.pendown()

# Function to draw a circle
def draw_circle():
    tracy.circle(25)      # Draw a circle with radius 25 (diameter 50)
    tracy.penup()
    tracy.forward(50)    # Move up to the next shape position
    tracy.pendown()

# Setup the initial position
tracy.penup()
tracy.goto(0, -200)  # Start at the bottom center of the canvas
tracy.pendown()

# Stack shapes - alternating between square and circle
for _ in range(5):  # Change the range for more shapes
    draw_square()    # Draw square
    draw_circle()    # Draw circle

# Complete the drawing
tracy.hideturtle()
turtle.done()

Explanation:

  1. Turtle Initialization: tracy is the turtle that will do the drawing. The speed is set to 1 for a slower drawing, but you can adjust it for quicker rendering.
  2. Draw Square Function: The function draw_square() draws a square. After drawing the square, it moves the turtle up to the next position for the next shape.
  3. Draw Circle Function: The function draw_circle() draws a circle. Because the turtle's starting position is at the bottom center of the circle, you simply set the radius to 25 pixels to equal the 50 pixels diameter.
  4. Stack Loop: A for loop runs for a given number of iterations (5 in this case), alternating between drawing a square and a circle. Adjust the range to change how many shapes are drawn in total.
  5. Positioning: The turtle starts from a specified position on the canvas and moves up with each shape drawn, effectively stacking them until it reaches the top of the canvas.

You can run this code in any Python environment that supports the turtle module to visualize the stack of shapes.