如何使用循环随机 select 绘制多个形状?
How to randomly select a shape to draw several using a loop?
当我想以随机方式显示我的对象时卡住了。
假设我有这个面板,假设矩形和椭圆是对象
我需要做什么才能让它们以这种形式显示。
我需要使用 Random n = new Random
吗?或者还有其他方法。
这是我的一个尝试,但我不知道如何集成随机函数来显示它们。
do
{
dr.DrawEllipse(Bpen, i + 30, 25, i + 30, 25);
i += 50;
}
while (i <= this.Width);
您可以使用一系列可用项目,例如 { squareType, circleType }
。
然后在该数组上随机 0..Length
到 select 并绘制相关形状。
例如,您可以使用此枚举:
public enum Shapes
{
Circle,
Square
}
并声明这些成员:
static readonly Array ShapesValues = Enum.GetValues(typeof(Shapes));
static readonly int ShapesCount = ShapesValues.Length;
而这个 RNG:
static readonly Random random = new Random();
所以你可以这样写:
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 );
通过这样做,您可以以干净且可维护的方式定义和管理任何必要的形状。
如果形状可以有不同的大小,请考虑使用中间变量来处理。
你也可以这样写让代码更安全:
static readonly ReadOnlyCollection<Shapes> ShapesValues
= Array.AsReadOnly(Enum.GetValues(typeof(Shapes)).Cast<Shapes>().ToArray());
static readonly int ShapesCount = ShapesValues.Count;
并且:
switch ( ShapesValues[random.Next(ShapesCount)] )
当我想以随机方式显示我的对象时卡住了。 假设我有这个面板,假设矩形和椭圆是对象
我需要做什么才能让它们以这种形式显示。
我需要使用 Random n = new Random
吗?或者还有其他方法。
这是我的一个尝试,但我不知道如何集成随机函数来显示它们。
do
{
dr.DrawEllipse(Bpen, i + 30, 25, i + 30, 25);
i += 50;
}
while (i <= this.Width);
您可以使用一系列可用项目,例如 { squareType, circleType }
。
然后在该数组上随机 0..Length
到 select 并绘制相关形状。
例如,您可以使用此枚举:
public enum Shapes
{
Circle,
Square
}
并声明这些成员:
static readonly Array ShapesValues = Enum.GetValues(typeof(Shapes));
static readonly int ShapesCount = ShapesValues.Length;
而这个 RNG:
static readonly Random random = new Random();
所以你可以这样写:
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 );
通过这样做,您可以以干净且可维护的方式定义和管理任何必要的形状。
如果形状可以有不同的大小,请考虑使用中间变量来处理。
你也可以这样写让代码更安全:
static readonly ReadOnlyCollection<Shapes> ShapesValues
= Array.AsReadOnly(Enum.GetValues(typeof(Shapes)).Cast<Shapes>().ToArray());
static readonly int ShapesCount = ShapesValues.Count;
并且:
switch ( ShapesValues[random.Next(ShapesCount)] )