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

    csp-14-2-1: What value should you use for range in line 17 in the program above (td_pattern) to complete the pattern to fill the drawing space?
  • 12
  • Using a range of 12 will complete the pattern on this line, but what should it be to finish the pattern in the space?
  • 14
  • This will stop in the middle of the last line of the pattern. How many would fill the last row?
  • 16
  • Each iteration of the loop draws one peak and there are 4 peaks per row. There is room for 4 rows so the answer is 4 * 4 = 16.
  • 18
  • This would try to draw on the line below the end of the drawing area.

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

Next Section - Detecting Odd and Even