How to use graphics.h functions to implement a bouncing ball using c?

2.3k views Asked by At

i'm trying to do a simple bouncing ball code ,my code below doesn't bounce the ball,it just makes it move when the enter button is used, what can I do to make the ball bounce by it self when the program is run?

#include<alloc.h>
#include<graphics.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>

void main()
{
int d=DETECT,m;
initgraph(&d,&m,"H:\\tc\\bgi");
int l=getmaxx()/2,t=0;
int x=1,y=1;
int xstep=1,ystep=1;
while(!kbhit())
{
cleardevice();
 circle(l,t,18);
  delay(5);
circle(l,t,18);

  if(l>=getmaxx()||l<=0)
  {
x*=-1;
xstep=x*(random(4)+1);
ystep=y*(random(3)+1);

  if (l<=0)
   t=0;
 else
  l=getmaxx();
   }
   if(t>=getmaxy()||t<=0)
   {
 y*=-1;
 ystep=(y*random(4)+1);
 xstep=(x*random(3)+1);
   if(t<=0)
 t=0;
   else
 t=getmaxy();
  }
l+=x+xstep;
t+=y+ystep ;
getch();

}
closegraph();

}

1

There are 1 answers

0
Praveen Vinny On

I will recommend you to make a few changes at the earliest.

  • Don't use getch() in the while loop.
  • Try increasing and decreasing the values of the parameters of the delay() function.
  • Try ellipse instead of circle.