Write a program in C for bouncing ball animation using graphics.h header file
In this program, we will draw a red color ball move it vertically up and down like a bouncing ball. We will use below mentioned functions in this program.
Function | Description |
---|---|
initgraph | It initializes the graphics system by loading the passed graphics driver then changing the system into graphics mode. |
getmaxx | It returns the maximum X coordinate in current graphics mode and driver. |
setcolor | It changes the current drawing colour. Default colour is white. Each color is assigned a number, like BLACK is 0 and RED is 4. Here we are using colour constants defined inside graphics.h header file. |
setfillstyle | It sets the current fill pattern and fill color. |
circle | It draws a circle with radius r and centre at (x, y). |
floodfill | It is used to fill a closed area with current fill pattern and fill color. It takes any point inside closed area and color of the boundary as input. |
cleardevice | It clears the screen, and sets current position to (0, 0). |
kbhit | It is used to determine whether a key is pressed or not. It returns a non-zero value if a key is pressed otherwise zero. |
delay | It is used to suspend execution of a program for a M milliseconds. |
closegraph | It unloads the graphics drivers and sets the screen back to text mode. |
C program for bouncing ball graphics animation
In this program, we first draw a red color ball on screen having center at (x, y) and then erases it using cleardevice function. We again draw this ball at center (x, y + 5), or (x, y – 5) depending upon whether ball is moving down or up. This will look like a bouncing ball. We will repeat above steps until user press any key on keyboard.
#include <stdio.h> #include <conio.h> #include <graphics.h> #include <dos.h> int main() { int gd = DETECT, gm; int i, x, y, flag=0; initgraph(&gd, &gm, "C:\\TC\\BGI"); /* get mid positions in x and y-axis */ x = getmaxx()/2; y = 30; while (!kbhit()) { if(y >= getmaxy()-30 || y <= 30) flag = !flag; /* draws the gray board */ setcolor(RED); setfillstyle(SOLID_FILL, RED); circle(x, y, 30); floodfill(x, y, RED); /* delay for 50 milli seconds */ delay(50); /* clears screen */ cleardevice(); if(flag){ y = y + 5; } else { y = y - 5; } } getch(); closegraph(); return 0; }
Program Output
Here is the screenshot of bouncing ball.