Programs 4 and 5: A ball rolls back and forth, forever.

This example also uses a repeat forever construction. The goal is to have the circle roll until it reaches the right boundary of the stage and then roll back. The circle should continue the back and forth movement forever.  There exists a number of correct solutions. We describe two below (Program 4 and Program 5) and a third one in the Nested Loops Section.

To make the circle change direction when reaching the edge, we use a variable “direction” to store the state of the direction.  We use direction=1 to indicate that the circle rolls from left to right. When the circle reaches the right edge of the stage, direction changes its value to -1. This indicates that the circle moves from right to left.  In order to better visualize the position change, we display the x position of the circle on the stage.

Note:  Using 1 and -1 to encode the two directions is a choice we made. If we had a ball moving left, right, up and down, we would need four encodings. We could use stings left, right, up and down or four numbers.

Our if-then-else construction used in program 4 repeats two almost identical code segments.

  • The else branch moves the circle to the right (increasing x by 5 units) and tests after every movement if the edge has been reached.
  • The else branch moves the circle to the left (decreasing x by 5 units) and tests for the left edge.

It is beneficial to understand how the two branches of the if-then-else statement are executed: when the circle moves to the right, the then-branch is executed repeatedly. Once it reaches the edge and the direction switches to -1, the else-branch is executed repeatedly.

In Program 5, the code executes the same circle movement, but it merges the moving to the left and right into one set of statements where the direction is managed by the value of variable direction.   The variable direction is now used when computing the next value of the x-coordinate of the circle.

Discuss with your students which version of the two codes they like more and which version they judge to be easier to understand. Program 4 contains redundancy in its code, but it may be easier to understand than program 5. At the same time, code with unnecessary redundancy can be harder to test and to maintain.

Scratch link: file: P4_forever_loop.sb2 Scratch link: file: P5_forever_loop_shorter.sb2
 image005  image006
Program 4 Program 5

Program 4 Video (Length: 4:27)

Program 5 Video (Length: 3:16)