Guess the number game - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

In this tutorial I'll show you how to write a game that ask you to guess a number. This game use a timer to generate a random number from 1 to 100

For this Tutorial we need 2 buttons: Name the first one "Play" and the second one "Ok".
We also need 1 textbox to enter the guessed number, 1 timer and 3 labels.

We should change the labels visibility to false. Do that by right click on each label and go to properties. In the properties window change "Visible to False"

The timer interval must be 1. To do that right click on Timer1 then properties. On the properties window change the interval to 1

For the form load event we add the following code:

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Label1.Text = 1
        'we start the timer
        Timer1.Start()
        'we disable button2, we enable it when user enter a number
        Button2.Enabled = False
        Label1.Visible = False
    End Sub

Then click on the timer and add the following highlighted code:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'We make the timer count till 100 then start over from 1
        Label1.Text += 1
        If Label1.Text = 100 Then
            Label1.Text = 1
        End If
    End Sub

Now we add the code to the play button: button1
Double click on button1 and add the following code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Button1 we stop the timer and therefore generate a random number
        If Button1.FlatStyle = FlatStyle.Standard Then
            Timer1.Stop()
            Button1.FlatStyle = FlatStyle.Flat
            Button2.Enabled = True
        ElseIf Button1.FlatStyle = FlatStyle.Flat Then
            Timer1.Start()
            Button1.FlatStyle = FlatStyle.Standard
            Button2.Enabled = False
        End If
    End Sub

Now we add the code for the button2.click event

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'This will check if the user enter the right number
        If TextBox1.Text = Label1.Text Then
            MsgBox("Congratulations, You guessed the right number")
            Label3.Text = -1
       Button1.FlatStyle = FlatStyle.Standard
            TextBox1.Text = ""
        ElseIf TextBox1.Text > Label1.Text Then
            MsgBox("Number is Smaller than " & TextBox1.Text)
        ElseIf TextBox1.Text < Label1.Text Then
            MsgBox("Number is Greater than " & TextBox1.Text)

        End If
        TextBox1.Focus()
        TextBox1.SelectAll()
        Label3.Text += 1
        Label2.Text = "Number tried: " & Label3.Text
    End Sub


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.