• 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

    • CapCut 6.5.0 (offline installer) by Razvan Serea CapCut is a versatile video editing app that offers a range of features such as multi-layer editing, keyframe animations, special effects, and more, to create professional-quality videos. With CapCut, users can edit and enhance their videos with a variety of tools such as filters, transitions, effects, and text overlays. CapCut's extensive library of pre-designed templates and visual effects also allows users to create unique and eye-catching videos in just a few clicks. Users can also adjust video speed, crop, and merge multiple clips, among other features. CapCut is available for both mobile devices and Windows, making it accessible for everyone. CapCut key features: User-friendly interface for easy video editing A wide range of editing tools, including trim, split, cut, and merge Music library with a wide range of tracks to choose from Customizable text and fonts to add captions and titles Multi-layer timeline for seamless editing and layering Filters and effects to enhance video quality and style A variety of transitions to choose from Multiple aspect ratio options for different platforms Green screen/chroma key for adding custom backgrounds Overlays and stickers to add to your videos Easy exporting to different video formats and resolutions Large library of pre-designed templates and visual effects Customizable video thumbnails for branding Keyframe animation to add movement to your video Speed adjustment for slow motion or time-lapse effects Customizable transitions between clips Reverse video playback for creative effects Voiceover recording and editing for narrating your video Color grading tools and much more... Download: CapCut 6.5.0 | 701.0 MB (Freeware) Links: CapCut Website | CapCut Screenshot | CapCut Online Editor Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Total Commander 11.55 by Razvan Serea Total Commander is a great two-pane file manager replacement for Windows, a program like Windows Explorer to copy, move, or delete files. It includes extra integrated applications like a built-in FTP client with FXP, a renaming tool, a disk space analyzer, a file synchronizer, can pack and unpack files, compare files by content, a quick view panel with bitmap display, HTTP proxy support and more. Total Commander 11 is compatible with Windows 95/98/ME/NT/2000/XP/Vista/7/8/8.1/10/11. Total Commander is distributed as shareware with a trial period of 30 days, but will continue to function, with a subscription reminder, after that. Total Commander features include: Two file windows side by side Multiple language and Unicode support Enhanced search function Compare files (now with editor) / synchronize directories Quick View panel with bitmap display ZIP, ARJ, LZH, RAR, UC2, TAR, GZ, CAB, ACE archive handling + plugins Built-in FTP client with FXP (server to server) and HTTP proxy support Parallel port link, multi-rename tool Tabbed interface, regular expressions, history+favorites buttons Thumbnails view, custom columns, enhanced search Compare editor, cursor in lister, separate trees, logging, enhanced overwrite dialog etc. Unicode names almost everywhere, long names (>259 characters), password manager for ftp and plugins, synchronize empty dirs, 64 bit context menu, quick file filter (Ctrl+S) USB port connection via special direct transfer cable, partial branch view (Ctrl+Shift+B), and many improvements to ftp, synchronizing and other functions And many more! Total Commander 11.55 release notes: This version mainly fixes bugs. Complete list of changes. New functions in Total Commander 11.55: Copying When "Copy to all selected folders/links..." is enabled, the "Keep relative paths" option is also respected Supports copying directories anywhere in subdirectories. For example, if "Only files of this type:" is set to "test\", the "test" folder will be found anywhere in the selected folders An overlay icon is displayed in the system tray when an overwrite confirmation dialog is open while Total Commander is not in the foreground When copying sparse files, only the parts containing non-zero data are copied. This option needs to be enabled via wincmd.ini [Configuration] CopySparseFiles=1 General Multi-rename tool: New placeholder [v] for inserting milliseconds, e.g. [hms].[v] Create/Verify Checksums: Use multiple threads for Blake3 checksums (64-bit only, on Windows 7 and newer) Use tc7z.dll as a fallback for unrar.dll if unrar.dll fails to load Rename directories in 7z archives when using the internal 7z packer New parameter for the internal MULTIRENAME command opens the tool and offers the user to undo the last operation Use external DLL tcsha64.dll to create/verify SHA3 checksums faster Download: Total Commander 11.55 | 10.6 MB (Shareware) View: Total Commander Website | Android | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • It should be the default browser behavior (apart from sending recorded audio to an external device)
    • "So if you are interested in this extension, for God's sake, do not try it in an office. Your coworkers will probably think you have finally lost it and are performing some bizarre humiliation ritual at your desk." If you install the plugin and start screaming at your system...you left being lost in the rear view.
    • Mullvad Browser 14.5.4 by Razvan Serea The Mullvad Browser is a privacy-focused web browser developed in a collaboration between Mullvad VPN and the Tor Project. It’s designed to minimize tracking and fingerprinting. You could say it’s a Tor Browser to use without the Tor Network. Instead, you can use it with a trustworthy VPN. The idea is to provide one more alternative – beside the Tor Network – to browse the internet with more privacy. To get as many people as possible to fight the big data gathering of today. To free the internet from mass surveillance. The Mullvad browser is free of charge, open source, and can be used without Mullvad VPN (although the combination is recommended). It is supported across platforms (Windows, MacOS, Linux). Privacy quality of the Tor Browser. To use with a VPN - Using a VPN is not enough to achieve perfect privacy online. There’s simply too much data being extracted through most browsers. The Mullvad Browser is a web browser with the privacy quality of the Tor Browser, to be used with a trustworthy VPN. Strong anti-fingerprinting from the Tor Project - The Tor Project has a proven track record of building a privacy-focused browser. The Mullvad Browser has the same fingerprinting protection as the Tor Browser – it just connects to the internet with (or without) a VPN instead of the Tor Network. No telemetry - Telemetry refers to unique data collected by the browser to enhance its performance. Mullvad does not support the collection of user data. Therefore, with the Mullvad Browser, all telemetry has been removed. Privacy first - Mullvad VPN has a proven record of putting privacy first. With no strange business models or short-term venture capitalist owners. The Tor Project is a non-profit organization fighting for human rights. Mullvad Browser 14.5.4 changelog: All Platforms Updated Firefox to 128.12.0esr Updated NoScript to 13.0.8 Bug 450: Rebase Mullvad Browser stable onto 128.12.0esr [mullvad-browser] Bug 43782: Add new UX flow for changing security level (Desktop) [tor-browser] Bug 43783: Tighten up the SecurityLevel module to enforce new UX flow [tor-browser] Bug 43784: Get confirmation from NoScript that settings are applied [tor-browser] Bug 43911: Backport security fixes from Firefox 140 [tor-browser] Build System / All Platforms Bug 41477: Update keyring/boklm.gpg for new subkeys (2025) [tor-browser-build] Bug 41498: Update keyring/morgan.gpg with updated public key [tor-browser-build] Download: Mullvad Browser 14.5 | 90.6 MB (Open Source) View: Mullvad Browser Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • First Post
      solidox earned a badge
      First Post
    • First Post
      BA the Curmudgeon earned a badge
      First Post
    • One Year In
      blissa jayden earned a badge
      One Year In
    • One Month Later
      blissa jayden earned a badge
      One Month Later
    • Week One Done
      blissa jayden earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      562
    2. 2
      ATLien_0
      213
    3. 3
      +FloatingFatMan
      171
    4. 4
      Michael Scrip
      152
    5. 5
      Som
      151
  • Tell a friend

    Love Neowin? Tell a friend!