The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 4 Programming with Scratch^61

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Click the green flag to run your program one last time, and you’ll see that the cat sprite waits
for a second after moving to the right before moving back to the left again. This is known as a
delay, and is key to controlling how long your sequence of instructions takes to run.


Looping the loop
The sequence you’ve created so far runs only once: you click the green flag, the cat sprite
moves and meows, and then the program stops until you click the green flag again. It doesn’t
have to stop, though, because Scratch includes a type of Control block known as a loop.
Click on the Control category in the blocks palette, colour-coded gold, and find the forever
block. Click and drag this into the scripts area, then drop it underneath the when clicked
block and above the first move 10 steps block.


when clicked


forever


move^10 steps


play sound meow


wait^1 secs


move -10 steps


Notice how the C-shaped forever block automatically grows to surround the other blocks in
your sequence. Click the green flag now, and you’ll quickly see what the forever block does:
instead of your program running once and finishing, it will run over and over again – quite literally
forever. In programming, this is known as an infinite loop – literally, a loop that never ends.
If the sound of constant meowing is getting a little much, click the red octagon next to
the green flag above the stage area to stop your program. To change the loop type, click and


CHALLENGE: ADD MORE STEPS
Try adding more steps to your sequence, and changing
the values in the existing steps. What happens when the
number of steps in one move block doesn’t match the
number of steps in another? What happens if you try to
play a sound while another sound is still playing?
Free download pdf