#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function
void init_gr(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg
(errorcode
));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
}
// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function
void end_gr(void)
{
closegraph();
}
// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function
void PutPixel(int x, int y, int color)
{
putpixel(x,y,color);
}
void Line(int x1,int y1,int x2, int y2, int color)
{
int delta_x,delta_y,incx,incy;
float k;
// determine dx and dy
delta_x=x2-x1;
delta_y=y2-y1;
// determine steps by x and y axes (it will be +1 if we move in forward
// direction and -1 if we move in backward direction
if (delta_x>0) incx=1;
else if (delta_x==0) incx=0;
else incx=-1;
if (delta_y>0) incy=1;
else if (delta_y==0) incy=0;
else incy=-1;
delta_x=abs(delta_x);
delta_y=abs(delta_y);
// select greatest from deltas and use it as a main axe
if (delta_x>delta_y && delta_x!=0)
{
k=(float)delta_y/delta_x;
for (int i=0;i<delta_x;i++) PutPixel(x1+incx*i,y1+incy*floor(k*i),color);
}
else
{
k=(float)delta_x/delta_y;
for (int i=0;i<delta_y;i++) PutPixel(x1+incx*floor(k*i),y1+incy*i,color);
}
}
int main(void)
{
// initializing graphics mode
init_gr();
/* examples */
Line(0, 0, 640, 480,15);
Line(320, 0, 320, 480,10);
Line(0, 240, 640, 240,11);
Line(0, 480, 640, 0,12);
Line(320, 11, 10, 5,13);
Line(320, 11, 630, 5,13);
/* clean up */
getch();
end_gr();
return 0;
}