• 0

Visual Basic - Guessing game (1 - 100)


Question


Public Class Form1

    

    Dim aRandNumGen As New Random

    Dim answer As Integer = aRandNumGen.Next(1, 101)

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        lblTime1.Text = "Time: " + TimeString

        lblTime2.Text = "Date: " + DateString

        GroupBox1.Hide()

    End Sub

 

    Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click

        If Not IsNumeric(TextBox1.Text) Then

            MessageBox.Show("Numeric")

        End If

        Dim guess As Integer

        guess = CInt(TextBox1.Text)

        If answer = guess Then

            GroupBox1.Show()

        End If

 

        If answer = guess Then

            Label2.Text = "Congartulations"

        ElseIf answer < guess Then

            Label2.Text = "Too High"

        ElseIf answer < guess - 5 Then

            Label2.Text = "A little too low"

        ElseIf answer > guess Then

            Label2.Text = "Too Low"

        ElseIf answer > guess + 5 Then

            Label2.Text = "A little too high"

        End If

        TextBox1.Focus()

        TextBox1.SelectionStart = 0

        TextBox1.SelectionLength =

            TextBox1.TextLength

    End Sub

    

    

End Class

 

So i need to make a guessing game and i can run it and get random number with good instruction but i am missing some codes like as you see that i want to make like if the randomnumber is near to the answer like + 5 it will said little too high and if rnadom number - 5 then it will said little too low but i can't seem to work it out and also that i am trying to make it so that the textbox1 can only be enter as numeric but whenever i put word it will make the program crash.

And i also have a groupbox saying Do you want to play again? with 2 rad buttons yes and no and a button OK

so i want to make it so that when the user enter the correct random number the groupbox will be visible but not at start

Link to comment
https://www.neowin.net/forum/topic/1170027-visual-basic-guessing-game-1-100/
Share on other sites

10 answers to this question

Recommended Posts

  • 0

Your crash is due to the fact that you still execute the CInt() cast even if the text is not numeric. Just read your code carefully, that's what it does. Don't do that.

 

Also you hide the groupbox on every tick of the timer, which means even if you show it when the user wins, it'll disappear as soon as the timer event happens again. You could hide it in the OnLoaded event and enable it when the user has guessed properly.

  • 0

Hey Asik

can you give me a hint about the crashing even without isnumeric i tried to remove it and yes it crash still but than if i remove the cint it won work because of option strict on and option explicit on so what you recommend me to do?

And for the groupbox i have fixed it to show up 

  • 0
Option Strict On

Option Explicit On

 

Public Class Form1

    

    Dim aRandNumGen As New Random

    Dim answer As Integer = aRandNumGen.Next(1, 101)

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        lblTime1.Text = "Time: " + TimeString

        lblTime2.Text = "Date: " + DateString

    End Sub

 

    Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click

        If Not IsNumeric(TextBox1.Text) Then

            MessageBox.Show("Numeric")

        End If

        If CDbl(TextBox1.Text) > 100 Then

            MessageBox.Show("Number be between 1 - 100")

        End If

        If CDbl(TextBox1.Text) < 1 Then

            MessageBox.Show("Number be between 1 - 100")

        End If

        Dim guess As Integer = CInt(TextBox1.Text)

 

        If answer = guess Then

            GroupBox1.Show()

        End If

 

        If answer = guess Then

            Label2.Text = "Congratulations"

        ElseIf answer < guess Then

            Label2.Text = "Too High"

        ElseIf answer - 5 < guess Then

            Label2.Text = "A little too low"

        End If

        If answer > guess Then

            Label2.Text = "Too Low"

        ElseIf answer + 5 > guess Then

            Label2.Text = "A little too high"

        End If

        TextBox1.Focus()

        TextBox1.SelectionStart = 0

        TextBox1.SelectionLength =

            TextBox1.TextLength

    End Sub

    

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        If RadYes.Checked Then

            Reset()

        End If

        If RadNo.Checked Then

            End

        End If

    End Sub

 

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click

        End

    End Sub

 

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click

        TextBox1.Clear()

    End Sub

End Class

 

