I am making a memory game that compares two cards against themselves to see if they are the same. I do this by comparing the tag of the image in the picture box. All of the images have unique tags, however, when compared in an if statement, it passes over and treats it as false. This is the code for when the card is clicked on.
private void pictureBox1_Click(object sender, EventArgs e)
{
Image temp = Boxes[0];
pictureBox1.Tag = Boxes[0].Tag;
pictureBox1.Image = temp;
if (openBox1 == null)
{
openBox1 = pictureBox1;
}
else if (openBox1 != null && openBox2 == null)
{
openBox2 = pictureBox1;
}
if (openBox1 != null && openBox2 != null)
{
if (openBox1.Image.Tag == openBox2.Image.Tag)
{
openBox1 = null;
openBox2 = null;
}
else
{
openBox1.Image = Properties.Resources.card;
openBox2.Image = Properties.Resources.card;
openBox1 = null;
openBox2 = null;
}
}
}
This is how I am tagging the images:
List<int> Repeats = new List<int>();
int random;
bool test;
foreach (Image n in Album)//checks to see if image has been added
{
test = true;
while (test)
{
random = randy.Next(0, 16);
if (!Repeats.Contains(random))
{
Boxes[random] = n;
Boxes[random].Tag = n.Width * n.Height;
Repeats.Add(random);
test = false;
}
}
}
I have stepped into the program for myself, and monitored the variables. When I click two of the same card it just ignores that they are the same value.
The code doesn't works because boxing. int
is a value type, to cast it to object
(the type accepted by Tag
) .net wraps the value type with a new object
('boxes' it). As object
is a reference type and each tag has a different object the equality is not satisfied.
To make it work you must unbox the value, via a type cast or using the operator as
:
//Unbox values before comparing
if (openBox1.Image.Tag as integer == openBox2.Image.Tag as integer)
//...