mardi 24 mars 2015

How to reset or 'clean' Random

I'm using a Random in one class to decide which shape to draw, out of three possible shapes, using a switch.


After the shape is determined, I construct a shape with a bunch of random properties using a different instance of Random. Everything works fine, except that, for some reason, the number generated to decide the shape is somehow affecting the randomly generated draw position.


Deciding and creating an instance of the shape (derived from TwoDimShape, see below):



private void btnGenerateRandShapes_Click(object sender, EventArgs e) {
for (int i = 0; i < (int)numRandShapes.Value; i++) {
Random rnd = new Random();
int tmp = rnd.Next(0, 3);
switch (tmp) {
case 0:
Circle circle = new Circle(drawArea);
circle.Draw();
break;
case 1:
Triangle triangle = new Triangle(drawArea);
triangle.Draw();
break;
case 2:
Rectangle rectangle = new Rectangle(drawArea);
rectangle.Draw();
break;
}
}
}


Randomizing the shapes properties in base class:



public TwoDimShape(Graphics drawArea) {
Random rand = new Random();
this.drawArea = drawArea;
startPos = new Point(rand.Next(0, MAX_X_POS), rand.Next(0, MAX_Y_POS));
height = rand.Next(0, MAX_DIM);
width = rand.Next(0, MAX_DIM);
lineWidth = rand.Next(MIN_LINE_WIDTH, MAX_LINE_WIDTH);
outlineColor = Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255));
fillColor = Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255));
brush = new SolidBrush(fillColor);
pen = new Pen(outlineColor, lineWidth);
}


I'm drawing these shapes in a picturebox. For some reason, circles are drawn on the left third of the picturebox, triangles in the middle third, and rectangles on the right third.


If put the shape construction in a different case in the switch, it changes which third they are drawn in.


This is leading me to





Aucun commentaire:

Enregistrer un commentaire