Video - Perform actions multiple times
3rd in a row but equally important with the previous 2 programming structures is the repetition structure.
If we want some actions to be executed many times then we should be able to use commands of that particular structure.
Let's listen to Steve on an extremely interesting video.
Often, as developers, we want some instructions to run again and again. Repeat them several times.
Let's look at a very simple program I've created to show you just that.
First let's run the script and see its effect in our setting.
You see how our sprite repeats some actions.
Let's take a look at the code. Indeed, we see that this command block is repeated three times.
We can repeat these code lines as many times as we want.
In this way, however, we create very large scenarios that are difficult to read and change if needed.
Instead of writing again and again the same commands we can set up running as many times as we want if these commands enter a block of repeats.
Let’s have a look…
A block of commands can also be repeated even if we do not know the exact number of repetitions. It can be repeated until something happens.
It can be repeated until something happens.
On my screen you will see the same scenario as before, only now the repetition is done with the command "Repeat until".
See the same lines of code. Repeat until the variable counter is equal to 10.
Note that the variable “counter” which initially gets the value 1 and after executing the repeat block its value rises by 1.
This keeps repeating until the value of the variable is 10.
Repetition is used too often in computer programming.
It is always used when we have to create games by programming.
In all games, we always want to be happening.
For example, remember the game we discussed in the previous lesson.
Remember that throughout the game, when the monkey touches a banana the score raises and the bananas moves to another point of the stage.
We want action like this throughout the whole game.
The instructions that perform these actions must be in a repeat mode.
Because we do not know how long the game will take in order to set the exact number of repeats, nor can we define an event that these instructions will run until it is done easily, the instruction FOREVER.
The "forever" instruction is a repeat command that is used very often in scratch game programming.
In the game we mentioned earlier and we will create in the next lesson, it is used in every sprite.
Let's have a look.