In this video, you will use a variable to keep track of the number of hits the battergets. Variables in computer science are places to store changing values. In this case, thevariable will store the number of hits, which will change each time the batter successfullyhits the ball. First, create the variable. Click the “data”menu, and click “make a variable.” Name the variable something that makes sense, like“hits.” More than one sprite will need to use the contents of hits, so keep “forall sprites” selected. Click “OK.” In the top left corner of the stage, you shouldsee an orange box labeled “hits.” It shows the current value stored in the variable “hits.”
At the moment, it’s “0.” A few new blocks for interacting with thevariable have also appeared. The value of “hits” should change each time the baseballtouches the red swung bat. From the “data” menu, drag the "change hits by 1" block intothe “if/then” block. Click the flag to test the game, then hitthe ball. Here comes the pitch – it’s outta here! Now you can see that the valueof “hits” has increased. But wait… the batter only hit the ball once,and “hits” increased by more than one. What’s going on?
The code keeps checking if the baseball hits the red bat each time the loop runs. If thebaseball touches the red bat for too long, the number of hits keeps increasing becausethe loop runs faster than the bat can change back.
To fix this, place a “wait” block from the control menu inside the “if/then”block. To figure out how long to wait, click on the bat sprite to check its code. Noticethat the bat is red for 0.2 seconds, so enter 0.2 seconds in the “wait” block.
Test the game again. When you click the bat, it may switch the scripts over to the batsprite's code. If this happens to you, just click the baseball again to keep programmingit. The number of hits now goes up by only 1!
But, it didn’t start counting hits from 0. To fix this, go to the “data” menu,drag out a “set hits to zero” block, and place it at the beginning of the program justunder the “when flag clicked” block. Click the flag to test the game again.
This time, hits start at 0 and increase by one when the bat hits the baseball. Much better!
Did you notice that there were lots of minor problems to tweak in your program? These arecalled bugs, and as you fix them you are “debugging” your program. This is an important step inprogramming! Computer scientists make mistakes all the time, so stick with it as you tweakyour code. Here's the game plan:Add a variable named “hits” to your game. Then, keep track of the batter's hits using“change by.” Make the program wait 0.2 seconds before runningthe loop again. Finally, reset the number of hits to 0 atthe beginning of each game. In the next video, you'll add analytics to your project.