我正在尝试编写将产生4张随机扑克牌的代码
(来源:wiseowl.co.uk)
这些值显然应该是唯一的。这是我已经尝试过的代码,但是无法使其正常工作。
Sub poker_is_hard()
Dim r As Range
Dim c As Variant
Dim s As Variant
Dim cs As Variant
Set r = Workbooks("Poker game.xls").Worksheets("Cards").Range("B2:E6")
cs = c & "" & s
For Each cs In r
c = Int(Math.Rnd * 13) + 1
'Card's value
If c = 11 Then
c = "J"
ElseIf c = 12 Then
c = "Q"
ElseIf c = 13 Then
c = "K"
ElseIf c = 1 Then
c = "A"
Else
End If
'Card's symbol
s = Int(Math.Rnd * 4) + 1
If s = 1 Then
s = ThisWorkbook.Worksheets("Symbols").Range("B1").Value
ElseIf s = 2 Then
s = ThisWorkbook.Worksheets("Symbols").Range("B2").Value
ElseIf s = 3 Then
s = ThisWorkbook.Worksheets("Symbols").Range("B3").Value
Else
s = ThisWorkbook.Worksheets("Symbols").Range("B4").Value
End If
Next cs
End Sub
最佳答案
这比OP要求的要多,但这里还有更多需要注意的地方。结果与OP提供的图像相似,因为将手放在工作表上[B2]处的范围内。
我正在使用Fisher–Yates shuffle。
只需运行Deal()
例程:
Public Sub Deal()
Const PLAYERS = 6, CARDS = 5
Dim i&, j&, k&, deck
CreateAndShuffle deck
ReDim hands(1 To CARDS, 1 To PLAYERS)
For i = 1 To CARDS
For j = 1 To PLAYERS
k = k + 1
hands(i, j) = deck(k)
Next
Next
[b2].Resize(CARDS, PLAYERS) = hands
End Sub
Private Sub CreateAndShuffle(a)
Dim i&, j&, k&, p&, suit
ReDim a(1 To 52)
suit = Array(ChrW$(9829), ChrW$(9830), ChrW$(9827), ChrW$(9824))
Randomize
For i = 1 To 13
For j = 0 To 3
k = k + 1
p = Int((k - 1 + 1) * Rnd + 1)
If j <> k Then a(k) = a(p)
a(p) = Mid$("A234567890JQK", i, 1): If i = 10 Then a(p) = 10
a(p) = a(p) & " " & suit(j)
Next
Next
End Sub