I'm making a Breakout Game and I want the bricks to get a random BackColor. Right now I have the bricks getting filled with all type of colors: red, green, blue, yellow, pink and all others.
What I want to do though is only get the random to randomize three colors only : blue, yellow and green.
This is what I have now:
private Random rnd = new Random();
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
bricks[x, y].BackColor = randomColor;
I've searched and tried many different things and nothing has worked! I feel like this might be simple to do but somehow can't really get to it. I thought about making a list of the 3 colors and try randomizing the list but it didn't work out!
why not map the 3 colors of your choice to numbers {0,1,2} and then make a simple switch statement?
and then just hope that the randomness of Random in C# is good enough for your game ;)
EDIT: damn it, too late :D
About the comments:
The use of
Thread.Sleep()
is just an example to test the results of a local instance of theRandom
class when used in a close loop.You will, probably, get series of the same result. Or all identical values.
Here, as a test, I'm inserting a small pause (1ms) when returning the random color, so the colors will be selected using a different seed (almost) every time. Test it without the pause.
The default implementation, using a single instance of the Random class, can yield similar results.
Test it without the
Thread.Sleep()
pause:Or, using a single instance:
A slightly different method to get different shades of
Red
,Green
andYellow
for each element:(It should probably be tweaked a little to avoid semi-gray color).
This is a random palette this method generates:
Disclaimer: I'm a newbie (to C#).
(colorArr.Length edit suggested by Corak)
Uses an array to store all the colors from which one will be picked. Next, a random element is called from the array.
You could write it as an extension to
Color
However, since you can't yet extend a class by adding static methods, meaning you have to call that using an instance of
Color
, egand
Color
is a sealed class (meaning we can't inherit from it), you might like to doWhich you can call with
Write your own method and call that instead. Generate a random number e.g 0,1,2 and using a switch return the correct colour. E.g: