Sovias Sovias - 19 days ago 10
C# Question

C# How to Compare images with If statements

I'm trying to Compare 3 images for a slot machine, the problem is that I'm not getting any errors but the images don't seem to be getting compared to anything. I have the images in an image list and they are being randomly selected but when imagebox1 is cherries the bettextbox wont = Winner

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Bitmap apple = Properties.Resources.Apple;
Bitmap cherries = Properties.Resources.Cherries;
Bitmap orange = Properties.Resources.Orange;

private void spinButton_Click(object sender, EventArgs e)
{
Random rand = new Random();
int pic = rand.Next(0, images.Images.Count);
int pic2 = rand.Next(0, images.Images.Count);
int pic3 = rand.Next(0, images.Images.Count);

pictureBox1.Image = images.Images[(pic)];
pictureBox2.Image = images.Images[(pic2)];
pictureBox3.Image = images.Images[(pic3)];

if (pictureBox1.Image == cherries)
{
betTextBox.Text = "Winner";
}

Answer

I would wager that the Images array in the ImageList control is not a reference to the original object, so comparing with == is not going to work (although the images themselves are the same, the object holding the image is not the same reference).

You could instead use the array index itself for the if expression.

int cherriesIndex=1;

private void spinButton_Click(object sender, EventArgs e)
{
    Random rand = new Random();
    int pic = rand.Next(0, images.Images.Count);
    int pic2 = rand.Next(0, images.Images.Count);
    int pic3 = rand.Next(0, images.Images.Count);

    pictureBox1.Image = images.Images[(pic)];
    pictureBox2.Image = images.Images[(pic2)];
    pictureBox3.Image = images.Images[(pic3)];

    if (pic == cherriesIndex)
    {
        betTextBox.Text = "Winner";
    }` 

This assumes that the cherries is element 1 in images.Images. I mean that for illustration mostly.

Comments