import appuifw, e32, sensor, math
from sensor import *

fps = 10

canvas = appuifw.Canvas()
appuifw.app.body = canvas
x1, y1 = canvas.size
x1 -= 1
y1 -= 1
# ball position
x, y = x1 / 2, y1 / 2
# ball speed
dx = 0
dy = 0

def recalc():
    global x, y, dx, dy
    # create some drag (linear reduction in speed)
    if abs(dx) > 0.001:
        dx -= 0.2 * dx / abs(dx)
    else:
        dy = 0
    if abs(dy) > 0.001:
        dy -= 0.2 * dy / abs(dy)
    else:
        dy = 0
    # ball acceleration proportional to tilt
    # in two dimentions
    ddx = -math.sin(math.radians(rot.y)) * 5
    ddy = math.cos(math.radians(rot.x)) * 5
    # calculate new speed based on acceleration
    dx += ddx
    dy += ddy
    # calculate new position based on speed
    x += dx 
    y += dy
    # handle bumps
    if x < 0:
        x = 0
        # bouncing with 60% conservation
        # more or less like a rubber ball
        dx = -dx * 0.6
    if x > x1:
        x = x1
        dx = -dx * 0.6
    if y < 0:
        y = 0
        dy = -dy * 0.6
    if y > y1:
        y = y1
        dy = -dy * 0.6

def paint():
    recalc()
    global x, y
    canvas.rectangle([0, 0, x1, y1], fill=0)
    canvas.ellipse([x-20, y-20, x+20, y+20], fill=0x00FFFF)
    timer.after(1.0 / fps, paint)

timer = e32.Ao_timer()
lock = e32.Ao_lock()

def bye():
    lock.signal()

appuifw.app.exit_key_handler = bye

rot = RotationData()
rot.start_listening()

timer.after(1.0 / fps, paint)
lock.wait()
timer.cancel()

rot.stop_listening()

