Counters…..
Counting
how many guesses the user has made is the next step….
Add
2 labels to the form……as shown
Name
the second label “lblnumguesses”
Every time the enter key is hit, we need to make the value of a variable increase by one…..
Dim
secretnumber As Integer
Dim
guess As Integer
Dim
cheater As Boolean
Step 2. Making the value of numguesses zero when we get a secret number
Private Sub cmdsecret_Click()
'generates
a secret number between 0 and 100
cheater
= False
numguesses = 0
secretnumber
= Int(Rnd(1) * 101 + 0)
Step 3 Making numguesses increase by one when you hit enter and show in the correct label
Private
Sub txtguess_KeyPress(KeyAscii As Integer)
'
checks if answer is correct after enter key is hit.
If
KeyAscii = 13 Then 'if i hit the enter
key
numguesses =
numguesses + 1
lblnumguesses.Caption =
numguesses
guess = txtguess.Text 'loads user guess into variable guess
If guess > secretnumber Then
lblmessage.Caption = "Too High"
If guess
< secretnumber Then lblmessage.Caption = "Too Low"
If guess = secretnumber
And cheater = False Then
If
guess = secretnumber And cheater = True Then
lblmessage.Caption = "Doesn't really count if you cheat"
End
If
End
Sub
Well there you have it….The game now counts everytime you take a guess…
Part 2 Keeping a Running
Total.
We are going to make the program add up the total value of the guesses as you guess. I know you wouldn’t do this in a guessing game but trust me.
Add 2 more labels to the bottom of the form as follows
The second label must be named lbltotal
Dim
secretnumber As Integer
Dim
guess As Integer
Dim
cheater As Boolean
Dim total As Integer
Step 2. Making the value of total zero when we get a secret number
Private Sub cmdsecret_Click()
'generates
a secret number between 0 and 100
cheater
= False
numguesses
= 0
total = 0
lblnumguesses.Caption = numguess
'makes zeros show in the text boxes
lbltotal.Caption = total
secretnumber
= Int(Rnd(1) * 101 + 0)
Step 3 Making total increase by the value of the guess when you hit enter and show it in the correct label
Private
Sub txtguess_KeyPress(KeyAscii As Integer)
'
checks if answer is correct after enter key is hit.
If
KeyAscii = 13 Then 'if i hit the enter
key
numguesses = numguesses + 1
lblnumguesses.Caption = numguesses
guess = txtguess.Text 'loads user guess into variable guess
If
guess < secretnumber Then lblmessage.Caption = "Too Low"
If guess = secretnumber And cheater = False
Then
lblmessage.Caption = "You're right
and you only took " + Str(numguesses) + " guesses"
ElseIf cheater = True Then
lblmessage.Caption = "Doesn't
really count if you cheat"
End If
total = total +
guess 'a new value of total with guess added on
lbltotal.Caption = total
End
If
End
Sub