Time for action count the paddle's steps

For fun, let's count the number of times our paddle moves left and right:

  1. Select the paddle sprite from the list of sprites.
  2. From the Variables palette, click the Make a variable button to display the Variable name dialog box.
  3. Type Steps and select For this sprite only.
  4. Click OK to add the variable.
  5. Click on the ball sprite and review the blocks available in the Variables palette. Steps is not an option. Select the paddle sprite again.
  6. From the Variables palette, add the change by 1 block to the end of each of the scripts that move the paddle with the left and right arrow key.
  7. Change the value from Score to Steps. Change the value from 1 to 50 in each script.
  8. From the Variables palette, add the set to block between the when flag clicked and forever if touching ball blocks.
  9. Change the value from Score to Steps.
  10. Click the flag and play the game. The score and the paddle steps variables increment as you play.
Time for action count the paddle's stepsscore, Troll pongvariable, creating for this sprite only

What just happened?

Each time I pressed an arrow key, my sprite moved 50 steps and the paddle steps monitor on the stage incremented by 50. If your sprite moved a different number of steps, you can change the value of the Steps variable accordingly.

When we added the Steps variable to the paddle, we noticed that we couldn't access the variable from any other sprite. When we clicked on the ball sprite, for example, the Steps variable was not an option. Also, when the Steps monitor displayed on the stage, it displayed as paddle Steps, which was another indicator that we were working with a local variable.

Global versus local variables

All sprites can change the value of a global variable; therefore, it can be difficult to track problems when they occur because we have to investigate each script in each sprite to find all the places that may be affecting our project. The bigger our project gets, the harder it can be to keep track of global variables.

We may also program in some unintended consequences, such as adding 50 points to our score each time we press the right arrow key, when what we really want to do is only count the number of steps.

Have a go hero

In the next exercise, we will introduce a second ball into the game. Your task is to add a new sprite to the project and name it ball2. In addition, you need to duplicate the ball's scripts for the ball2 sprite.

Add a second level

Let's add another level of complexity to our pong game by adding a new level that triggers based on elapsed time. After 30 seconds, we're going to introduce a second ball to the game.

Let's begin now.

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

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