Hey, welcome back, fasten your seat belts as today we're going to cover a lot of ground. This lesson is about FUNCTIONS.
A FUNCTION is a block of code that can be written once and be used in multiple places in your program.
Let's create a FUNCTION in Scratch. On the left of the screen, click on the section for My Blocks, then you should see an option to Make A Block. In Scratch, these blocks are FUNCTIONS. Click it and then name your FUNCTION something that you can easily understand later. Your screen should look something like this now,
In our first example, we want to move our sprite in a square that is 100 steps on each side. Here's one way to do this. This approach takes 13 lines of code. Let's substitute those 13 lines of code with a FUNCTION.
First, define the FUNCTION name it Move And Turn. The Move And Turn FUNCTION tells the computer to move our Sprite 100 Steps turn 90 degrees and wait 0.5 seconds.Our program will execute this FUNCTION 4 times to complete a square using the REPEAT BLOCK. Each time the FUNCTION is called, we move forward a certain number of steps and turn 90 degrees then wait half a second.
Here's the second example. We want our sprite to move diagonally towards the bottom left corner when we press the A key or left arrow key. And we want to move diagonally towards the top right corner when we press the D key or right arrow key. Create two FUNCTIONS here and name them Move Right and Move Left.
The Move Right FUNCTION is defined to change X by 10 steps and Y by 10 steps. So when we press the right arrow key will move diagonally up and to the right. The Move Left FUNCTION is defined to change X by -10 steps and Y by -10 steps. So we're moving diagonally down into the left.
Can you code the program that includes the FUNCTIONS? Go ahead, give it a try.
Alright, that's it for FUNCTIONS, except all the great exercises and quizzes that our genius instructors have created to help you master this concept.
And remember, keep it D.R.Y. That is Don't repeat yourself. Alright, I'll see you in the next lesson.