Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An issue in designing a Card Trick Game using C#

Tags:

c#

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))

like image 444
John Avatar asked May 19 '13 17:05

John


2 Answers

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.

like image 140
faester Avatar answered Oct 27 '22 11:10

faester


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);
} 
like image 42
Mike Precup Avatar answered Oct 27 '22 10:10

Mike Precup