I want to create a card trick game using C#. I've designed Picture Boxes on the form to be the cards (backside). I also created a Click method for each of the pictures that creates a random number between 0, 51 and use the number to set an image from an ImageList.
Random random = new Random();
int i = random.Next(0, 51);
pictureBox1.Image = imageList1.Images[i];
My problem is that sometimes I get the same numbers (example: two Jacks of Spades), how can I prevent that?! (I mean if, for example, I got (5), I may get another (5))
Store the numbers you have already selected in a HashSet<int>
and continue selecting until the current nunber is not in the HashSet
:
// private HashSet<int> seen = new HashSet<int>();
// private Random random = new Random();
if (seen.Count == imageList1.Images.Count)
{
// no cards left...
}
int card = random.Next(0, imageList1.Images.Count);
while (!seen.Add(card))
{
card = random.Next(0, imageList1.Images.Count);
}
pictureBox1.Image = imageList1.Images[card];
Or, If you need to select many numbers, you can fill an array with the sequential numbers and swap the number in each index with the number from another random index. Then take the top N needed items from the randomized array.
If you want to make sure you have no repeat images, you can have a list of remaining cards, and remove the shown card each time.
Random random = new Random();
List<int> remainingCards = new List<int>();
public void SetUp()
{
for(int i = 0; i < 52; i++)
remainingCards.Add(i);
}
public void SetRandomImage()
{
int i = random.Next(0, remainingCards.Count);
pictureBox1.Image = imageList1.Images[remainingCards[i]];
remainingCards.RemoveAt(i);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With