3

Possible Duplicate:
Random number generator not working the way I had planned (C#)

I am experienced in basic C# programming and am currently making a Die roller. This application can roll up to four dice. The problem that I am having is that the dice always produce the same result. I use a method where random number generator to generate a number from one to six and then the appropriate picture is selected. I repeat the method below for each image box because the user is allowed to input how many dice they want to roll. My issue is that the dice generate the same picture every single time. What am I doing wrong?

    public Image displaypic(PictureBox box)
    {
        string picchoice;
        int number;

        Image picture = box.Image;

        //Prevents Redundant Images
        Image displaying = box.Image;
        do
        {
            //picks a die to display     
            Random rand = new Random();
            number = rand.Next(1, 7);

            picchoice = number.ToString();

            //select an image from the image selection method
            picture = diepic(picture, picchoice);

        }
        while (picture == displaying);

        //return image
        return picture;
  }
Community
  • 1
  • 1
user925290
  • 33
  • 1
  • 4

1 Answers1

8

Random numbers aren't really random (they are known as pseudo-random) -- they are chosen based on a predetermined algorithm, which uses a "seed value" to choose the numbers. By default, this is DateTime.Now.Ticks

Your application is running so fast that it's using the same seed for each instance of Random. You can fix this by instantiating the Random object outside your loop:

Random rand = new Random();
do
{
    //picks a die to display     
    number = rand.Next(1, 7);

    picchoice = number.ToString();

    //select an image from the image selection method
    picture = diepic(picture, picchoice);

}
while (picture == displaying);

For more information about this, see the "Remarks" section here: http://msdn.microsoft.com/en-us/library/ctssatww.aspx

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121