Question

I'm designing a small game using windows forms in which there is 5 labels, each set to resemble an image of dice ( 1 - 6 ) from a specified imagelist. The game is made to be "rolled" 3 times, at the end of the roll you can select labels NOT to be rolled by changing their background color. At the end of each roll, the sum of the die faces is calculated and presented.

Now for the problem...

I know that my labels can reach the imagelist as the "rolling" function of the dice works very well. Each label is set to be run through a timer tick event that will occur 10 times in which random images are selected from the imagelist, creating the illusion of rolling dice. However, when I wish to ADD the total of the die faces at the end of the rolling cycle using the imagelist index, each index returns -1. Take note, the index of each respective die is one less than the amount of the die. Likewise, if you had a die resembling a one, it's index would be zero. I account for such by adding 1 to the index. So... although I may have a 5,5,6,4,3 - my score counter amounts to 0, rather than say 23.

Why would the imgaelist index give a value of -1 when the lowest available index is 0?

Here is my code. The actual calculation for the sum of the die faces is made in the else statement. I set m_iScore (the score counter) to zero prior to evaluating the sum because I want the sum to be representative of the faces after EACH roll.

private void timer1_Tick(object sender, EventArgs e)
        {
            Label[] labelArray = new Label[] { label1, label2, label3, label4, label5 };
            Random randnum = new Random();
            if (m_iAnimations < 10)
            {
                for (int iCount = 0; iCount < labelArray.Length; iCount++)
                {
                    if ((labelArray[iCount]).BackColor == Color.Lime)
                    {
                        (labelArray[iCount]).Image = imageList1.Images[randnum.Next(0, 6)];
                    }
                }
                m_iAnimations++;
            }
            else
            {
                timer1.Enabled = false;
                m_iAnimations = 0;
                m_iScore = 0;
                for (int iCount = 0; iCount < labelArray.Length; iCount++)
                {
                    m_iScore = m_iScore + ((labelArray[iCount]).ImageIndex + 1);
                }
                scoreval.Text = m_iScore.ToString();
            }

        }

If I don't add 1 to the image index, scoreval.Text shows -5.

Was it helpful?

Solution

Setting the Image property doesn't change the ImageIndex property -- they're more-or-less completely unrelated.

In general, UI should display program state, not hold it. Do all your computation, then push the results of that computation into the UI; don't use the UI elements as if they're variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top