Credit: Problem written by Chris.
Handouts: Graphics Reference
Make a ball that bounces as if under the influence of gravity. To do this, adapt code for a regular bouncing ball, but each frame have the y velocity increase downward by a small amount to simulate the pull of gravity. Additionally, each time the ball bounces off the bottom, decrease the y velocity by a certain percentage.
(Note: the gray path in the image above is just an illustration - the working program will just have a black ball bouncing on the screen)
"""File: gravity_ball.py-------------------A ball bounces as if due to gravity. Specifically, each frame the y velocity increasesdownward to simulate gravity, and each time it bounces it loses some of its y velocityto simulate damping."""import timefrom graphics import CanvasBALL_DIAMETER = 20ANIMATION_DELAY_SECONDS = 0.02# The amount to add each frame to the y velocity to simulate the pull of gravityGRAVITY = 0.5# The amount by which to multiply the y velocity each time we bounce (simulates losing energy)DAMPING = 0.7def main():canvas = Canvas()canvas.set_canvas_title("Gravity Ball")# draw a ball on the top left cornerball = canvas.create_oval(0, 0, BALL_DIAMETER, BALL_DIAMETER)canvas.set_color(ball, "black")# variables for velocityvx = 3vy = 0while True:# update vyvy += GRAVITY# should the ball bounce?if (canvas.get_top_y(ball) > (canvas.get_canvas_height() - canvas.get_height(ball))) and vy > 0:# Dampen the velocity and invert the velocityvy = vy * -DAMPINGcanvas.move(ball, vx, vy)time.sleep(ANIMATION_DELAY_SECONDS)canvas.update()canvas.mainloop()if __name__ == "__main__":main()