# [.net] Guessing Game using Random.Next in .NET

This topic is 4367 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I need to create a guessing game that generates a random number that the user has to guess. The user gets 10 chances to guess the number, and the computer tells the user if to guess lower or higher based on their guess and the actual number. If the user guess correctly the application should display a "congratualtions!" message. If the user does not guess the number within the amount of tries, the application should display the random number. Here is what I have so far... Private Sub uiGuessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uiGuessButton.Click Dim number As Integer Dim guess As Integer Dim randomGenerator As New Random 'generator Dim count As Integer ' counter Try 'get the number guessed guess = Convert.ToInt32(Me.uiGuessTextBox.Text) 'verify that the user entered a number Do While guess <> number number = randomGenerator.Next(1, 100) Do While count <= 10 'update counter count = count + 1 Loop Loop If guess > number Then 'display the guessed number in the label Me.uiNumberYouGuessed.Text = Convert.ToString(guess) 'display the guess needs to be lower Me.UiDisplayResultsLabel.Text = Convert.ToString("Please guess a lower number.") ElseIf guess < number Then 'display the guessed number in the label Me.uiNumberYouGuessed.Text = Convert.ToString(guess) 'display the guess needs to be higher Me.UiDisplayResultsLabel.Text = Convert.ToString("Please guess a higher number.") ElseIf guess = number Then 'display the guessed number in the label Me.uiNumberYouGuessed.Text = Convert.ToString(guess) 'tell the user they guessed correctly Me.UiDisplayResultsLabel.Text = Convert.ToString("Congratulations!") Else 'display try again Me.UiDisplayResultsLabel.Text = Convert.ToString("Try again.") End If 'after 10 tries, display the random number Me.UiDisplayResultsLabel.Text = Convert.ToString("The number was " & number & ".") Catch exformat As FormatException MessageBox.Show("The number must be numeric.", "Guessing Game", _ MessageBoxButtons.OK, MessageBoxIcon.Information) Catch ex As Exception MessageBox.Show(ex.Message, "Guessing Game", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Try Something is not in the right order her, because my code is giving me the answer after the first guess...

##### Share on other sites
I don't know if this is homework or not, so I'll just give a hint.

Do While count <= 10
'update counter
count = count + 1
Loop

The problem lies with that code.

##### Share on other sites
Yes, this is homework.
Does that Do while loop not need to be nested? Or do I have it in the wrong place and that is why I am terminating the program too soon? Thanks!

##### Share on other sites
if you have a loop inside another loop, the inside loop has to exit before the outer loop continues.

##### Share on other sites
OH YEAH! I remember learning that! LOL! That would be the inner loop contined within the outer loop, which must be true for the loops to be nested and to work correctly.

Hmmmmmm...
I don't need a nested loop do I?

##### Share on other sites
Hey vanidosa27,

There are a lot of logic errors in you code which makes it behave other than what you want it to do. Since it is a homework, I will throw you hints so you have something to think about.

- Notice that the number to guess is recalculated every time the button is clicked, so is the counter.

- "Do While guess <> number" at this point number was only declared... so it's 0!

- Think what Nypyren said

- Your condition " If guess > number ", do you see that it will always be executed only once?

- Notice that the lines
 Else'display try againMe.UiDisplayResultsLabel.Text = Convert.ToString("Try again.")End If

will never be executed because you already have smaller than, larger than, or equal.

##### Share on other sites
I think you need to rethink your code.

Try writing the program down logically on paper and the program will stare you right in the face. Now just a little hint I wouldn't write the entire logic of the game in a button click handler. Good luck

##### Share on other sites
- Notice that the number to guess is recalculated every time the button is clicked, so is the number of tries.

I can't seem to figure this one out

- "Do While guess <> number" at this point number was only declared... so it's 0!

Okay, so I need to initialize my number

- Think what Nypyren said

- Your condition " If guess > number ", do you see that it will always be executed only once?

No, I don't see this either

- Notice that the lines

Else
'display try again
Me.UiDisplayResultsLabel.Text = Convert.ToString("Try again.")
End If

I think I understand this one, I need to take out the =, or move it to the else statement?

##### Share on other sites
To Adam, I asked my teacher if I should use a Call method and she said that a user-defined sub procedure should only be used when two or more objects needs to call it?

##### Share on other sites
Pseudocode

1. declare variables
2. Generate a random number
3. convert the guess to and integer
4. Compare the guess with the random number
5. count the guess
6. tell the user if the guess is higher or lower
7. end after 10 guesses or correct answer

##### Share on other sites
I don't know if you quite got what I was saying. Your code looks as though the user only gets one guess because all your logic is inside the click handler.

You could always store the number of guesses made in the main form and then you could check the number of guesses when you enter the click handler and if it's less than 10 you can then check whether the number is greater, less, or equal and display the appropriate message.

I hope this helps you out a bit more.

##### Share on other sites
Quote:
 Original post by Adam HamiltonI don't know if you quite got what I was saying. Your code looks as though the user only gets one guess because all your logic is inside the click handler.You could always store the number of guesses made in the main form and then you could check the number of guesses when you enter the click handler and if it's less than 10 you can then check whether the number is greater, less, or equal and display the appropriate message.I hope this helps you out a bit more.

Can you show me an example of storing something in the main form and then checking?

##### Share on other sites
hehe, that's not pseudocode, it's a logic execution. Pseudocode is when you use the syntax of the programming language mixed with english description.

Did you learn about global variables?

