I wrote some code that generate a random point and also makes random rectangles. All debug seems ok but the code just draw 1 rectangle.
See my code and tell me whats wrong.
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);
}
}
UPDATE : This is method for generate point
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);
}
Your code most likely looks something like this:
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);
}
What you want to do is only generate a new Random object once, and always re-use that variable later:
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);
}