Submit your Jupyter notebook (.ipynb file) that contains your well-commented code. Please name your file that you submit {yourStudentID}_LA2.ipynb
1. 2.
3.
You are going to write some Python code that simulates bouncing and colliding balls.
Start by defining some global variables. You will need:
a. two variables that define the width and height of the drawing window,
b. one variable that defines the number of balls in your simulation,
c. one variable that defines the ball radius,
d. and four lists that store the x,y location of each ball and the velocity of each ball, vx,vy. The x,y locations can
be assigned randomly anywhere in the drawing window, but make sure that the ball is entirely visible when it is first drawn. The velocity can be set randomly in the range -5 to 5 (pixels/timestep).
See random.uniform for generating these random values.
Next you will need at least three functions:
a. update_position(i): This function takes as input an index i and updates the location of the ball at the
corresponding position in the ball list. A ball’s location is updated as follows:
x = x + timestep * vx
y = y + timestep * vy
where timestep controls the speed of the animiation (I set my timestep to 1).
i. If the ball strikes any side of the drawing window, you should bounce the ball by negating the ball’s velocity: vx = -vx and vy = -vy.
ii. If, after updating the position of the ball, it strikes another ball, then you should bounce the ball in another direction. There are many ways to do this and you should choose any reasonable approach. In my version, I reversed the direction of both balls by negating their velocity.
iii. When changing the velocity of a ball, make sure to re-update its position, otherwise, it may lead to repeated and rapid collisions.
b. draw_ball(i): This function takes as input an index i and draws the corresponding ball at this position in the ball list.
c. draw_frame(): This function is called by the animation code and iteratively updates the position of each ball and then draws each ball using, of course, the above two functions.
My animation code looks likes this, where WINDOW_X, WINDOW_Y define the width/height of the drawing window, and the while-loop is set to run forever:
with draw.animate_jupyter(draw_frame, delay=0.05) as anim: while( True ):
D = draw.Drawing(WINDOW_X, WINDOW_Y, origin=’center’ ) # erase canvas
D.append(draw.Rectangle(-WINDOW_X/2,-WINDOW_Y/2,WINDOW_X,WINDOW_Y, fill=’black’))
anim.draw_frame()
4.
5. 6. 7. 8.
9.
Resources
1. bouncingBalls.mov