Credit: Tyler Conklin
This is a bonus program! It's meant to be challenging.
Write a program that animates two different balls bouncing around the canvas. If a ball hits off of a wall, it should bounce back in the opposite direction. The two balls can also bounce off of each other. An example is shown in the below gif.
In this run, the width of each ball is 50 pixels, but feel free to use whichever numbers you would like. Note that when creating the balls it is important to give the balls different, random velocities and starting X,Y positions.
When computer scientists tackle a large problem, it helps to break it down into smaller steps. One way to break this problem down would be:
canvas.get_left_x(ball)
(same thing goes for the Y position).canvas.find_overlapping(obj)
which returns a list of the objects (if any) that are colliding with obj
. You can check what it is using ==
and !=
, for instance:# Get the coordinates of the ball
ball_coords = canvas.coords(ball)
# Find all objects overlapping with these coordinates
colliders = canvas.find_overlapping(ball_coords[0], ball_coords[1],
ball_coords[2], ball_coords[3])
# Loop over each element in the colliders list and see if it is something
# other than this ball itself (an object always "overlaps with itself")
for collider in colliders:
if collider != ball:
...
It may also help to write functions that return more than one thing.
Bonus: try using lists to animate any number of balls around the screen! Try also to play with what happens when the balls collide with each other to make the bounce physics more natural.