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