Hi gang,
I've started making a card game, which seems is going to be quite a challenge for me. To make my question more simple, let's say we have a form with three empty images and three images with cards. How do I put those three card pics randomly into empty ones with just a single click of a button? I'd appreciate any pointer, that could get me on track...

Dani AI

Generated

A simple, robust way to do this is to treat the three card images as a small collection, shuffle their order once, then assign them to the three empty picture controls. That avoids accidental duplicates and the common pitfall of re-creating the random seed on every click. was right to point toward randomization; below is a concise, reliable pattern that complements the thread and gives a clean replacement for ad-hoc approaches.

' form-level fields
Private rnd As New Random()
Private cards As Image() = {cardImg1, cardImg2, cardImg3}
Private targets As PictureBox() = {pbEmpty1, pbEmpty2, pbEmpty3}

Private Sub btnDeal_Click(sender As Object, e As EventArgs) Handles btnDeal.Click
    Dim n As Integer = cards.Length
    Dim idx(n - 1) As Integer
    For i As Integer = 0 To n - 1
        idx(i) = i
    Next

    ' Fisher-Yates shuffle
    For i As Integer = n - 1 To 1 Step -1
        Dim j As Integer = rnd.Next(i + 1)
        Dim tmp As Integer = idx(i)
        idx(i) = idx(j)
        idx(j) = tmp
    Next

    For i As Integer = 0 To n - 1
        targets(i).Image = cards(idx(i))
    Next
End Sub

Notes: create and reuse Random at form scope so successive clicks are not identical; load card images once (not on each click) to avoid file I/O and disposal issues; set PictureBox.SizeMode (Zoom/Stretch) if images appear cropped. For algorithm background see the Fisher–Yates shuffle and the .NET Random docs (Fisher–Yates shuffle, System.Random). This approach is easy to scale if you later expand to a full deck.

Recommended Answers

All 2 Replies

Try this link to a previous discussion. It might put you on the correct path to a solution.

http://www.daniweb.com/forums/thread134994.html

or to read up more on randomize and get some sample code go to -


This link discuss the actual card game with sample code...

Those links are not working (at least for me).. But anyway, I figured out a way to do what I need by myself. While it's undoubtedly not the most optimal method, it does the trick. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.