Page 186 - Learn To Program With Scratch
P. 186
counters
Sometimes, you’ll need to keep track of the number of iterations a loop per-
forms. For example, if you want to give users only three chances to enter the
correct password, you’ll have to count their attempts and lock them out after
the third try.
You can handle such programming scenarios by using a variable (com-
monly referred to as the loop counter) that counts the number of loop itera-
tions. Let’s jump right in and explore some examples that demonstrate
practical ways to use loop counters.
Check a Password
Password The program in Figure 7-12 asks the user to enter a password for unlock-
Check .sb2 ing a laptop. The Laptop sprite has two costumes: the off image indicates
that the laptop is locked, and the on image indicates that the laptop is
unlocked. The user will be denied access to the laptop if an invalid pass-
word is entered three times.
Laptop starts in a Costume for an
“locked” state. “unlocked” laptop.
Figure 7-12: This script gives the user three chances to enter the correct password .
When the green flag is clicked, the Laptop sprite switches to the off
costume and calls the GetPassword procedure to authenticate the user.
This procedure is expected to return the password check result to the main
script using the gotPass flag. When the procedure returns, the if/else block
checks the gotPass flag to decide whether or not the user should be allowed
to access the system. If gotPass was set to 1, meaning the user entered the
correct password, the if block executes a say command that displays Access
164 Chapter 7
www.it-ebooks.info

