Click to See Complete Forum and Search --> : How do I shuffle cards


Tony.H
January 23rd, 2000, 04:35 PM
hi guys
how do I shuffle a set of numbers randomly? ie. 1 to 52 as in a pack of cards. ie. change a sequence 1,2,3,4,5...... 52. to 4,51,35,17,1,48 etc, but be different at each shuffle. any advice or code would be welcome. Tony.H

Aaron Young
January 24th, 2000, 02:08 PM
Try something like:

private aDeck(1 to 52) as Integer

private Sub Form_Load()
Dim iCard as Integer

for iCard = 1 to 52
aDeck(iCard) = iCard
next
End Sub

private Sub Command1_Click()
Dim iCard as Integer

ShuffleDeck
List1.Clear
for iCard = 1 to 52
List1.AddItem aDeck(iCard)
next
End Sub

private Sub ShuffleDeck(optional byval iTimes as Integer = 50)
Dim iTmp as Integer
Dim iCard as Integer
Dim iRandCard as Integer

Randomize Timer
While iTimes
for iCard = 1 to 52
iRandCard = Int(Rnd * 51) + 1
iTmp = aDeck(iCard)
aDeck(iCard) = aDeck(iRandCard)
aDeck(iRandCard) = iTmp
next
iTimes = iTimes - 1
Wend
End Sub





Aaron Young
Analyst Programmer
ajyoung@pressenter.com
aarony@redwingsoftware.com


[Cimperiali: Colorized and indented to let people enjoy more]

BrewGuru99
January 24th, 2000, 05:48 PM
Ha! This is cool code!

I made a black jack card game a long time ago, and to shuffel I would generate a number 1 - 52, and if it was un-used, I'ed place it in the card array and then add it's number to a space and comma delinniated (sp?) string. If the number was already in the string, I would add 1 to the number until I came up with an unused number (looping back to 1 at > 52).

Quite in-efficent and slow. I like your way much better. :)
Reminds me of some code for encryption, using a byte array (Believe it was called s-box...)

Brewguru99

January 24th, 2000, 08:43 PM
Funny, I wrote a black jack game a few years ago that I used the same horribly inefficient shuffle method you had used. This method here is much better. I wrote that program back in my C++ days ;)

Take care,

Tony

hhh123
September 12th, 2002, 11:21 AM
Never posted here before, but I've been working on a card game recently and did the shuffle routine by using a collection.


Dim Cards As New Collection
Dim i, rndCard As Integer

For i = 1 To 52
Cards.Add i
Next

Randomize
Do While Cards.Count > 0
rndCard = Int(Rnd * Cards.Count) + 1
List1.AddItem Cards(rndCard)
Cards.Remove rndCard
Loop