Quantcast
Channel: VBForums - Visual Basic 6 and Earlier
Viewing all articles
Browse latest Browse all 21100

Creating a Guessing Game

$
0
0
As a class project, we need to create a guessing game where the computer generates a number between 1 and 50. The user uses a button and a text box to input guesses. Here is my code so far:

Public Module Variables

Public guesses As Integer = 5

Public secret As Integer = CInt(Int((6 * Rnd()) + 1))
End Module


Public Class Form1


Public Sub btnguess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnguess.Click


Dim input As Integer

input = CInt(txtguess.Text)

If input = secret Then
MessageBox.Show("You got it right!", "You won!")
Me.Close()

ElseIf input > 50 Or input < 1 Then
lbldiff.Text = "Invalid guess entered!"
guesses -= 1
lblguesses.Text = "Guesses: " & guesses
ElseIf input > secret Then
lbldiff.Text = "Too High!"
guesses -= 1
lblguesses.Text = "Guesses: " & guesses
ElseIf input < secret Then
lbldiff.Text = "Too Low!"
guesses -= 1
lblguesses.Text = "Guesses: " & guesses
End If
If guesses = 0 Then
MessageBox.Show("Out of guesses! You lose!", "Game over!")
lblguesses.Text = "The correct answer was " & secret
btnrestart.Visible = True
ElseIf guesses < 0 Then
lblguesses.Text = "The correct answer was " & secret
End If

End Sub

Private Sub btnrestart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrestart.Click
btnrestart.Visible = False
Application.Restart()
End Sub
End Class

I would put
Public secret As Integer = CInt(Int((6 * Rnd()) + 1))
under form.load, however the variable is local and doesn't influence the btnGuess.click events.

In the module, I can declare a random number, however it is always the same number for some reason because I can't put
Randomize()
in a module category.

Anyone have any ideas to fix this?

Viewing all articles
Browse latest Browse all 21100

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>