mardi 22 mars 2016

Random Number generator -VB

I am trying to generate a random number and have put it in the form1 loaded sub routine. I want the number to remain the same until the time they have guessed it correctly and not change in every button click.

Option Strict On
Option Explicit On
Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Dim RandNo As Integer       'Random Number
    Randomize()
        RandNo = CInt(29 * Rnd() + 1)
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim guess As Integer        'guess number
    Dim numTry As Integer       'No. of trys
    Dim RandNo As Integer       'Random Number
    Dim OrdNo As Integer        'Ordinal Number
    Dim Score As Integer        'Score

    Score = 0 'Initial value of score set as 0
        OrdNo = 1 'Initial value of ordinal set as 1 

        guess = CInt(TextBox1.Text)
        OrdNo = +1
        Label5.Text = CStr(OrdNo)

    'Show Message Box if the guess is not within the range
    If 1 > guess Then
            MessageBox.Show("Input within the range (1-30)", "Error", MessageBoxButtons.OK)
        End If

        'Show Message Box if the guess is not within the range
        If guess > 30 Then
            MessageBox.Show("Input within the range (1-30)", "Error", MessageBoxButtons.OK)
        End If

        'Display result and message when guess is larger than the lucky number
        If guess > RandNo Then
            Label11.Text = CStr(guess)
            Label10.Text = "The Lucky Number is smaller than your guess"
            OrdNo = +1
            Label5.Text = CStr(OrdNo)
        End If

        'Display result and message when guess is smaller than lucky number
        If guess < RandNo Then
            Label11.Text = CStr(guess)
            Label10.Text = "The Lucky Number is larger than your guess"

        End If

        numTry = 21

        For numTry = 21 To 0 Step -1
            Label4.Text = CStr(numTry)
        Next

        'Display result and message when guess is equal to the lucky number
        If guess = RandNo Then
            Label11.Text = CStr(guess)
            Label10.Text = "Congratulations ! This is the lucky number"
            Score = +10 'Increase the score by 10
            Label6.Text = CStr(Score)
            OrdNo = +1
            Randomize()
            RandNo = CInt(29 * Rnd() + 1)

        End If

    End Sub

End Class




Aucun commentaire:

Enregistrer un commentaire