How many times did something happen?
How long has it been since I did that?
Has A happened more times than B has?
All these things (and more) can be tracked using variables.
Lets start with a simple example: Let us imagine we want our monster to have hunger change its moods. How do we track when it gets hungry and how do we keep track of when it gets fed?
In the embedded code below, you’ll see on approach to this problem. (Link to code here)
Using the internal clock, we can keep track of how long it has been since the monster was turned on.
We then create a variable we call hunger and say that it is equal to however long the monster has been on, minus how much food it has eaten.
Next we define a variable food and say that every time button A is pushed, food increases by 5000 (5 seconds)
Finally, we use a logic statement to say that if hunger is less than 10000 (remember, hunger was set in milliseconds so 10000ms is 10 seconds) to display a happy face otherwise display a grumpy face.
Here’s what happens when we run the program: If the monster hasn’t been fed in 10 seconds (it’s "hunger” variable higher than 10000), it becomes hungry and changes its face. Pushing the button A gives it “food” which is takes away 5 seconds (5000ms) of “hunger”
In 1997, the hottest toy was the Tamagotchi pet, a little pocket pet that had to be cared for. Caring for it meant keeping track of many of its needs:
feeding
keeping it clean
playing with it
putting it to bed
How can you use variables to design your own version of such a pet? Decide how you want your monster cared for then decide which variables you need to do that. How do the variables work together? What do you have to do to make your monster happy?
CORE: Use variables in your Monster’s code to give it some basic emotions based on the variables.
ADVANCED: Combine variables with loops to track events. How hard is it for other people to figure out how to keep your monster happy?