如何使用随机函数让矩形在不同的位置生成?

时间:2019-02-13 17:36:07

标签: c#

我希望我的绿色矩形foodBody随机产生。我知道我应该为此使用随机函数,但是我遇到了问题。当我运行它时,什么也没发生。你能帮我吗?

这是我当前的代码:

`使用系统; 使用System.Windows.Forms; 使用System.Drawing;

命名空间WindowsFormsApp1 {     公共局部类Form1:表单     {         int sx = 100,sy = 100,fx = 200,fy = 200;

    public Form1()
    {
        InitializeComponent();
    }

    private Rectangle foodBody;

    Random random = new Random();

    private Rectangle snakeBody;

    private void Form1_Load(object sender, EventArgs e)
    { 
        snakeBody = new Rectangle(sx, sy, 15, 15);
        foodBody = new Rectangle(Random.Next(this.Width), random.Next (this.Height),15,15);  //Breakpoint
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.FillRectangle((Brushes.Red),snakeBody);
        e.Graphics.FillRectangle((Brushes.Green),foodBody);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.Right)
        {
            snakeBody.X += 5;
        }

        if (e.KeyData == Keys.Left)
        {
           snakeBody.X -= 5;
        }
        if (e.KeyData == Keys.Up)
        {
            snakeBody.Y -= 5;
        }
        if (e.KeyData == Keys.Down)
        {
            snakeBody.Y += 5;
        }

        this.Refresh();
    }    

    private void moveTimer_Tick(object sender, EventArgs e)
    {
        Invalidate();
    }
}

}

`

1 个答案:

答案 0 :(得分:0)

创建一个Random对象(在您的Form1类的顶部):

Random random = new Random();

使用以下形式的随机位置创建一个新的Rectangle对象:

foodBody = new Rectangle(random.Next(this.Width), random.Next(this.Height), 15, 15);