我写了一些代码来生成随机点并生成随机矩形。所有调试似乎都可以,但代码只绘制了 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 关注
- 98 浏览
添加回答
举报
0/150
提交
取消