# Computer graphics program to implement a bouncing ball

0
0

## Computer graphics program in Python and C++

### Python

from graphics import *
import time, random

def bounceInBox(shape, dx, dy, xLow, xHigh, yLow, yHigh):
delay = .005
for i in range(600):
shape.move(dx, dy)
center = shape.getCenter()
x = center.getX()
y = center.getY()
if x < xLow:
dx = -dx
elif x > xHigh:
dx = -dx
if y < yLow:
dy = -dy
elif y > yHigh:
dy = -dy
time.sleep(delay)

def getRandomPoint(xLow, xHigh, yLow, yHigh):
'''Return a random Point with coordinates in the range specified.'''
x = random.randrange(xLow, xHigh+1)
y = random.randrange(yLow, yHigh+1)
return Point(x, y)

'''return a red disk that is drawn in win with given center and radius.'''
disk.setOutline("black")
disk.setFill("green")
disk.draw(win)
return disk

def bounceBall(dx, dy):
'''Make a ball bounce around the screen, initially moving by (dx, dy)
at each jump.'''

winWidth = 290
winHeight = 290
win = GraphWin('Ball Bounce', winWidth, winHeight)
win.setCoords(0,0,winWidth, winHeight)

xLow = radius # center is separated from the wall by the radius at a bounce

center = getRandomPoint(xLow, xHigh, yLow, yHigh)
bounceInBox(ball, dx, dy, xLow, xHigh, yLow, yHigh)
win.close()
bounceBall(1, 5)

### C++

#include<bits/stdc++.h>
#include<graphics.h>
#include<conio.h>
using namespace std;

void ball(int x, int y){
circle(x, y, 50);
floodfill(x, y, WHITE);
}

void bounce(){
int x = getwindowwidth()  / 2;
int y = 10;
double u = 0;
int a = 10;
double t = 0;
while(1){

t = 0;
a = 10;
// y = 10;
cout << "dircetion changec \n";
while(y <= getwindowheight() - 150 ){
delay(10);
cleardevice();
ball(x, y);
t += 0.01;
u += a * t;
y += round(u * t);
cout << y <<"\n";
if(y < 0){
break;
}
}
a *= -1;
t = 0;
u = 0;
cout << "dircetion changec \n";
while(y >= 100){
delay(10);
cleardevice();
ball(x, y);
t += 0.01;
u += a * t;
y += round(u * t);
cout << y <<"\n";
if(y < 0){
break;
}
}
y = 10;

}
}

int main(){
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

bounce();
getch();
closegraph();

return 0;
}
SHARE
Hey! I am one of the 100,000 engineering students in India, with a step forward to support and provide resources to 99,999 other students.