Search code examples
randomcolorsc++-clibackcolor

RNG giving same number after second interation in loop


So, I'm trying to make a game that requires randomly colored pictureboxes. I've been trying to make the random color generator, but I'm running into an issue that I can't explain.

When this code runs (inside of Form1_Load event):

for(int i=0; i<6, i++)
{
    DateTime moment = DateTime::Now;
    Random^RNG=gcnew Random(moment.Millisecond);
    color[i]=RNG->Next(16);

    if(color[i]<=9)
    {
        colorStr[i]=color[i].ToString();
    }
    else if(color[i]==10)
    {
        colorStr[i]="A";
    }
    else if(color[i]==11)
    {
        colorStr[i]="B";
    }
    else if(color[i]==12)
    {
        colorStr[i]="C";
    }
    else if(color[i]==13)
    {
        colorStr[i]="D";
    }
    else if(color[i]==14)
    {
        colorStr[i]="E";
    }
    else if(color[i]==15)
    {
        colorStr[i]="F";
    }
    FullColor+=colorStr[i]; //FullColor was initialized with a value of "#";
}

this->textBox1->Text=FullColor;
this->Player->BackColor = System::Drawing::ColorTranslator::FromHTML(FullColor);

The textbox displays either all the same number (i.e. #000000), or the first number will be unique, but the other five will be equal to each other (i.e. #A22222).


Solution

  • Random generator should not be re-created every time. Try to do it once, before the loop:

    Random^RNG=gcnew Random(moment.Millisecond);
    for(int i=0; i<6, i++)
    {
        ....
    

    (In your case, it seems that the moment.Millisecond is the same for sequential calls. But even if it would be different, the generator is not supposed to be re-created.)


    Instead of the loop, you may consider the following code:

    Random^ RNG = gcnew Random(); // somewhere at the beginning
    ....
    int color = RNG->Next(0x1000000);
    String^ colorStr = color.ToString("X6");