Time for action - add a score variable

To keep score we need to set up a variable and add a condition to increment the score when the ball touches the paddle:

  1. From the Variables palette, click on the Make a variable button to display the Variable name dialog box.
  2. Type the word Score and select the For all sprites option.
    Time for action - add a score variable
  3. Click OK to add the variable. The Variables palette displays several new blocks and the Score reporter block automatically displays on the stage.
  4. We will calculate the score based on the ball's behavior, so select the ball from the list of sprites.
  5. Add change Score by 1 to the inside of the forever if touching paddle block.
  6. Click the flag and play the game. Each time the two sprites collide, the score increments. Play the game several times, and note that we have a running score.
  7. Let's reset the score to 0. From the Variables palette, add the set Score to 0 block between the when flag clicked and forever if touching paddle blocks.
  8. Play the game a few times. The score resets to 0, each time you click the green flag.
Time for action - add a score variable

What just happened?

Each time the ball touched the paddle, we added a point to the Score variable and reported it on the stage for all to see. At the start of each game, we reset the score to 0 so the player doesn't add to the score from the previous game.

For all sprites

When we make a variable for a sprite, we can select the For all sprites option. This makes a global variable, which means that all our sprites can access the value stored in the variable.

This has many implications. For example, one sprite may change the value of the variable based on an event, while another sprite has the ability to change the variable based on a different event. We can also use the variable's value to trigger an event for an individual sprite, such as a message broadcast.

Working with too many global variables will quickly complicate your scripts because each sprite has access to the variable.

For this sprite only

In contrast to the global variable, Scratch enables us to create a variable For this sprite only. Programmers often call this a local variable because it can be accessed only by the sprite you assigned it to. Let's take a look.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.252.146