ExPlOiD
ExPlOiD

Reputation: 153

How to detect and set image to only 1 picture box that is empty?

I have a GameForm with 7 pictureboxes to represent cards from a player hand. There are 2 players and 2 picture boxes in the middle. The picturebxoes in the middle is for the player to Discard his card and another is to draw cards. When the player clicks on a image the card will go to Discard Pile picture box and thus leaving the picturebox in the hand empty. How do I make it so that when a player draws a card it goes to an empty picture box ? !

I've tried using this method

if (pictureBox1.Image == null) {
        pictureBox1.ImageLocation = images[n];
        }
 ...
 ...
if (pictureBox7.Image == null) {
        pictureBox7.ImageLocation = images[n];
        }

But if I did that, then if 2 Picturebox are empty, Both will get filled with the random card drawn.. Any suggestion on how to only draw 1 card and set to only 1 empty picturebox everytime ? Thanks in advance !

Upvotes: 0

Views: 478

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

Just use else if instead of if, to make sure that once you assign the card to an available position, you don't accidentally assign it to other positions too.

if (pictureBox1.Image == null)
    pictureBox1.ImageLocation = images[n];
else if (pictureBox2.Image == null)
    pictureBox2.ImageLocation = images[n];
...
...
else if (pictureBox7.Image == null)
    pictureBox7.ImageLocation = images[n];

Alternatively, you could store the PictureBox controls in a collection like this, when your program starts:

List<PictureBox> hand = new List<PictureBox> { pictureBox1, ..., pictureBox7 };

Then when you need to find the first available position, use LINQ:

// Find the first slot in the player's hand with a null Image, if any
var availableSlot = hand.FirstOrDefault(x => x.Image == null);

// If an empty slot was found, set it to the image from the "draw" pile
if (availableSlot != null)
    availableSlot.Image = images[n];

Upvotes: 2

Related Questions