Reputation: 25
I got stuck when i want to display my objects in a random way . Let's say i got this pannel and let's say the rectangle and ellipse are the objects
What do i need to do so i can have them display in this form.
Do i need to use Random n = new Random
? or there is another way.
This is one of my attemps but i dont know how to integrate the random function to display them.
do
{
dr.DrawEllipse(Bpen, i + 30, 25, i + 30, 25);
i += 50;
}
while (i <= this.Width);
Upvotes: 2
Views: 330
Reputation:
You can use an array of available items like { squareType, circleType }
.
And then random 0..Length
on that array to select and draw the relevant shape.
For example you can use this enum:
public enum Shapes
{
Circle,
Square
}
And declare these members:
static readonly Array ShapesValues = Enum.GetValues(typeof(Shapes));
static readonly int ShapesCount = ShapesValues.Length;
And this RNG:
static readonly Random random = new Random();
So you can write:
int posX = 0;
do
{
switch ( ShapesValues.GetValue(random.Next(ShapesCount)) )
{
case Shapes.Circle:
// ...
break;
case Shapes.Square:
// ...
break;
default:
throw new NotImplementedException();
}
posX += 50;
}
while ( posX <= Width );
By doing this, you can define and manage any necessary shape in a clean and maintainable way.
If the shapes can have different sizes, consider handling this with intermediate variables.
You could also write this to make the code more secure:
static readonly ReadOnlyCollection<Shapes> ShapesValues
= Array.AsReadOnly(Enum.GetValues(typeof(Shapes)).Cast<Shapes>().ToArray());
static readonly int ShapesCount = ShapesValues.Count;
And:
switch ( ShapesValues[random.Next(ShapesCount)] )
Upvotes: 2