Public Class frmNum
Dim intNum, intTimes, intMaxNum, intMinNum As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'加载窗体时生成随机数字
Dim rndNum As New Random
intNum = rndNum.Next(0, 100) '大于等于0,小于100的整数
lblAbout.Text = ""
intMinNum = 0
intMaxNum = 99
End Sub
Private Sub btnNum_Click(sender As Object, e As EventArgs) Handles btnNum.Click
If IsNumeric(txtNum.Text) Then '检测是否是数字
Try '防止数字超过整型数字范围
Dim intInputNum As Integer = CInt(txtNum.Text) '不必设置为公共变量
If intInputNum >= 0 AndAlso intInputNum < 100 Then
intTimes = intTimes + 1 '统计次数
If intInputNum > intNum Then
lblTell.Text = "高了"
txtNum.SelectAll() '方便用户修改
If chkTell.Checked = True Then
intMaxNum = intInputNum
End If
ElseIf intInputNum < intNum Then
lblTell.Text = "低了"
txtNum.SelectAll() '方便用户修改
If chkTell.Checked = True Then
intMinNum = intInputNum
End If
Else
'次数不同,提示不同,不然太单调了。
Select Case intTimes
Case 1
lblTell.Text = intTimes & "次就中,超级牛啊!赶快去买彩票吧!"
Case Is < 5
lblTell.Text = intTimes & "次猜中,您是用香水洗过手吗?!"
Case Is < 10
lblTell.Text = intTimes & "次猜中,太棒了,您运气不错啊!"
Case Is < 20
lblTell.Text = intTimes & "次猜中,恭喜您终于猜对了!"
Case Is < 50
lblTell.Text = intTimes & "次猜中,运气有些背啊!再试一次吧!"
Case Is < 90
lblTell.Text = intTimes & "次猜中,好衰啊,不过还是猜对了!"
Case Else
lblTell.Text = intTimes & "次猜中,恭喜您要创世界纪录了!"
End Select
'重新开始
Dim rndNum As New Random
intNum = rndNum.Next(0, 100)
intTimes = 0
intMinNum = 0
intMaxNum = 99
If chkTell.Checked = True Then
lblAbout.Text = "范围:0~99"
End If
End If
If chkTell.Checked = True Then
lblAbout.Text = "范围:" & intMinNum & "~" & intMaxNum
End If
Else
MsgBox("错误,输入数字超出范围")
End If
Catch ex As Exception
MsgBox("错误,输入数字超出范围")
End Try
Else
MsgBox("错误,请输入数字!")
End If
End Sub
Private Sub chkTell_CheckedChanged(sender As Object, e As EventArgs) Handles chkTell.CheckedChanged
If chkTell.Checked = True Then
lblAbout.Text = "范围:" & intMinNum & "~" & intMaxNum
End If
End Sub
Private Sub txtNum_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNum.KeyPress
'回车调用按钮事件
If e.KeyChar = ChrW(13) Then
Me.btnNum_Click(sender, e)
End If
End Sub
End Class
本代码在VS2017+win10编译通过
猜数字软件下载
链接:https://pan.baidu.com/s/1pzx29N148EIXiRcucZ0acA
提取码:9fj7
二分法,算法实例——猜数字小游戏的vb.net代码
最新推荐文章于 2023-09-13 17:10:29 发布