Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

70 Chapter 4


to this position and heading after finishing each small spiral in
order to maintain the shape of the big spiral. If we didn’t remem-
ber the location and direction of the turtle before starting to draw
the small spirals, our turtle would wander all over the screen,
starting each small spiral relative to where it left off with the last
small spiral.
The two commands that will tell us the turtle’s location and
direction are t.position() and t.heading(). The turtle’s position is
accessed through t.position(), and it consists of both the x (horizon-
tal) and y (vertical) coordinates of the turtle’s location on the screen,
just like on a coordinate graph. The direction the turtle is heading
is available through the command t.heading() and is measured from
0.0 degrees to 360.0 degrees, with 0.0 degrees pointing up toward
the top of the screen. We will store these pieces of information in the
variables position and heading before we start each small spiral so
that we can pick up where we left off on the big spiral each time.
It’s time for the inner loop. We’re indented even farther here.
This inner loop will draw a small spiral at each corner of the big-
ger spiral.

y for n in range(int(m/2)):
t.pendown()
t.pencolor(colors[n%sides])
t.forward(2*n)
t.right(360/sides - 2)
t.penup()
z t.setx(position[0]) # Go back to the big spiral's x location
{ t.sety(position[1]) # Go back to the big spiral's y location
| t.setheading(heading) # Point in the big spiral's heading
} t.left(360/sides + 2) # Aim at the next point on the big spiral

Our inner loop y begins with n = 0 and stops when n = m/2,
or one-half of m, to keep the inner spirals smaller than the outer
spiral. The inner spirals look like our previous spirals, except that
we put the pen down before drawing each line and lift it after each
line is drawn so that our big spiral stays clean.
After we draw our inner spiral from y, we pick back up at z
by setting the horizontal position of the turtle to the one we stored
at w. The horizontal axis is commonly called the x-axis, so when
we set the horizontal location, we use t.setx(), or set the x-axis posi-
tion of our turtle’s location on the screen. At {, we set the y-axis
location, or vertical position, that we stored at w. At |, we turn
Free download pdf