# bounce4.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):
        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)

    # Update the position and velocity of this BBall 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-10) and self.vy > 0.0:
            self.sy = (h-10)
            self.vy = -fr*self.vy

    def draw(self):
        fill( 255, 0, 0 )
        ellipse( self.sx, self.sy, 20, 20 )

fr = 0.9                    # Losses due to friction
ay = 0.2                    # y acceleration (gravity)

# 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):
    bball = BBall()
    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()
