猜数字的小程序源码

设计一个猜数字游戏程序,由系统自动产生一个四位数,各位数字互不相同,给玩家8次从键盘录入四个数字的机会,每次给出玩家猜中数字的个数及位置,直到数字及位置完全一致为止,如果8次机会均猜不中,则输出产生的四位数。例如:若产生的数为2358:
次数用户输入系统提示解释
112340A2B猜中2个数字(2、3),但位置不对
256781A1B猜中2个,有1个位置也正确(8),有1个位置不对(5)
323902A0B猜中2个数字(2、3)且位置也正确
423783A0B猜中3个数字(2、3、8),且位置也正确
523952A1B猜中3个数字,有2个位置也对(2、3),1个位置不对(5)
623852A2B猜中4个数字,但2个位置对(2、3),2个位置不对(8、5)
72358恭喜你!你猜得完全正确!

Private Sub form_Click()
Dim a(3), b(3), i, j, k, tmp, tmp1 As String, p As Boolean, A1, B1
Randomize
For i = 0 To 3
    a(i) = Int(Rnd * 10)
    For k = 0 To i - 1
        If a(i) = a(k) Then i = i - 1
    Next k
    Debug.Print a(i),
Next i
For i = 1 To 8
    tmp = InputBox("请输入四位不同的数字(0-9)" & vbNewLine & "输入为空或取消则中止运行。", "这是第" & i & "次猜题")
    If tmp = "" Then Exit Sub
    p = False
    If Len(Trim(tmp)) = 4 Then
        For j = 1 To 4
            tmp1 = Mid(tmp, j, 1)
            If tmp1 >= "0" And tmp1 <= "9" Then
                b(j - 1) = Val(tmp1)
                For k = 1 To j - 1
                    If b(j - 1) = b(k - 1) Then
                        p = True
                        Exit For
                    End If
                Next k
            Else
                p = True: Exit For
            End If
        Next j
    Else
        p = True
    End If
    If p Then
        MsgBox "输入数据相同或非法!请再试一次!", , "猜数字"
        i = i - 1
    Else
        A1 = 0: B1 = 0
        For k = 0 To 3
            If a(k) = b(k) Then
                A1 = A1 + 1
            Else
                For j = 0 To 3
                    If a(k) = b(j) Then B1 = B1 + 1
                Next j
            End If
        Next k
        Print i, tmp, A1 & "A" & B1 & "B"
        If A1 = 4 Then
            MsgBox tmp & "恭喜你!你猜得完全正确!", , "猜数字"
            Exit Sub
        End If
    End If
Next i
End Sub

你可能感兴趣的:(string,游戏)