# bounce5.py
# Demonstrating the use of objects

from Processing import *
window(500, 500)
w = width()
h = height()

# Declare a BBall class that encapsulates all attributes and methods of a Ball
class BBall:
    # The constructor chooses a random starting location and velocity
    # and sets the given diameter and color
    def __init__(self, diam, clr):
        self.sx = random(0.0, w)
        self.sy = random(0.0, 10.0)
        self.vx = random(-3.0, 3.0)
        self.vy = random(0.0, 5.0)
        self.diameter = diam
        self.clr = clr

    # Update the position and velocity of this Ball instance
    def update(self):
        # Equations of Motion
        self.sx = self.sx + self.vx
        self.sy = self.sy + self.vy + + 0.5*ay
        self.vy = self.vy + ay

        # Bounce off walls and floor
        if self.sx <= 0.0 or self.sx >= w:
            self.vx = -fr*self.vx
        if self.sy >= (h-0.5*self.diameter) and self.vy > 0.0:
            self.sy = (h-0.5*self.diameter)
            self.vy = -fr*self.vy

    def draw(self):
        fill( self.clr )
        ellipse( self.sx, self.sy, self.diameter, self.diameter )

fr = 0.9                    # Losses due to friction
ay = 0.2

# Set the number of BBall objects and init the list that holds all
nBalls = 10 # 100
bballs = []

# Create all Ball instances and add to balls list
for i in range(nBalls):
    diam = random(10, 30)
    clr = color( random(255), random(255), random(255) )
    bball = BBall( diam, clr )
    bballs.append( bball )

# Function that updates and draws balls
def draw(o, e):
    background(255)

    # Update and redraw all Ball instances
    for i in range(nBalls):
        bballs[i].update()
        bballs[i].draw()

# Handle loop event and start looping
frameRate(50)
onLoop += draw
startLoop()
