Using Decisions with Turtles

Here’s an example of conditional execution (using an if statement) with a turtle. We can make the turtle do some action when a condition is true. In this example if the turtle gets to right side of the space (drawing area), pick it up and move it back to the left side of the space further down so that it can draw more.

This code calculates maxX as half the width since the drawing area uses the cartesian coordinate system with (0,0) as the center. Since the width is 400 the maxX is 200. We move the turtle to -1 * maxX which is -200. When the turtle’s x coordinate is greater than or equal to the maxX, which means it is at the right edge, then we move the turtle back to the left edge and down 100.

For more information on what this code does listen to the audio tour.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

Modify the code above to draw a different pattern. Try turning changing the direction of every turn, what does that do?

You have attempted 1 of 3 activities on this page