Random Numbers


Random numbers are often used in programming. They are actually pseudo-random numbers and follow a pre-determined
starting sequence at a "seed" value which comes from the clock and is always different.


CREATE A RANDOM OBJECT CALLED "rnd"

  
      //
      // create the random object that we will use
      // placing this at the class level makes it available to 
      // all methods to generate random numbers  
      //
      // for graphics, we will use it for size, location and color  
      
      // create (instantiate) a random object called "rnd" from the "Random" class
      
      Random rnd = new Random();     
      

USE THE "rnd" OBJECT

      
// COLORS:
// RGB(red green blue)  each color has a value from 0-255 : stored in 8 bits

r = rnd.Next(0, 256); // generate an int number from 0 thru 255
g = ... 
b = ...
      
// a is for opacity: 0 is transparent, and 255 is opaque

a = ...

// LOCATION: (x,y)
//  note using Width and Height properties of panel to adapt to different sizes 

x = rnd.Next(0, panDraw.Width); 


y = rnd.Next(0, panDraw.Height);   

SIZE

 
// SIZE:    
// size of shape  - up to you
    
w = rnd.Next(10, 61);

h = ...

CREATE BRUSH

 
//COLOR:
// create a colored brush using the random values generated above
br = new SolidBrush( Color.FromArgb( a, r, g, b ) );      

   // OR

br = new SolidBrush( Color.FromArgb( rnd.Next(0,256), 
                                     rnd.Next(0,256), 
                                     rnd.Next(0,256), 
                                     rnd.Next(0,256) ) );      

DRAW THOSE SHAPES!

 
// remember we must first create a graphics 'context'
Graphics gr = panDraw.CreateGraphics();

// draw a rectangle using the random values generated above       
gr.FillRectangle( br, x, y, w, h );

  // OR

gr.FillRectangle( br, rnd.Next(0,panDraw.Width), 
                      rnd.Next(0,panDraw.Height),
                      rnd.Next(20, 60), 
                      rnd.Next(40, 80) ); // x,y,w,h

// draw an ellipse using the random values generated      
gr.FillEllipse( br, x, y, w, h );      

CLEAR THE GRAPHICS PANEL with a COLOR

 
// Clear the panel - must provide a color       
gr.Clear( Color.White );

// Clear the panel - must provide a color       
gr.Clear( Color.Red );