Okay so this is my newly improve code and i have groupbox showing after the person guess correctly and now i just need to make that if the user enter not numeric it should pop up a message box "Numeric Only" but mine kept on crashing what do i need to fix?

And also i already make that if the user enter number correctly than groupbox show yes/no and a button if no then program will exit but if yes i want to reset it but what's the code?

  • 0
  On 11/08/2013 at 04:30, atyemail said:

 

 
        If Not IsNumeric(TextBox1.Text) Then
            MessageBox.Show("Numeric")
        End If
 
Okay so this is my newly improve code and i have groupbox showing after the person guess correctly and now i just need to make that if the user enter not numeric it should pop up a message box "Numeric Only" but mine kept on crashing what do i need to fix?

 

 

It's because you still run the whole code after showing the message box, try adding "Return" (means, in this case, stop running through the method) after that line:

If Not IsNumeric(TextBox1.Text) Then
    MessageBox.Show("Numeric Only")
    Return
End If
  • 0

Thank you very much,

Please help me atm i have problem when the random number is in range random number - 10 = a little too low but the a little too high is not working, any suggestion?

 

Public Class Form1
    
    Dim aRandNumGen As New Random
    Dim answer As Integer = aRandNumGen.Next(1, 101)
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        lblTime1.Text = "Time: " + TimeString
        lblTime2.Text = "Date: " + DateString
    End Sub
 
    Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click
        If Not IsNumeric(TextBox1.Text) Then
            MessageBox.Show("Numeric")
            Return
        End If
        If CDbl(TextBox1.Text) > 100 Then
            MessageBox.Show("Number be between 1 - 100")
        End If
        If CDbl(TextBox1.Text) < 1 Then
            MessageBox.Show("Number be between 1 - 100")
        End If
        Dim guess As Integer = CInt(TextBox1.Text)
 
        If answer = guess Then
            GroupBox1.Show()
        End If
 
        If answer = guess Then
            Label2.Text = "Congratulations"
        ElseIf answer < guess Then
            Label2.Text = "Too High"
        ElseIf answer - 10 < guess Then
            Label2.Text = "A little too low"
        ElseIf answer > guess Then
            Label2.Text = "Too Low"
        ElseIf answer + 10 > guess Then
            Label2.Text = "A little too high"
        End If
 
        TextBox1.Focus()
        TextBox1.SelectionStart = 0
        TextBox1.SelectionLength =
            TextBox1.TextLength
    End Sub
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If RadYes.Checked Then
            Reset()
        End If
        If RadNo.Checked Then
            End
        End If
    End Sub
 
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        End
    End Sub
 
    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        TextBox1.Clear()
    End Sub
End Class
  • 0
If answer = guess Then
    Label2.Text = "Congratulations"
ElseIf answer < guess Then
    Label2.Text = "Too High"
ElseIf answer - 10 < guess Then
    Label2.Text = "A little too low"
ElseIf answer > guess Then
    Label2.Text = "Too Low"
ElseIf answer + 10 > guess Then
    Label2.Text = "A little too high"
End If

It's because the logic is flawed. Try to read and follow the logic.

(I also recommend placing 'guess' on the left side for readability)

 

If you can't fix it yourself, this is how I would do it :

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

If guess = answer Then
    Label2.Text = "Congratulations"
ElseIf guess > answer Then
    If guess < answer + 10 Then
        Label2.Text = "A little too high"
    Else
        Label2.Text = "Too High"
    End If
ElseIf guess < answer Then
    If guess > answer - 10 Then
        Label2.Text = "A little too low"
    Else
        Label2.Text = "Too Low"
    End If
End If
  • 0
  On 11/08/2013 at 03:49, atyemail said:

Hey Asik

can you give me a hint about the crashing even without isnumeric i tried to remove it and yes it crash still but than if i remove the cint it won work because of option strict on and option explicit on so what you recommend me to do?

And for the groupbox i have fixed it to show up 

Your method should look roughly like this (pseudo-code, you figure out how to translate in VB):

If the text in the textbox is not a number Then
     print some error message
Else
     convert text to integer with CInt
     tell user whether the guess is above, below or equal to the answer
End If

