# BoxBouncer.py

from Processing import *

window(500, 500)

boxes = []
rectMode(CENTER)

class Bouncer:
    def __init__(self, x, y):
        self.x = x          # Position
        self.y = y
        self.vX = 0.0       # Velocity
        self.vY = 0.0
        self.aY = 0.2       # Acceleration
        self.friction = 0.7 # Friction factor

    def step(self):
        if self.y <= height():  # Update position if on sketch
            self.x = self.x + self.vX
            self.y = self.y + self.vY
            self.vY = self.vY + self.aY
        else:               # Bounce when hit
            self.y = height()
            self.vY = -self.friction*self.vY

    def display(self):
        fill(200)
        pushMatrix()
        translate(self.x, self.y)
        rect(0, 0, 20, 20)
        popMatrix()

# Create a new box and add to the master list
def createBox(o, e):
    x, y = mouseX(), mouseY()
    b = Bouncer(x, y)
    boxes.append( b )

# Draw all boxes
def draw(o, e):
    background(0)
    for b in boxes:
        b.step()
        b.display()

# Create a new box whenever the mouse is clicked
onMousePressed += createBox

# Draw all
frameRate(30)
onLoop += draw
loop()
