Draw a Chess Board using Graphics Programming in C
Last Updated :
21 Jun, 2020
Prerequisite: graphics.h, How to include graphics.h in CodeBlocks?
In Computer Graphics, we use graphics.h which provide direct functions to draw different coordinate shapes(like circle, rectangle etc). By using these functions we can draw different objects like car, hut, trees etc. In this program, the task is to draw a Chess Board using the functions in graphics.
To run the program we have the include the below header file:
#include <graphic.h>
Approach: We will create a Chess Board with the help below functions:
- rectangle(left, top, right, bottom): A function from graphics.h header file which is used to draw a rectangle. Coordinates of the left top and right bottom corners are required to draw the rectangle. left specifies the X-coordinate of the top left corner, top specifies the Y-coordinate of the top left corner, right specifies the X-coordinate of the right bottom corner, bottom specifies the Y-coordinate of the right bottom corner.
- delay(): This function is present in library “dos.h” is used for holding the program output for a small period of time since processing is very fast so use it to see the result.
- setcolor(): A function from graphics.h header file which sets the color of the pointer (cursor). There are some predefined colors in computer graphics. Here n is the color number.
- setfillstyle(): A function from graphics.h header file which sets the current fill pattern and fill color.
- floodfill(): A function from graphics.h header file which is used to fill an enclosed area.
Below is the implementation of to draw Chess Board using graphics in C:
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdio.h>
void main()
{
int gr = DETECT, gm;
int r, c, x = 30, y = 30, black = 0;
initgraph(&gr, &gm, "C:\\TURBOC3\\BGI" );
for (r = 0; r < 8; r++) {
for (c = 1; c <= 8; c++) {
if (black == 0) {
setcolor(WHITE);
setfillstyle(SOLID_FILL, BLACK);
rectangle(x, y, x + 30, y + 30);
floodfill(x + 1, y + 1, WHITE);
black = 1;
}
else {
setcolor(WHITE);
setfillstyle(SOLID_FILL, WHITE);
rectangle(x, y, x + 30, y + 30);
floodfill(x + 1, y + 1, WHITE);
black = 0;
}
x = x + 30;
delay(30);
}
if (black == 0)
black = 1;
else
black = 0;
delay(30);
x = 30;
y = 30 + y;
}
getch();
closegraph();
}
|
Output:
Below is the output of the above program:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...