I introduced the concept of variables in Scratch last week. Variables are extremely important in programming because they refer to values that can be changed. Some examples you gave of variables that are in video games:
- Character speed
- Enemy spawn rate
- Powerup locations
A variable is a place to store a value (something fixed). Something like 1 or “booyah” are examples of values. The reason you’d use a variable rather than the value directly is because you may want to use it in more than one place – for example, if you input your name to be used in a greeting (and you want many people to use the same code).
There are also more complicated types, but we will discuss those in a future lesson.
You can use operators on numbers to produce new numbers, like +, -, *, / and %. The % operator is the remainder operator. You can also use the + operator on strings as well. But what happens when you try to add a string to a number? Try it out.
Lastly, you can compare two numbers (and it will produce a value of true or false depending whether it’s correct) by using the == (equals), != (not equals), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). However, using two equal signs will make a string and number equal as long as they are the same (eg “1” == 1 is true). If you don’t want to do this and want them to be the same type, then you have to use === and !== operators.
Here are some more resources you can do for practice:
- Khan Academy’s variable review here: https://www.khanacademy.org/computing/computer-programming/programming/variables/a/review-variables
- Crunchzilla’s Code Monster lesson variables (section 3): http://www.crunchzilla.com/code-monster
and here’s this week’s assignment: http://jsfiddle.net/zeroth_hour/yj049v9g/
In order to do this week’s assignment, you’ll need a few functions: