PDA

View Full Version : VB loop on random # generator..need help


jmoney3457
11-29-2007, 06:45 AM
i've made this random game (random # generator) but i can't figure out how to put in a loop and have it show When number is correct display a message that states it is the correct number and how many guesses it took. ..here is my code so far Public Class Form1

Private Sub exitgame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitgame.Click
'close the form
Me.Close()
End Sub

Private Sub start_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles start.Click
'show the new form
Dim popup As New Form2()
Form2.Show()
End Sub
End Class

Public Class Form2

Private Sub btn_cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
'close the form
Me.Close()
End Sub

Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click
'declare variables
Dim randomNumber As Integer
Dim numGuesses As Integer
'generate random number between 1 and 100
randomNumber = Int((100 * Rnd()) + 1)
'if the guess is too low, prompt user
If (guess.Text < randomNumber) Then
MessageBox.Show("Guess Higher", "Try Again", MessageBoxButtons.OK)
'increment number of guesses by 1
numGuesses = numGuesses + 1
'if the guess is too high, prompt user
ElseIf (guess.Text > randomNumber) Then
MessageBox.Show("Guess Lower", "Try Again", MessageBoxButtons.OK)
'increment number of guesses by 1
numGuesses = numGuesses + 1
'if they guess the right number, congradulate them.
ElseIf (guess.Text = randomNumber) Then
MessageBox.Show("Congradulations!", "You're Correct", MessageBoxButtons.OK)
'close the form
Me.Close()
End If
'if they guess more than 10 times then tell them the answer and close the form.
If (numGuesses > 10) Then
MessageBox.Show("The answer is" + randomNumber, "Nice Try", MessageBoxButtons.OK)
Me.Close()
End If
End Sub
End Class

Roelf
11-29-2007, 09:32 AM
you generate a new number everytime a user clicks OK. After generating the number, you compare the user input to this new number.

I think you should generate a number once, perhaps on opening of your form2. Store this number in a private member of the form. Each time a user clicks ok, compare the input to this value in the private member.

jmoney3457
11-29-2007, 09:39 PM
anyone got code on how to put in a loop & would display the correct answer when the user inputs it & how many guesses it took?