網路城邦
回本城市首頁 唐老鴨之家
市長:  副市長:
加入本城市推薦本城市加入我的最愛訂閱最新文章
udn城市資訊科技網路分享【唐老鴨之家】城市/討論區/
討論區Excel VBA 字體:
上一個討論主題 回文章列表 下一個討論主題
猜四個相異數字的遊戲
 瀏覽1,662|回應0推薦0


等級:6
留言加入好友
Rem === 猜數字遊戲 ===
Rem 猜四位數字(無重複)
Rem xA表示字對位置也對的有x個
Rem yB表示字對位置不對的有y個
Rem 使用元件:Text1,2,Label1,2,3,Command1,2,3

Dim Num(4) As Integer
Dim Used(10) As Boolean
Dim Selected(10) As Boolean
Dim Position(10) As Integer

Private Sub CommandButton1_Click() '輸入完成
For I = 1 To 4
tmp = Val(Mid(TextBox1.Text, I, 1))
If Position(tmp) = I Then
aa = aa + 1
Else
If Selected(tmp) Then
BB = BB + 1
End If
End If
Next I
TextBox2.Text = TextBox2.Text & TextBox1.Text & " ===> " & Str(aa) & "A" & Str(BB) & "B" & vbCrLf
TextBox1.Text = ""
If aa = 4 Then
MsgBox "恭喜,你答對了!"
End If
End Sub

Private Sub CommandButton2_Click() '直接看答案
For I = 1 To 4
tmpstr = tmpstr & Str(Num(I))
Next I
TextBox2.Text = TextBox2.Text & "答案:" & tmpstr & vbCrLf
TextBox1.Visible = False
CommandButton1.Visible = False
CommandButton2.Visible = False
End Sub

Private Sub CommandButton3_Click() '重新開始
TextBox1.Visible = True
CommandButton1.Visible = True
CommandButton2.Visible = True
TextBox2.MultiLine = True
TextBox1.Text = ""
TextBox2.Text = ""
For I = 0 To 9
Selected(I) = False
Position(I) = 0
Next I
Randomize
For I = 1 To 4
Do
Num(I) = Int(Rnd * 10)
Loop While (Selected(Num(I)))
Selected(Num(I)) = True
Position(Num(I)) = I
Next I
End Sub

Private Sub TextBox1_Change()
For I = 0 To 9
Used(I) = False
Next I
tmplen = Len(TextBox1.Text)
If tmplen <> 4 Then
CommandButton1.Visible = False
If tmplen > 4 Then
TextBox1.Text = Left(TextBox1.Text, tmplen - 1)
tmplen = tmplen - 1
End If
Else
CommandButton1.Visible = True
End If
For I = 1 To tmplen
tmpch = Mid(TextBox1.Text, I, 1)
Used(Val(tmpch)) = False
Next I
For I = 1 To tmplen
tmpasc = Asc(Mid(TextBox1.Text, I, 1))
If tmpasc > 47 And tmpasc < 59 Then
If Used(tmpasc - 48) Then
MsgBox "數字重複"
TextBox1.Text = Left(TextBox1.Text, tmplen - 1)
Else
Used(tmpasc - 48) = True
End If
Else
If tmpasc <> 8 Then 'the Backspace
MsgBox "必需輸入數字"
TextBox1.Text = Left(TextBox1.Text, tmplen - 1)
End If
End If
Next I
End Sub

本文於 修改第 1 次
回應 回應給此人 推薦文章 列印 加入我的文摘

引用
引用網址:https://city.udn.com/forum/trackback.jsp?no=58536&aid=5035797