If you find any post useful then, please do share with others. Thanks!

Popular Posts

Contact

Email me

Need help and that also free? I like to learn this way, in case of any question or for a small task, please feel free to email me with details and example data, if required.

Friday, March 17, 2023

Number Guessing Game, Using Excel VBA

In this game, the player has to guess a randomly generated secret number between 1 and 100. The player has 10 guesses to correctly guess the number. After each guess, the player is told whether the secret number is higher or lower than their guess. If the player correctly guesses the secret number, they win the game. If the player uses up all their guesses without correctly guessing the secret number, they lose the game.


Note: This game uses the Rnd function to generate a random number. However, the Rnd function is based on the system clock, so if you want to generate truly random numbers, you may need to use a more advanced random number generator.


Sub NumberGuessingGame()

    Dim SecretNumber As Integer

    Dim Guess As Integer

    Dim GuessesRemaining As Integer

    

    SecretNumber = Int((100 - 1 + 1) * Rnd + 1) 'generate a random number between 1 and 100

    GuessesRemaining = 10 'set the number of guesses

    

    Do While GuessesRemaining > 0

        Guess = InputBox("Guess the secret number between 1 and 100." & vbNewLine & "You have " & GuessesRemaining & " guesses remaining.", "Number Guessing Game")

        If Guess = SecretNumber Then

            MsgBox "Congratulations! You guessed the secret number in " & (10 - GuessesRemaining + 1) & " guesses."

            Exit Sub

        ElseIf Guess < SecretNumber Then

            MsgBox "The secret number is higher than your guess."

        ElseIf Guess > SecretNumber Then

            MsgBox "The secret number is lower than your guess."

        End If

        GuessesRemaining = GuessesRemaining - 1

    Loop

    

    MsgBox "Game over. The secret number was " & SecretNumber & "."

End Sub


No comments:

Post a Comment