Also, I would suggest to print the value of you variables. For example, in the code that you posted, print the value of number, guess and count after they are declared. Then print them again after guess is initiallized. Then again after the second loop. Then again after the if condition. This is just to let you know what is going on with you program, it will help you spot the errors.

##### Share on other sites
Quote:
 Original post by Darkneonhehe, that's not pseudocode, it's a logic execution. Pseudocode is when you use the syntax of the programming language mixed with english description.Did you learn about global variables?Also, I would suggest to print the value of you variables. For example, in the code that you posted, print the value of number, guess and count after they are declared. Then print them again after guess is initiallized. Then again after the second loop. Then again after the if condition. This is just to let you know what is going on with you program, it will help you spot the errors.

I am not to good at writing pseudocode. I have not learned global variables yet...
I'm trying here...

##### Share on other sites
I'm not that good at Visual Basic I'm just learning myself I come from a C++ background

Maybe someone with more Visual Basic experience can elaborate on what I'm trying to say but I'll give it a shot

Somewhere in your Form1 class or whatever is the main form declare a variable named guesses or something

Maybe you could put these just before your button click handler

' Correct me if I'm wrong with the Class keyword

Class Form1

Dim guesses As Integer ' Number of guesses the user has made
Dim number As Integer ' The number the computer is thinking of

Private Sub uiGuessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uiGuessButton.Click

.
.
.

End Sub

End Class

Now in your Form1_load handler do this (double click the main form in your Windows Forms Designer)

----------------------------------
Dim rng as New Random

number = rng.Next(1, 100)

' Set the number of guesses to 0
guesses = 0

-----------------------------------

Now in your button click handler do this

-------------------------------------
dim guess as integer

If guesses < 10 then

guess = Convert.ToInt32(Me.uiGuessTextBox.Text)

if guess < number then
'Do message less than
end if

if guess > number then
'Do message greater than
end if

if guess = number then
'Do message correct
end if

End If

I have to get back to work now but I'll check in later

I hope this somehow helps you out.

##### Share on other sites
Hmmm did your teacher specifically asked to use textboxes and a button? Did she teach how to use the InputBox? Unless someone can correct me, what you try to accomplish is impossible without global variables. I guess static variables could be used, but if you don't know about global variables I doubt you know about static variables.

I think you should review your program design and use a InputBox instead of a button. If your teach asked to use a button, then how to do this without global variables I don't know. You would need to list what you have learned so far maybe we could pin-point on something.

##### Share on other sites
In my last post I forgot to increment the guesses counter

Just after the line

If guesses < 10 Then

guesses = guesses + 1

.
.
.
.

End If

##### Share on other sites
Quote:
 Original post by DarkneonHmmm did your teacher specifically asked to use textboxes and a button? Did she teach how to use the InputBox? Unless someone can correct me, what you try to accomplish is impossible without global variables. I guess static variables could be used, but if you don't know about global variables I doubt you know about static variables. I think you should review your program design and use a InputBox instead of a button. If your teach asked to use a button, then how to do this without global variables I don't know. You would need to list what you have learned so far maybe we could pin-point on something.

Yes, I learned how to use the input box, and I learned about static varibles and had to write a code that took the amount owed and the amount paid and returned the change and then broke down the change into dollars, quarters, nickels, and pennies. So I needed my variables to be static in that problem (I needed them to retain their value, even when the procedure in which they were declared ended).
My professor just wants us to utilize all the code that we have learned in preceding chapters. I have coded all the easy stuff, like the exit button, the Textbox.SelectAll(), the Clearing the screen, and the Closing Event procedure.

When we did the inputbox lesson, it only returned a string to be assigned in a label on the form...

Would I put it in the Load event procedure?...

I think something like:
CONST PROMPT As string = "Enter your guess:"
Const TITLE As String = "Guessing Game"
'get the users guess and assign it to the module-level guess variable
guess = INputBox(PROMPT, TITLE)

##### Share on other sites
Yes, if you decide to use the InputBox, you can put you code in Form_Load. In a nutshell, your program will look something like that.

Declare variables
Initialize variables

Do While guesses < MaxNumberOfAllowedGuesses
'Program Logic
Loop

'Final output

##### Share on other sites
Can I just skip the Do While and use a Case Selection?

##### Share on other sites
No. Why would you want to skip the loop?

You must use the loop and you must use the selection. The selection goes inside the loop.

##### Share on other sites
Okay!

The Chapter we just finished was on Do While and nested Do selection structures, so I just automatically assumed that we should use those to code this problem ...

##### Share on other sites
Well, there are many different ways to solve the same problem. How you solve it is up to you, but you normally choose the easiest and fastest solution. Analogically, there are many ways to describe the same thing. The choice of words is up to you.

So I gave you one solution, and Adam gave you another. If you sit down and think some more, you might come up with another one. You can solve this problem without using the loop (look at Adam's code), if it is easier and faster for you, than go for it.

##### Share on other sites
I think I am incorporating some of both. I have my inputbox, and my module level variable.
I just wrote my counter

Dim number As Integer = 0
Dim randomGenerator As New Random 'generator
Dim count As Integer ' counter

Try

Do
count = 0
'generate a random number
number = randomGenerator.Next(1, 101)
'increment counter
count = count + 1
Loop While count >= 10

Catch exformat As FormatException
MessageBox.Show("The number must be numeric.", "Guessing Game", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Guessing Game", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try

With my Try/Catch statement, and now I am writing my IF/ELSE for the lower and higher numbers or correct answer. I think I might get this to work before midnight, or I lose power from the storm howling outside my windows! :)

##### Share on other sites
How do I get the InputBox to pop up again, after the first guess?