分享

vba写的猜数字游戏

 Slient66 2024-05-24 发布于河北

游戏的目标是猜测一个1到100之间的随机数。


Sub 猜数字游戏()
   Dim targetNumber As Integer
   Dim userGuess As Integer
   Dim attempts As Integer
   
   ' 生成一个1到100之间的随机数
   Randomize
   targetNumber = Int((100 - 1 + 1) * Rnd + 1)
   
   ' 初始化尝试次数
   attempts = 0
   
   ' 循环直到用户猜对数字
   Do
       ' 获取用户输入
       userGuess = InputBox('请输入一个1到100之间的数字:', '猜数字游戏')
       
       ' 检查用户输入是否有效
       If userGuess < 1 Or userGuess > 100 Then
           MsgBox '请输入一个1到100之间的数字。'
       Else
           ' 增加尝试次数
           attempts = attempts + 1
           
           ' 检查用户猜测是否正确
           If userGuess = targetNumber Then
               MsgBox '恭喜你,猜对了!你尝试了' & attempts & '次。'
               Exit Do
           ElseIf userGuess < targetNumber Then
               MsgBox '猜低了,请再试一次。'
           Else
               MsgBox '猜高了,请再试一次。'
           End If
       End If
   Loop
End Sub
```

要运行这个游戏,请将代码复制到Excel VBA编辑器中的一个新模块,然后运行`猜数字游戏`子程序。

Sub 猜数字游戏()
   Dim targetNumber As Integer
   Dim userGuess As Integer
   Dim attempts As Integer
   
   ' 生成一个1到100之间的随机数
   Randomize
   targetNumber = Int((100 - 1 + 1) * Rnd + 1)
   
   ' 初始化尝试次数
   attempts = 0
   
   ' 循环直到用户猜对数字
   Do
       ' 获取用户输入
       userGuess = InputBox('请输入一个1到100之间的数字:', '猜数字游戏')
       
       ' 检查用户输入是否有效
       If userGuess < 1 Or userGuess > 100 Then
           MsgBox '请输入一个1到100之间的数字。'
       Else
           ' 增加尝试次数
           attempts = attempts + 1
           
           ' 检查用户猜测是否正确
           If userGuess = targetNumber Then
               MsgBox '恭喜你,猜对了!你尝试了' & attempts & '次。'
               Exit Do
           ElseIf userGuess < targetNumber Then
               MsgBox '猜低了,请再试一次。'
           Else
               MsgBox '猜高了,请再试一次。'
           End If
       End If
   Loop
End Sub

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多