Reputation: 100
I’m new to programming and I’m reading a book called How To Think Like A Computer Scientist. In the fourth chapter, it talks about functions.
At the end of the chapter, there’s an exercise that asks me to draw the following pattern using Python’s turtle module.
I was examining this picture and decided to split it into two: 1) the lines in the middle and 2) the squares that go on top of each other like a spiral.
I drew the first part using this code:
import turtle
wn = turtle.Screen() # Set up the window
wn.bgcolor("lightgreen")
alex = turtle.Turtle() # Create Alex
alex.color("blue")
alex.pensize(3)
for i in range(20): # Here I start drawing the lines
alex.forward(100)
alex.backward(100)
alex.left(360/20) # Fit 20 lines in the 360 degree circle
wn.mainloop()
When I run it, it draws this:
Then, I created the draw_square function and managed to draw the first square:
import turtle
def draw_square(turtle, size):
for i in range(4):
turtle.forward(size)
turtle.left(90)
wn = turtle.Screen() # Set up the window
wn.bgcolor("lightgreen")
alex = turtle.Turtle() # Create Alex
alex.color("blue")
alex.pensize(3)
for i in range(20): # Here I start drawing the lines
alex.forward(100)
alex.backward(100)
alex.left(360/20) # Fit 20 lines in the 360 degree circle
# In a messy way, using what I've learned, I move Alex to where he's supposed to be now
# I'm pretty sure there's a classier way to do this
alex.penup()
alex.backward(100)
alex.right(90)
alex.forward(100)
alex.left(90)
alex.pendown()
# Here I get Alex to draw the square
draw_square(alex, 200)
wn.mainloop()
When I run it, it draws this:
Now I’m stuck. I don’t know where to go from here. I don’t know how to go about drawing all the other squares. I can’t figure out where to place the turtle, and how many degrees to tilt the square (probably 20, like the lines, but I don’t know how to implement it)… Anyways, you guys got any tips? Any suggestions?
I’m trying not to skip any exercises on the book and this one got me.
Upvotes: 5
Views: 4529
Reputation: 56965
Excellent attempt, and thanks for the clear images of expected/actual output!
The pattern is actually a bit simpler than you may think. A single box is being drawn from the center repeatedly, with the turtle pivoting slightly on the center point on each iteration. The overlaps of the box sides create the illusion of "spokes".
As for determining the turn amount in degrees, I took 360 and divided it by the number of spokes shown in the image (20), giving 18 degrees.
Here's code that produces the correct output.
from turtle import Screen, Turtle
def draw_square(turtle, size):
for i in range(4):
turtle.forward(size)
turtle.left(90)
def main():
turtle = Turtle()
Screen().bgcolor("lightgreen")
turtle.color("blue")
turtle.pensize(3)
boxes = 20
for _ in range(boxes):
draw_square(turtle, 200)
turtle.left(360 / boxes)
Screen().exitonclick()
if __name__ == "__main__":
main()
Output:
Upvotes: 6