• 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

    • Gemini in Google Sheets can now generate fully editable charts by David Uzondu Back in January, Google introduced a feature in Google Sheets powered by Gemini that lets you ask the AI to create charts from your data. The problem was, these charts were just static pictures, slapped on top of your cells. You could not edit them, and they would not update if your data changed. Now, the company has upgraded the feature so you can edit the charts however you want, plus they stay synced with your data as it changes. The process is quite straightforward. You use the Gemini side panel and just type what you want, like "create a bar chart showing campaign performance by market." Gemini then builds the chart, and when you insert it, the chart appears in a completely new tab within your spreadsheet. From that new home, you have total control. You can change the title, tweak the colors, and adjust all the little details just like any normal chart you would build yourself. It is not a completely perfect system, however. The biggest catch is that the editable chart is linked to the data in that new tab, not your original data source. So if you want the chart to reflect new numbers, you have to update the data in the chart’s dedicated tab. This is a bit of a weird detour from how standard Sheets charts have always worked, where they update directly from the source cells. For certain, more complex chart types, Google also notes that Gemini might still fall back to spitting out a static image, so your mileage may vary. The full rollout began recently, with Google expecting it to reach everyone within one to three days. This update is available for a bunch of Google Workspace accounts, including Business Standard, Business Plus, Enterprise Standard, and Enterprise Plus. It is also included for anyone with a Google One AI Premium plan, which the company has since renamed to Google AI Pro and Ultra. If you are on one of the old Gemini Business or Enterprise add-ons that Google stopped selling back on January 15, 2025, you get this feature too. Just make sure your admin has the "Smart features and personalization" setting turned on, or none of this will work.
    • iOS feature updates are lacklustre. I know it’s difficult with a mature OS, but imagine the announcements without Liquid Glass. Pretty thin.
    • Should you buy the Kindle Scribe? What to know about Amazon's e-reader for notes and reading by Paul Hill We’re all familiar with the Amazon Kindle lineup of affordable e-readers, but did you know that Amazon has a Kindle for writing on too? That’s where the Kindle Scribe comes in. The Scribe is more notebook sized, rather than book sized and has the largest screen Amazon has ever included in a Kindle. With this device, Amazon is trying to expand the paper reading-like experience to paper writing-like. With the current discount, you can save up to 25%, with prices as low as $299.99. There are three models available: a 16GB, 32GB, and 64GB model. You cannot expand the storage so be sure to pick the size you’ll need from the get-go. The Kindle Scribe won’t be the perfect choice if all you want to do is read books, however, if you’re a student or professional who wants to take notes, or an avid reader that wants to make annotations, then this could be a good pick for you. What it does The Kindle Scribe features a large 10.2-inch glare-free display with a 300 ppi density. It comes with a Premium Pen that makes it feel like you’re writing on paper as you jot down your notes. To make writing easy, you get Active Canvas for in-book notes and a built-in notebook with templates. You can import and write on PDFs and documents via Send to Kindle, including sending directly from Word if you have a Microsoft 365 subscription. Once you have written out your notes, the Kindle Scribe allows you to summarize them using artificial intelligence. You can even customize the length and tone of your notes. You can also refine your notes by converting your handwritten words into a script font. One of the standout features of other Kindle devices is their spectacular battery life, and the Kindle Scribe promises the same. The battery will last you up to 12 weeks for reading and up to 3 weeks for writing. Furthermore, Amazon has used 18% recycled materials including 100% recycled aluminum parts, and it comes in fully recyclable packaging. Finally, and it shouldn’t really need mentioning, the Kindle Scribe has full access to the Kindle Store so you can quickly and easily gain access to all of the latest books. Should you buy it? If you are looking for a distraction free gadget to read books on and take notes then the Kindle Scribe is definitely worth considering now that it is at its lowest price to date. Students and professionals are two groups who might benefit the most from this model. If you’re just looking for a Kindle for reading on Amazon, there are other models that may be better such as the Paperwhite or Oasis. The Kindle Scribe is a pretty radical change for a Kindle device with its very large display and writing capabilities. If you’ve been waiting for something like this, then it may justify an upgrade from an older Kindle. If you do decide to buy, make sure to get enough storage from the get go. Amazon Kindle Scribe (16GB): $299.99 (Amazon US) / MSRP $399.99 Amazon Kindle Scribe (32GB): $319.99 (Amazon US) / MSRP $419.99 Amazon Kindle Scribe (64GB, Tungsten): $349.99 (Amazon US) / MSRP $449.99 Amazon Kindle Scribe (64GB, Metallic Jade): $349.99 (Amazon US) / MSRP $449.99 This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • They shouldn’t listen to stupid ideas and this is a stupid idea. Many issues can be fixed via the registry but not with general registry cleaners. Sometimes a value needs to be changed or a new key needs to be created or deleted but there is no way a general cleaner could make that distinction. Making daily backups of your system state is a better idea so if your system does start behaving differently you can revert to a previous date. System Restore used to be helpful in this area but doesn’t seem as reliable these days. A full registry restore is often helpful.
  • 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
      506
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      241
    4. 4
      +Edouard
      201
    5. 5
      snowy owl
      163
  • Tell a friend

    Love Neowin? Tell a friend!