Thursday, April 21, 2011

Draw different shape of polygon randomly

My program draw 10 polygon triangles in random sizes (width and height). The coordinate (points) of the polygon were generated using Random generator = new Random(). Since the points of the triangle and the width and height were randomly generated, how can I control the number of sizes drawn? e.g. there are 10 polygon in total, but I wanted to limit the number of different sizes e.g. only 2 or 4 different sizes.

for(int i = 0; i < 10; i++) {
   double xWidth = generator.nextDouble() * 50.0 + 20.0; // range width of triangle
   double yHeight = generator.nextDouble() * 50.0 + 20.0; // range height of triangle

   xCoord[0] = generator.nextInt(300);
   yCoord[0] = generator.nextInt(300);

   xCoord[1] = (int) (xCoord[0] - xWidth);
   xCoord[2] = (int) (xCoord[1] + (xWidth/2));         

   yCoord[1] = yCoord[0];
   yCoord[2] = (int) (yCoord[1] - yHeight);         

   triangles.add( new Polygon(xCoord,yCoord, 3));
}
From stackoverflow
  • Why not just randomly generate 4 shapes and then run a different loop to pick randomly from those four shapes.

    Jessy : sounds do difficult :-(
  • This code only generates the tringles, there has to be a .draw() somewhere - you just wrap that in some sort of code that picks one to four triangles - which again will need some sort of randomizer if you want those selected randomly.

  • int limit = generator.nextInt(4)+1;    // [1,4]
    for(int i = 0; i < limit; i++) {
     //...
    }
    

0 comments:

Post a Comment