This graphics program should draw a worm. A worm is made up of
NUM_CIRCLES
circles. Use afor
loop to draw the worm, centered vertically on the screen. Also, be sure that the worm is still drawn across the whole canvas, even if the value ofNUM_CIRCLES
is changed.
Hint: Think about the location of each circle. You should see a pattern that develops and can be used in a loop.
Here is the exact solution in Python using the
turtle
graphics library:import turtle
# Constants
NUM_CIRCLES = 15 # You can change this value to any number of circles
RADIUS = 20 # Radius of each circle
SPACING = RADIUS * 2 # Distance between centers of circles
# Set up the screen
screen = turtle.Screen()
screen.setup(width=800, height=200) # Adjust the screen size as needed
# Set up the turtle
worm = turtle.Turtle()
worm.shape(“circle”)
worm.penup()
worm.color(“black”)
# Calculate the starting x-position to center the worm horizontally
start_x = -((NUM_CIRCLES – 1) * SPACING) / 2
# Draw the worm
for i in range(NUM_CIRCLES):
worm.goto(start_x + i * SPACING, 0) # Centered vertically at y = 0
worm.stamp() # Stamp a circle shape at the current position
# Finish drawing
turtle.done()
Explanation of the Solution:
NUM_CIRCLES
: This determines the number of circles in the worm.RADIUS
: Sets the radius of each circle, which helps calculate the spacing.SPACING
: The distance between the centers of each circle, calculated asRADIUS * 2
.worm
is created with a circular shape and no drawing line (penup()
). It is colored black to resemble the worm’s segments.start_x
is calculated to position the first circle such that the worm is centered horizontally across the screen.for
loop iteratesNUM_CIRCLES
times, placing each circle at an even horizontal distance (SPACING
) from the previous one. Each circle is stamped at the calculated position.