Your problem currently is that you attempt to convert to integer even if the text isn't a number.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I am afraid to ask but what specific crowd are you talking about? Most people wanted Mozilla to concentrate on the browser but of course are still complaining when they do that. Anyway Firefox works just fine for me. We all deserve the Chrome only future that is coming.
    • Such a missed opportunity for a company with arena sized buckets of cash. The first on device AI and they never really improved it all those years. They could have been leading this charge.
    • Glow 25.06 by Razvan Serea Glow provides detailed reporting on every hardware component in your computer, saving you valuable time typically spent searching for CPU, motherboard, RAM, graphics card, and other stats. With Glow, all the information is conveniently presented in one clean interface, allowing you to easily access and review the comprehensive hardware details of your system. Glow provides detailed information on various system aspects, including OS, motherboard, processor, memory, graphics card, storage, network, battery, drivers, and services. The well-organized format ensures easy access to the required information. You can export all the gathered data to a plain text file, facilitating sharing with others for troubleshooting purposes. No installation needed. Just decompress the archive, launch the executable, and access computer-related information. Glow runs on Windows 11 and Windows 10 64-bit versions. Glow 25.06 release notes: What's new Support provided for Windows 11 24H2 May 2025 update. Support provided for Intel Arrow Lake-H series processors. Support for AMD Ryzen AI series processors. Support for NVIDIA RTX 50 series graphics cards. Support for AMD RX 9000 series graphics cards. Support for processors and graphics cards from Intel, AMD and NVIDIA until May 2025. Support for GDDR7 graphics memory. .NET Framework June 2025 security update has been integrated. Fixed Bugs Fixed DPI bug in the Memory Test Tool that caused buttons to be nested with the table at 150% DPI and above. Fixed a translation bug in the Cache Cleanup Tool that caused an incorrect character encoding set in the Russian language. Fixed various DPI bug and character encoding bug fixes. Note: Always unzip the program before using it. Otherwise you may get an error. Download: Glow 25.06 | 2.0 MB (Open Source) View: Glow Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • How to enable the redesigned Windows 11 Start menu by Taras Buria This week, Microsoft started testing a big redesign for Windows 11's Start menu. It is now rolling out to Windows Insiders in the Dev and Beta Channels, addressing quite a few pain points in the original Start menu, which was shipped in late 2021. Nearly four years later, we finally have the long-anticipated redesign (announced earlier this year). The updated menu now features a single-page view, with all your pins and apps on one scrollable page. You can change the list of all apps between three variants: list, grid, and category. More importantly, you can now hide the recommended section in the Start menu settings (one of the most requested Start menu-related changes). The new Start menu is available in this week's Dev and Beta update. However, like always, Microsoft is rolling out changes gradually, which means you might not have the lucky ticket even on the latest build. If you do not want to wait, you can force-enable the new Start menu and its Phone Link button using a few commands in the ViVeTool app. Here is how to do that: Download ViveTool from GitHub and unpack the files in a convenient and easy-to-find folder. Run Command Prompt as Administrator and navigate to the folder containing the ViveTool files with the CD command. For example, if you have placed ViveTool in C:\Vive, type CD C:\Vive. Type vivetool /enable /id:47205210,49221331,49381526,49402389,49820095,55495322,48433719 and press Enter. Restart your computer. As usual, keep in mind that stuff in preview builds is less stable, so be aware of the risks of running preview builds. While Microsoft is not saying when the new Start menu will be available to all users, it will probably not take too long before it shows up in Release Preview and non-security updates. By the way, if you are curious, check out some of the prototypes that Microsoft considered when designing the new Start menu. Credit for the IDs goes to @phantomofearth on X.
    • reddit's "bottom of the barrel" > 99% of neowin front page "news"
  • Recent Achievements

    • Week One Done
      IAMFLUXX earned a badge
      Week One Done
    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
    • First Post
      Kurotama earned a badge
      First Post
    • Collaborator
      Carltonbar earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      ATLien_0
      268
    3. 3
      +FloatingFatMan
      234
    4. 4
      +Edouard
      201
    5. 5
      snowy owl
      162
  • Tell a friend

    Love Neowin? Tell a friend!