Question:

Visual Basic 2005 - how to code a shuffle?

by  |  earlier

0 LIKES UnLike

I am currently trying to create a memory card game of 10 cards. The carrds are C21 C22 C61 C62 C71 C72 CA1 CA2 CK1 CK2 where the 1st number is the card image and the 2nd number is the pair number, and pairs of '2' '6' '7' 'Ace' 'King'. I am trying to code the cards so that they are shuffled then placed face down in the format as such....

card1 card2

card3 card4

card5 card6.........etc

Any help with this would be much appreciated. Thank You

 Tags:

   Report

1 ANSWERS


  1. I typically use a double-substitution method for shuffling cards ... the code below can be pasted into a form code module with a single button to see how it works.  I've tested it and it seems to accomplish what you're looking for.

    It should be easy enough to modify as you need.

    Good luck!

    Public Class Form1

        Dim Cards(9) As String

        Private Sub CreateCards()

            Cards(0) = "C21"

            Cards(1) = "C22"

            Cards(2) = "C61"

            Cards(3) = "C62"

            Cards(4) = "C71"

            Cards(5) = "C72"

            Cards(6) = "CA1"

            Cards(7) = "CA2"

            Cards(8) = "CK1"

            Cards(9) = "CK2"

        End Sub

        Private Sub ShuffleCards()

            Dim i, x, y As Integer

            Dim temp1, temp2 As String

            Randomize()

            For i = 0 To 4999

                x = Int(Rnd() * 10)

                y = Int(Rnd() * 10)

                temp1 = Cards(x)

                temp2 = Cards(y)

                Cards(x) = temp2

                Cards(y) = temp1

            Next i

        End Sub

        Private Sub Button1_Click(ByVal sender As System.Object, _

            ByVal e As System.EventArgs) _

            Handles Button1.Click

            CreateCards()

            ShuffleCards()

            ' test shuffle

            Dim iLoop As Integer

            Dim strCards As String = ""

            For iLoop = 0 To 9

                strCards = strCards & Cards(iLoop) & ", "

            Next

            MsgBox(strCards, , "Info")

        End Sub

    End Class

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.