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:
- 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. - 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. - 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. - 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. - 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.