We will make an application that makes us guess a number between 1 and 10 and making the computer as the jury. The computer will speak out whether the number we have input is too high, too low or correct. Firstly, create a new Website on ASP.NET web developer and build a simple interface like below.Also, include a label, name it as lblGuessedNumber and make it as invisible.
This will store a randomly generated number.
Add the Speech Object Library Object as reference.
To generate a random number, we make use of the Random class. On Page_Load event we place the following code snippet.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Try
If Not IsPostBack() Then
Dim number As Integer
Dim rnd As New Random() ' Random number generator
number = rnd.Next(1, 10) ' Generates random number between 1 and 10
' Storing the random number in the hidden label
lblGuessedNumber.Text = number
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Notice that the code is placed inside the Not IsPostBack() if statement as we do not want to generate a random number on every postback. Now, to validate the number that the user has input, we will make use of the following code snippet in the button's click event.
Protected Sub btnGuess_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGuess.Click
Try
' Variables declaration
Dim voice As New SpVoice
Dim userNumber As Integer
Dim computerNumber As Integer ' Parse the numbers and store then in integer variables
userNumber = Integer.Parse(txtNumber.Text)
computerNumber = Integer.Parse(lblGuessedNumber.Text) ' Speak the verdict
If (userNumber <>
voice.Speak(txtNumber.Text & " is too low!")
ElseIf (userNumber > computerNumber) Then
voice.Speak(txtNumber.Text & " is too high!")
Else
voice.Speak("Cool man! You guessed the correct number!")
End If
Catch ex As Exception
Throw ex
End Try
End Sub


