Visual Basic provides a function that can generate random numbers. This function, Rnd, will return a random number, of type Single, between 0 and 1. To get truly random numbers, you must initialize the random number generator using the Randomize statement. Place this statement in the Form Load event.
Create a program that will “think” of a number between 1 and 10. In a Do While loop, use the InputBox function to ask the user to guess the number. Keep track of how many tries it takes the user to guess the number.
Tell the user how many tries it took him to guess the number. Use Select Case to display an appropriate message, based on the number of tries (see below). You may use a label on the form or MsgBox for the output.
To create a random number between 1 and 10, multiply the result of Rnd by 10 and add 1. Rnd * 10 + 1
Use the Int function to convert the result of Rnd to an integer.
Here’s help (use Option Explicit, Val function, appropriate data types and standard prefixes):
Private Sub cmdStart_click( )
‘Declare RandomNumber variable
‘Declare InputNumber variable
‘Declare Counter variable
‘Create random number between 1 and 10
RandomNumber = Int(Rnd * 10 + 1)
‘Use this line of code during testing, then remove it!
‘Get numeric value of user’s guess and accumulate number of guesses until there’s a match
Do While InputNumber <> RandomNumber
InputNumber = Val(InputBox (“Guess my number between 1 and 10”,”Guessing Game”))
Counter = Counter + 1
Select Case Counter
MsgBox (“Wow! You guessed my number in 1 try!”)
Case 2 to 3
MsgBox (“Great job! You guessed my number in “ & Counter & “ tries!”)
Case 4 to 5
Every time that I press the start button to begin guessing numbers, the answer is revealed on the side. How do I stop this?