我寫了一些代碼來生成隨機點并生成隨機矩形。所有調試似乎都可以,但代碼只繪制了 1 個矩形。查看我的代碼并告訴我出了什么問題。private void btnRun_Click(object sender, EventArgs e){ Graphics g = pnlWarZone.CreateGraphics(); if (int.Parse(txtGenerationCount.Text) > 0) { RectangleF[] rects = new RectangleF[int.Parse(txtGenerationCount.Text)]; for (int i = 0; i < int.Parse(txtGenerationCount.Text); i++) { rects[i] = new RectangleF(GeneratePoint(),new SizeF(4,4)); } g.FillRectangles(new SolidBrush(Color.Blue), rects); }}更新:這是生成點的方法private Point GeneratePoint(){ Random r = new Random(); //return random.NextDouble() * (maxValue - minValue) + minValue; var x =r.Next(_rectangles[0].X, _rectangles[0].Width); var y =r.Next(_rectangles[0].Y, _rectangles[0].Height); return new Point(x,y);}
1 回答
小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
您的代碼很可能看起來像這樣:
private Point GeneratePoint() {
Random rnd = new Random();
int x = rnd.Next(0, pnlWarZone.ClientSize.Width);
int y = rnd.Next(0, pnlWarZone.ClientSize.Height);
return new Point(x, y);
}
您要做的只是生成一個新的 Random 對象一次,然后始終重新使用該變量:
Random rnd = new Random();
private Point GeneratePoint() {
int x = rnd.Next(0, pnlWarZone.ClientSize.Width);
int y = rnd.Next(0, pnlWarZone.ClientSize.Height);
return new Point(x, y);
}
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報
0/150
提交
取消
