Reputation: 47
I just started learning game programming at school and we are using c#(and xna. So now we need to make a tetris game. What I want to do is using random number to create the colors so Im wondering wether this is correct or not:
public Block RandomColor()
{
int r = Random.Next(6);
if (r == 0)
{
return Color.Red;
}
else if (r == 1)
{
return Color.Orange;
}
else if (r == 2)
{
return Color.Yellow;
}
else if (r == 3)
{
return Color.Green;
}
else if (r==4)
{
return Color.Blue;
}
else if (r==5)
{
return Color.Indigo;
}
else if (r==6)
{
return Color.Purple;
}
I am pretty uncertain about this because
1) visual studio doesnt give errors on this one
2) But everytime I want to write Color 2 things pop up: RandomColor and ConsoleColor. Do I need randomColor then instead of Color?
I tested wether I could screw with the code after Color. and the answer was yes. So does it mean the colors wont change when I run the code?
First time on stackoverflow so not sure Im doing this right:)
Upvotes: 2
Views: 444
Reputation: 39122
Here's a different method to get a random color from a set of colors:
private Random rnd = new Random();
private Color[] Colors = new Color[] { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Purple };
public Color RandomColor()
{
return Colors[rnd.Next(Colors.Length)];
}
Upvotes: 2
Reputation: 61339
A few things about your code:
You state a return type of Block
but actually return Color
objects. Pretty surprising the compiler isn't complaining about that.
Because you are returning Color
objects (once you get (1) fixed) you are pretty good to go. ConsoleColor
is not used in XNA (not even sure what "randomColor" is).
You can't just invoke Random.Next
. You need to create a Random
instance (not in this method, especially if it will be called in a loop) and then invoke Next
on that.
Invoking Next
returns a number in [0,x) (where x is the number passed). In case you aren't familiar with that notation, x is exclusive so you will never get x itself. Your if statements should range from 0 to 5, not 1 to 6.
Otherwise, assuming you are actually using the return value in SpriteBatch.Draw
you are totally in the ballpark. Not having errors is a good thing :). Your second and third questions don't make a ton of sense yet.
Upvotes: 1