在C#中的随机位置绘制形状

时间:2016-08-27 08:09:00

标签: c#

我想在C#用户控件绘制方法中在面板上绘制四个形状(矩形,正方形,三角形,圆形)。我尝试了下面的代码,但它将在相同的位置(x,y)绘制形状。我声明了四个随机变量,但它没有用。我需要分别在不同的位置绘制这些形状。有没有人可以帮助我?

这是我的代码:

int recX;
int recY;
int squX;
int squY;
int circleX;
int circleY;
int triX;
int triY;
public int shapeType { get; set; }


public GameArea()
{
    InitializeComponent();
    food = new Food(randFood);
    Random randRectangle = new Random();
    recX = randRectangle.Next(1, 35) * 10;
    recY = randRectangle.Next(1, 35) * 10;

    Random randSquare = new Random();
    squX = randSquare.Next(1, 35) * 10;
    squY = randSquare.Next(1, 35) * 10;

    Random randCircle = new Random();
    circleX = randCircle.Next(1, 35) * 10;
    circleY = randCircle.Next(1, 35) * 10;

    Random randTriangle = new Random();
    triX = randTriangle.Next(1, 35) * 10;
    triY = randTriangle.Next(1, 35) * 10;
}
private void GameArea_Paint(object sender, PaintEventArgs e)
{
    paper = e.Graphics;
    if (shapeType != 0)
     {

        if(shapeType == Convert.ToInt32(Enums.ShapeTypes.Rectangle))
        {
            food.drawFood(paper, shapeType, recX,recY);
            food.drawSquare(paper, squX, squY);
            food.drawCircle(paper, circleX, circleY);

        }
}

1 个答案:

答案 0 :(得分:1)

反复使用相同的随机,否则您将使用相同的种子。

示例:

Random rndLocGen = new Random();
recX = rndLocGen.Next(1, 35) * 10;
recY = rndLocGen.Next(1, 35) * 10;
cirX = rndLocGen.Next(1, 35) * 10;
cirY = rndLocGen.Next(1, 35) * 10;