Public Class frmMain
'Declare Global for Random Generator, Random Number, Number of Guesses & an Array of the Guesses
Dim numRandom As New Random
Dim numAnswer As Integer
Dim numGuesses As Integer = 0
Dim aryGuesses() As Integer
'On Load
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Generate Random Number, and Blank the Guesses Label
numAnswer = numRandom.Next(1, 101)
lblGuesses.Text = ""
End Sub
'Validate Guess before Entry
Private Sub txtGuess_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtGuess.TextChanged
'Is it Numeric ?
If IsNumeric(txtGuess.Text) = False Then
ErrorProvider.SetError(txtGuess, " Your guess must Numeric ")
btnGuess.Enabled = False
'Is it Greater Than or Equle to 1 ?
ElseIf 1 >= txtGuess.Text Then
ErrorProvider.SetError(txtGuess, " Your guess must be greater than, or equle to 1 ")
btnGuess.Enabled = False
'Is is Less Than or Equle to 100 ?
ElseIf 100 <= txtGuess.Text Then
ErrorProvider.SetError(txtGuess, " Your guess must be less than, or equle to 100 ")
btnGuess.Enabled = False
'Is it a Unique number ?
ElseIf lstAnswers.Items.Contains(txtGuess.Text) = True Then
ErrorProvider.SetError(txtGuess, " You cannot guess the same number again ")
btnGuess.Enabled = False
Else 'Allow the Guess
ErrorProvider.SetError(txtGuess, "")
btnGuess.Enabled = True
End If
End Sub
'Reset Button
Private Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
'Reset the Array, ListBox, TextBox, Label, Button, Picture, Number of Guesses, and Generate new Random Number
Array.Clear(aryGuesses, 0, numGuesses)
lstAnswers.DataSource = aryGuesses
txtGuess.Clear()
lblGuesses.Text = ""
txtGuess.Enabled = True
btnGuess.Enabled = False
pctWrong.Visible = False
numAnswer = numRandom.Next(1, 101)
numGuesses = 0
End Sub
'Guess
Private Sub btnGuess_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGuess.Click
'Is the guess the Answer ? Then Show it.
If txtGuess.Text = numAnswer Then
pctWrong.Visible = True
pctWrong.ImageLocation = "tick.png"
btnGuess.Enabled = False
txtGuess.Enabled = False
'Is is Greater Than ? Indicate it through image and Add to Answers List
ElseIf txtGuess.Text > numAnswer Then
ReDim Preserve aryGuesses(numGuesses)
aryGuesses(numGuesses) = txtGuess.Text
pctWrong.Visible = True
pctWrong.ImageLocation = "arrow_down.png"
Else 'Is is Less Than ? Indicate it through image and Add to Answers List
ReDim Preserve aryGuesses(numGuesses)
aryGuesses(numGuesses) = txtGuess.Text
pctWrong.Visible = True
pctWrong.ImageLocation = "arrow_up.png"
End If
'Add one to the Number of Guesses
numGuesses = numGuesses + 1
'If you have made 10 guesses then end the game, otherwise just display the number.
If numGuesses = 10 Then
btnGuess.Enabled = False
lblGuesses.Text = "Game Over"
Else
lblGuesses.Text = "Guess Number: " & numGuesses & " of 10"
End If
'Display Answer in ListBox
lstAnswers.DataSource = aryGuesses
End Sub
End Class