line
functionThe line
function draws a line from a point to a second point. It takes four arguments--the x & y coordinates of the first and second points. Remember that the top left corner of the screen is (0,0). The following line of code will draw a line from the center of the screen (320,240) to the center of the top of the screen (320,0), if the graphics window is set to 640 by 480
line (320,0,320,240);
We could make a pattern of lines with the following code:
#include "winbgim.h"
void DrawLines ();
int main ()
{
initwindow(640,480);
DrawLines();
getch();
closegraph();
return 0;
}
void DrawLines ()
{
setcolor(MAGENTA);
line (320,0,320,240);
line (320,30,350,240);
line (320,60,380,240);
line (320,90,410,240);
line (320,120,440,240);
line (320,150,470,240);
line (320,180,500,240);
line (320,210,530,240);
line (320,240,560,240);
}
kbhit()
The "keyboard hit" function checks to see if a key has been pressed. If no key has been pressed it returns false. If a key has been pressed, it returns true. It is usually used with the !
(not) operator. Example:
#include "winbgim.h"
void main (void)
{
initwindow(640,480);
int nNum = 0;
while(!kbhit()) //keep loop going until a key is pressed
{
line(0,nNum,640, 480 - nNum);
nNum++;
delay(50);
}
getch();
closegraph();
return 0;
}
rand()
The random function generates a "pseudo-random" number between 0 and RAND_MAX (some huge number). rand()
is generally used with modulus to get a random number within a certain range. For example:
#include <iostream.h>
#include <stdlib.h> //include the random functions
#include <time.h> //include the library of time functions
int main ()
{
srand(time(NULL)); //seed the random number generator
cout<<rand()%100<<endl; //displays a number between 0 and 99
system("PAUSE");
return 0;
}
You can use random numbers to have your design at appear at different random places on the screen.