dimanche 28 mai 2017

C# - Random color generator not working

So I'm having a bit of a problem with a simple random color generator class that despite all effort will not stop generating the same set of colors everytime the application starts.

This is an issue that only happens the first time it is used. However the time between the initialization of the Random object and the first generation call is user-determined. So I really have no idea what is causing it

Here's my code:

        /// <summary>
    /// Random number generator
    /// </summary>
    static Random Random;

    public static void Initialize()
    {
        //Intializes the random number generator
        Random = new Random();
    }

    /// <summary>
    /// Generates a random color
    /// </summary>
    /// <returns></returns>
    public static Color GenerateOne()
    {
        while (true)
        {
            Color clr = Color.FromArgb(RandByte(), RandByte(), RandByte());

            float sat = clr.GetSaturation();

            if (sat > 0.8 || sat < 0.2)
            {
                continue;
            }

            float brgt = clr.GetBrightness();
            if (brgt < 0.2)
            {
                continue;
            }

            return clr;
        }
    }

    /// <summary>
    /// Generates a set of random colors where the colors differ from each other
    /// </summary>
    /// <param name="count">The amount of colors to generate</param>
    /// <returns></returns>
    public static Color[] GenerateMany(int count)
    {
        Color[] _ = new Color[count];

        for (int i = 0; i < count; i++)
        {
            while (true)
            {
                Color clr = GenerateOne();

                float hue = clr.GetHue();
                foreach (Color o in _)
                {
                    float localHue = o.GetHue();

                    if (hue > localHue - 10 && hue < localHue + 10)
                    {
                        continue;
                    }
                }

                _[i] = clr;
                break;
            }
        }

        return _;

    }

    /// <summary>
    /// Returns a random number between 0 and 255
    /// </summary>
    /// <returns></returns>
    static int RandByte()
    {
        return Random.Next(0x100);
    }
}

Screenshot of repeating color scheme if needed

Thanks in advance :)




Aucun commentaire:

Enregistrer un commentaire