GoalWrite a sub-routine, call it from a main script and trace what it does.
New words
sub-routine · a small named part of a program that can be used again and againdefine · to write the steps of a sub-routine under its namecall · to use a sub-routine by putting its block in a scriptMy Blocks · the group in Scratch where you make your own blocks
Explanation
A sub-routine is a group of blocks with a name. In Scratch we make one in the My Blocks group. The ‘define’ block holds the steps. To use them, we put the new block, with the same name, into the main script. This is called calling the sub-routine. We write the steps once and call them as often as we like. This makes a program shorter and easier to read. It also makes a program easier to fix, because a change in the define block changes every call. In an algorithm we write ‘Define sidestep’ and later ‘Call sidestep’.
Worked examples
After call
x position
start
−100
1
−70
2
−40
3
−10
The crab starts at x = −100. Each sidestep moves it 50 right and then 20 back, which is 50 − 20 = 30 to the right. After three calls the crab is at −100 + 90 = −10.
Change the define block once, and every call changes. If the first move is 40 instead of 50, each sidestep is 40 − 20 = 20 to the right. After three calls the crab is at −100 + 60 = −40.
One define block can have many calls. Here the crab sidesteps when the flag is clicked and again every time the space key is pressed. The steps are written only once.
Class activity
Dance steps (a group of 4 or more). Invent a short move, such as clap, turn and step, and give it a name, for example ‘shimmy’. Write the steps for shimmy on one card. This card is the define block. The caller then reads out a routine such as ‘shimmy, jump, shimmy, shimmy’. The dancers look at the shimmy card each time it is called. Now change the card, for example add a stamp. Did every shimmy change? If you have a computer or tablet, make a block called sidestep in Scratch and call it three times.
Practice
1
What does it mean to ‘call’ a sub-routine?
To use it: you put its block in a script, so that its steps run at that point.
2
The sprite starts at y = −40. What is its y position at the end, and how long does the program take?
Each nudge moves it 20 up and 5 down, so 20 − 5 = 15 up. Four calls give 4 × 15 = 60, so the sprite ends at −40 + 60 = 20. Each call waits 0.2 seconds, so the program takes 4 × 0.2 = 0.8 seconds.
3
A pupil makes a block called ‘spin’ but puts no blocks under its define block. What happens when the main script calls spin?
Nothing happens. The call runs the steps under the define block, and there are none.
4
A sprite faces right (direction 90). It calls the sub-routine three times. Which way does it face at the end?
Each call turns it 180 degrees. Three calls turn it 540 degrees. 540 − 360 = 180, so it turned the same as one call of 180 degrees. It now faces left (direction −90).