Abstraction with Variables

A common way to abstract information is to represent it as a variable.  Variables can make the difference between a static project and a dynamic project.  Static means that the project never changes; every time you run it, it will be exactly the same.  Whereas a dynamic project will be different depending on the value of the variable.  The beauty of using abstraction through a variable is that you do not have to change the code to provide a different experience each time.  The reference to the variable remains the same, but the value of the variable is what changes the experience. 

 

To get a better idea of how you might use variables to create a dynamic experience, let's show two examples of using a variable.  In the first, we'll use one of Scratch's built in variables.  In the second example, we'll create our own variable.

Built-in Variable Example (15 min)

Let's create a simple birthday card where Scratch Cat first asks the user how old they are turning.  Then, we'll put that many candles on the cake.  First, let's decompose the problem to figure out what we need to do.  Then, watch the video below to learn how to do this in Scratch. Links to an external site.

Decomposition:

  1. Create sprite to ask how old the user is (e.g., Scratch Cat)
    1. When the user clicks the flag, say, "I heard it was your birthday today.  Congratulations!"
    2. Ask, "how old are you?"
    3. When they give you an answer, make that many clones of the candle sprite and place them on the cake.
  2. Create a cake sprite on which to put the candles
  3. Create a candle sprite that can be cloned according to the person's age
    1. Create a lit and unlit costume for the candle
    2. When the candle sprite starts as a clone, loop forever between costumes

Play media comment.

User-Created Variable Example (5 min)

Probably one of the most common uses of variables in Scratch projects is to somehow keep score (e.g., for a learning game).  Let's modify our earlier snowflake example to see how many flakes we can "catch."  For each flake we catch we'll increase the score by 1.  First, let's decompose the problem.  Then, watch the video below to see how we would remix the snowflake example to create our own score counter.

Decomposition

  1. Remix the snowflake example
  2. Create a 'score' variable
    1. The variable will have to be accessible to all sprites since it's a single score affected by multiple sprites.
  3. When a cloned snowflake is clicked, increase the score by 1

That's it!  We can obviously make this game more fun by adding other variables (e.g., a timer), but this demonstrates the basic concept of creating your own variable and changing it to make your project more dynamic.

Play media comment.