Sign in to follow this  
vanidosa27

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

Recommended Posts

vanidosa27    122
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 this post


Link to post
Share on other sites
vanidosa27    122
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 this post


Link to post
Share on other sites
vanidosa27    122
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 this post


Link to post
Share on other sites
Darkneon    166
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 again
Me.UiDisplayResultsLabel.Text = Convert.ToString("Try again.")
End If

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

Share this post


Link to post
Share on other sites
Adam Hamilton    271
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 this post


Link to post
Share on other sites
vanidosa27    122
- 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 this post


Link to post
Share on other sites
vanidosa27    122
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 this post


Link to post
Share on other sites
vanidosa27    122
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 this post


Link to post
Share on other sites
Adam Hamilton    271
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 this post


Link to post
Share on other sites
vanidosa27    122
Quote:
Original post by Adam Hamilton
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.


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

Share this post


Link to post
Share on other sites
Darkneon    166
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 this post


Link to post
Share on other sites
vanidosa27    122
Quote:
Original post by Darkneon
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.


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

Share this post


Link to post
Share on other sites
Adam Hamilton    271
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 this post


Link to post
Share on other sites
Darkneon    166
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 this post


Link to post
Share on other sites
vanidosa27    122
Quote:
Original post by Darkneon
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.


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 this post


Link to post
Share on other sites
Darkneon    166
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 this post


Link to post
Share on other sites
vanidosa27    122
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 this post


Link to post
Share on other sites
Darkneon    166
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 this post


Link to post
Share on other sites
vanidosa27    122
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this